method2testcases
stringlengths
118
3.08k
### Question: DefaultEmailSenderProvider implements EmailSenderProvider { @Override public Optional<SimpleEmailSender> lookupSimpleEmailSenderFor(final String providerType) { assertValidProviderTypeArgument(providerType); return Optional.ofNullable(registeredSimpleEmailSenders.get(providerType)); } DefaultEmailSenderProvider(final List<SimpleEmailSenderRegistry> simpleEmailSenderRegistries, final List<TemplatedEmailSenderRegistry> templatedEmailSenderRegistries); @Override Optional<SimpleEmailSender> lookupSimpleEmailSenderFor(final String providerType); @Override Optional<TemplatedEmailSender> lookupTemplatedEmailSenderFor(final String providerType); }### Answer: @Test public void testLookupSimpleEmailSenderForWithIllegalArguments() { assertThatThrownBy(() -> emailSenderProvider.lookupSimpleEmailSenderFor(null)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> emailSenderProvider.lookupSimpleEmailSenderFor("")) .isInstanceOf(IllegalArgumentException.class); } @Test public void testLookupSimpleEmailSenderMissing() { assertThat(emailSenderProvider.lookupSimpleEmailSenderFor(simpleEmailSenderRegistry.name() + "_test")) .isEmpty(); } @Test public void testLookupSimpleEmailSenderPresent() { assertThat(emailSenderProvider.lookupSimpleEmailSenderFor(simpleEmailSenderRegistry.name())) .isPresent() .contains(simpleEmailSenderRegistry.sender()); }
### Question: DefaultEmailSenderProvider implements EmailSenderProvider { @Override public Optional<TemplatedEmailSender> lookupTemplatedEmailSenderFor(final String providerType) { assertValidProviderTypeArgument(providerType); return Optional.ofNullable(registeredTemplatedEmailSenders.get(providerType)); } DefaultEmailSenderProvider(final List<SimpleEmailSenderRegistry> simpleEmailSenderRegistries, final List<TemplatedEmailSenderRegistry> templatedEmailSenderRegistries); @Override Optional<SimpleEmailSender> lookupSimpleEmailSenderFor(final String providerType); @Override Optional<TemplatedEmailSender> lookupTemplatedEmailSenderFor(final String providerType); }### Answer: @Test public void testLookupTemplatedEmailSenderForWithIllegalArguments() { assertThatThrownBy(() -> emailSenderProvider.lookupTemplatedEmailSenderFor(null)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> emailSenderProvider.lookupTemplatedEmailSenderFor("")) .isInstanceOf(IllegalArgumentException.class); } @Test public void testLookupTemplatedEmailSenderForMissing() { assertThat(emailSenderProvider.lookupTemplatedEmailSenderFor(templatedEmailSenderRegistry.name() + "_test")) .isEmpty(); } @Test public void testLookupTemplatedEmailSenderForSender() { assertThat(emailSenderProvider.lookupTemplatedEmailSenderFor(templatedEmailSenderRegistry.name())) .isPresent() .contains(templatedEmailSenderRegistry.sender()); }
### Question: MandrillSimpleEmailSender implements SimpleEmailSender { @Override public void send(final SimpleEmailMessage message) { Assert.notNull(message,"Null was passed as an argument for parameter 'message'."); mandrillApiCommunicator.sendEmail(message); } MandrillSimpleEmailSender(final MandrillApiCommunicator mandrillApiCommunicator); @Override void send(final SimpleEmailMessage message); }### Answer: @Test public void testSendWithInvalidArguments(){ assertThatThrownBy(()-> mandrillSimpleEmailSender.send(null)) .isInstanceOf(IllegalArgumentException.class); } @Test public void testSend(){ final SimpleEmailMessage message = SimpleEmailMessage.of(uuid(), uuid(), uuid(), uuid(), Collections.emptySet()); mandrillSimpleEmailSender.send(message); verify(mandrillApiCommunicator).sendEmail(message); }
### Question: PushNotificationSubscriptionServiceImpl implements PushNotificationSubscriptionService { @Nonnull @Override public boolean checkIfPushNotificationSubscriptionExistsForUser(@Nonnull final Long userId) { assertUserIdNotNull(userId); LOGGER.debug("Checking if push notification subscription exists for user with id - {}", userId); final User user = userService.getUserById(userId); final PushNotificationSubscription subscription = pushNotificationSubscriptionRepository.findByUser(user); final boolean exists = (subscription != null); LOGGER.debug("Push notification subscription lookup result for user with id - {} is - {}", userId, exists); return exists; } PushNotificationSubscriptionServiceImpl(); @Nonnull @Override boolean checkIfPushNotificationSubscriptionExistsForUser(@Nonnull final Long userId); @Nonnull @Override PushNotificationSubscription getPushNotificationSubscriptionForUser(@Nonnull final Long userId); @Transactional @Nonnull @Override PushNotificationSubscription createPushNotificationSubscription(@Nonnull final Long userId, @Nonnull final PushNotificationSubscriptionDto subscriptionDto); @Nonnull @Override PushNotificationSubscription getPushNotificationSubscriptionById(@Nonnull final Long subscriptionId); PushNotificationSubscriptionRepository getPushNotificationSubscriptionRepository(); void setPushNotificationSubscriptionRepository(final PushNotificationSubscriptionRepository pushNotificationSubscriptionRepository); UserService getUserService(); void setUserService(final UserService userService); }### Answer: @Test public void testCheckIfPushNotificationSubscriptionExistsForUserWithInvalidArguments() { resetAll(); replayAll(); try { pushNotificationSubscriptionService.checkIfPushNotificationSubscriptionExistsForUser(null); fail("Exception should be thrown"); } catch (final IllegalArgumentException ex) { } verifyAll(); } @Test public void testCheckIfPushNotificationSubscriptionExistsForUserWhenItDoesNotExistYet() { final Long userId = 1L; final User user = getServicesImplTestHelper().createUser(); user.setId(userId); resetAll(); expect(userService.getUserById(eq(userId))).andReturn(user).once(); expect(pushNotificationSubscriptionRepository.findByUser(eq(user))).andReturn(null).once(); replayAll(); final boolean result = pushNotificationSubscriptionService.checkIfPushNotificationSubscriptionExistsForUser(userId); assertFalse(result); verifyAll(); }
### Question: AbstractNotificationServiceImpl implements AbstractNotificationService<T> { @Nonnull @Override public T getNotificationById(@Nonnull final Long notificationId) { assertNotificationIdNotNull(notificationId); LOGGER.debug("Getting notification for id - {}, class - {}", notificationId, getInstanceClass()); final T notification = getRepository().findById(notificationId).orElseThrow(() -> new NotificationNotFoundForIdException(notificationId, getInstanceClass())); LOGGER.debug("Successfully retrieved notification for id - {}, notification class - {}", notificationId, getInstanceClass()); return notification; } AbstractNotificationServiceImpl(); @Nonnull @Override T getNotificationById(@Nonnull final Long notificationId); @Transactional @Nonnull @Override T updateNotificationState(@Nonnull final Long notificationId, @Nonnull final NotificationState notificationState); @Transactional @Nonnull @Override T updateProviderExternalUuid(@Nonnull final Long notificationId, @Nonnull final String providerExternalUuid); }### Answer: @Test public void getNotificationByIdWithInvalidArguments() { resetAll(); replayAll(); try { getService().getNotificationById(null); fail("Exception should be thrown"); } catch (final IllegalArgumentException ex) { } verifyAll(); } @Test public void getNotificationById() { final Long notificationId = 1L; final T notification = getInstance(); resetAll(); expect(getRepository().findById(eq(notificationId))).andReturn(Optional.of(notification)).once(); replayAll(); final T result = getService().getNotificationById(notificationId); assertEquals(notification, result); verifyAll(); }
### Question: MandrillTemplatedEmailSender implements TemplatedEmailSender { @Override public void send(final TemplatedEmailMessage message) { Assert.notNull(message,"Null was passed as an argument for parameter 'message'."); mandrillApiCommunicator.sendEmailTemplate(message); } MandrillTemplatedEmailSender(final MandrillApiCommunicator mandrillApiCommunicator); @Override void send(final TemplatedEmailMessage message); }### Answer: @Test public void testSendWithInvalidArguments() { assertThatThrownBy(() -> templatedEmailSender.send(null)) .isInstanceOf(IllegalArgumentException.class); } @Test public void testSend() { final TemplatedEmailMessage message = new TemplatedEmailMessageBuilder( uuid(), uuid(), uuid(), Collections.singletonMap(uuid(), uuid()), Collections.emptySet() ).build(); templatedEmailSender.send(message); verify(mandrillApiCommunicator).sendEmailTemplate(message); }
### Question: RPCQueueMessageHandlerAdapter implements MessageListener { @Override public void onMessage(final Message message) { final String replyPayload = messageHandler.handleMessage(message.getBody()); final String replyTo = message.getMessageProperties().getReplyTo(); if (StringUtils.isNoneBlank(replyTo)) { reply(replyTo, replyPayload, message.getMessageProperties().getCorrelationId()); } } RPCQueueMessageHandlerAdapter(final RPCQueueMessageHandler messageHandler, final RabbitOperations rabbitOperations); @Override void onMessage(final Message message); }### Answer: @Test public void onMessageWithoutReplyTo() { final MessageProperties props = new MessageProperties(); final byte[] payload = UUID.randomUUID().toString().getBytes(); final Message message = new Message(payload, props); expect(messageHandler.handleMessage(aryEq(payload))).andReturn("{\"id\":1}"); replayAll(); rpcQueueMessageHandlerAdapter.onMessage(message); verifyAll(); } @Test public void onMessageWithReplyTo() { final MessageProperties props = new MessageProperties(); final String replyTo = UUID.randomUUID().toString(); props.setReplyTo(replyTo); final byte[] payload = UUID.randomUUID().toString().getBytes(); final Message message = new Message(payload, props); final String handleMessageResult = "{\"id\":1}"; expect(messageHandler.handleMessage(aryEq(payload))).andReturn(handleMessageResult); rabbitOperations.send(eq(replyTo), isA(Message.class)); expectLastCall().andAnswer(() -> { final Message replyToMessage = (Message) getCurrentArguments()[1]; assertThat(replyToMessage.getBody()).isEqualTo(handleMessageResult.getBytes()); return null; }); replayAll(); rpcQueueMessageHandlerAdapter.onMessage(message); verifyAll(); }
### Question: AmazonSnsPushMessageSubscriber implements PushMessageSubscriber { @Override public String registerDeviceEndpointArn(final String userDeviceToken, final String applicationArn) { assertValidDeviceTokenAndAplicationArn(userDeviceToken, applicationArn); return refreshDeviceEndpointArnInternal( executeRegisterDeviceEndpointRequest(userDeviceToken, applicationArn), userDeviceToken, applicationArn ); } AmazonSnsPushMessageSubscriber(final AmazonSnsApiCommunicator amazonSnsApiCommunicator); @Override String refreshDeviceEndpointArn(final String existingDeviceEndpointArn, final String userDeviceToken, final String applicationArn); @Override String registerDeviceEndpointArn(final String userDeviceToken, final String applicationArn); }### Answer: @Test public void testRgisterDeviceEndpointArnWithInvalidArguments() { Assertions.assertThatThrownBy(() -> messageSubscriber.registerDeviceEndpointArn(null, uuid())) .isInstanceOf(IllegalArgumentException.class); Assertions.assertThatThrownBy(() -> messageSubscriber.registerDeviceEndpointArn(uuid(), null)) .isInstanceOf(IllegalArgumentException.class); }
### Question: NotificationQueueConsumerServiceImpl implements NotificationQueueConsumerService, InitializingBean { @Override public void processNotification(@Nonnull final Long notificationId, @Nonnull final Map<String, String> secureProperties) { Assert.notNull(notificationId, "Notification id should not be null"); Assert.notNull(secureProperties, "Secure properties map should not be null"); LOGGER.debug("Processing notification with id - {}", notificationId); notificationProcessingService.processNotification(notificationId, secureProperties); LOGGER.debug("Successfully processed notification with id - {}", notificationId); } NotificationQueueConsumerServiceImpl(); @Override void afterPropertiesSet(); @Override void processNotification(@Nonnull final Long notificationId, @Nonnull final Map<String, String> secureProperties); NotificationProcessingService getNotificationProcessingService(); void setNotificationProcessingService(final NotificationProcessingService notificationProcessingService); }### Answer: @Test public void testProcessSmsNotificationMessageWithInvalidArguments() { resetAll(); replayAll(); try { smsNotificationQueueConsumerService.processNotification(null, Collections.emptyMap()); fail("Exception will be thrown"); } catch (final IllegalArgumentException e) { } try { final Long notificationId = 1L; smsNotificationQueueConsumerService.processNotification(notificationId, null); fail("Exception will be thrown"); } catch (final IllegalArgumentException e) { } verifyAll(); } @Test public void testProcessSmsNotificationMessage() { final Long notificationId = 1L; resetAll(); notificationProcessingService.processNotification(eq(notificationId), eq(Collections.emptyMap())); expectLastCall().once(); replayAll(); smsNotificationQueueConsumerService.processNotification(notificationId, Collections.emptyMap()); verifyAll(); }
### Question: PushNotificationSubscriptionRequestQueueConsumerServiceImpl implements PushNotificationSubscriptionRequestQueueConsumerService { @Override public void processPushNotificationSubscriptionRequest(@Nonnull final Long requestId) { Assert.notNull(requestId, "Push notification subscription request id should not be null"); LOGGER.debug("Processing push notification subscription request with id - {}", requestId); pushNotificationSubscriptionRequestProcessingService.processPushNotificationSubscriptionRequest(requestId); } PushNotificationSubscriptionRequestQueueConsumerServiceImpl(); @Override void processPushNotificationSubscriptionRequest(@Nonnull final Long requestId); PushNotificationSubscriptionRequestProcessingService getPushNotificationSubscriptionRequestProcessingService(); void setPushNotificationSubscriptionRequestProcessingService(final PushNotificationSubscriptionRequestProcessingService pushNotificationSubscriptionRequestProcessingService); }### Answer: @Test public void testProcessPushNotificationSubscriptionRequestWithInvalidArguments() { resetAll(); replayAll(); try { pushNotificationSubscriptionRequestQueueConsumerService.processPushNotificationSubscriptionRequest(null); fail("Exception should be thrown"); } catch (final IllegalArgumentException ex) { } verifyAll(); } @Test public void testProcessPushNotificationSubscriptionRequest() { final Long requestId = 1L; resetAll(); expect(pushNotificationSubscriptionRequestProcessingService.processPushNotificationSubscriptionRequest(requestId)).andReturn(null).once(); replayAll(); pushNotificationSubscriptionRequestQueueConsumerService.processPushNotificationSubscriptionRequest(requestId); verifyAll(); }
### Question: NotificationQueueProducerServiceImpl implements NotificationQueueProducerService { @Override public void processStartSendingNotificationEvent(@Nonnull final Long notificationId, @Nonnull final Map<String, String> secureProperties) { Assert.notNull(notificationId, "Notification id should not be null."); Assert.notNull(secureProperties, "Secure properties should not be null."); logger.debug("Processing notification sending event for notification by id - {}", notificationId); amqpConnectorService.publishMessage(RPCCallType.START_NOTIFICATION_PROCESSING, new NotificationRPCTransferModel(notificationId, secureProperties), NotificationRPCTransferModel.class, new NotificationMessageSendingEventListenerRPCResponseHandler()); } NotificationQueueProducerServiceImpl(); @Override void processStartSendingNotificationEvent(@Nonnull final Long notificationId, @Nonnull final Map<String, String> secureProperties); }### Answer: @Test public void testProcessStartSendingSmsMessageEventWithInvalidArguments() { resetAll(); replayAll(); try { smsNotificationQueueProducerService.processStartSendingNotificationEvent(null, Collections.emptyMap()); fail("Exception will be thrown"); } catch (final IllegalArgumentException e) { } try { final Long notificationId = 1L; smsNotificationQueueProducerService.processStartSendingNotificationEvent(notificationId, null); fail("Exception will be thrown"); } catch (final IllegalArgumentException e) { } verifyAll(); } @Test public void testProcessStartSendingSmsMessageEvent() { final Long notificationId = 1L; resetAll(); amqpConnectorService.publishMessage(eq(RPCCallType.START_NOTIFICATION_PROCESSING), isA(NotificationRPCTransferModel.class), eq(NotificationRPCTransferModel.class), isA(AmqpResponseHandler.class)); expectLastCall().once(); replayAll(); smsNotificationQueueProducerService.processStartSendingNotificationEvent(notificationId, Collections.emptyMap()); verifyAll(); }
### Question: PushNotificationSubscriptionRequestQueueProducerServiceImpl implements PushNotificationSubscriptionRequestQueueProducerService { @Override public void processPushNotificationSubscriptionRequest(@Nonnull final Long requestId) { Assert.notNull(requestId, "Push notification subscription request should not be null"); logger.debug("Processing push notification subscription request with id - {}", requestId); amqpConnectorService.publishMessage(RPCCallType.START_PUSH_NOTIFICATION_SUBSCRIPTION_PROCESSING, new PushNotificationSubscriptionRequestRPCTransferModel(requestId), PushNotificationSubscriptionRequestRPCTransferModel.class, new PushNotificationSubscriptionRPCResponseHandler()); } PushNotificationSubscriptionRequestQueueProducerServiceImpl(); @Override void processPushNotificationSubscriptionRequest(@Nonnull final Long requestId); ApplicationEventDistributionService getApplicationEventDistributionService(); void setApplicationEventDistributionService(final ApplicationEventDistributionService applicationEventDistributionService); AmqpConnectorService getAmqpConnectorService(); void setAmqpConnectorService(final AmqpConnectorService amqpConnectorService); }### Answer: @Test public void testProcessPushNotificationSubscriptionRequestArguments() { resetAll(); replayAll(); try { pushNotificationSubscriptionRequestQueueProducerService.processPushNotificationSubscriptionRequest(null); fail("Exception will be thrown"); } catch (final IllegalArgumentException e) { } verifyAll(); } @Test public void testProcessPushNotificationSubscriptionRequest() { final Long requestId = 1L; resetAll(); amqpConnectorService.publishMessage(eq(RPCCallType.START_PUSH_NOTIFICATION_SUBSCRIPTION_PROCESSING), isA(PushNotificationSubscriptionRequestRPCTransferModel.class), eq(PushNotificationSubscriptionRequestRPCTransferModel.class), isA(AmqpResponseHandler.class)); expectLastCall().once(); replayAll(); pushNotificationSubscriptionRequestQueueProducerService.processPushNotificationSubscriptionRequest(requestId); verifyAll(); }
### Question: DirectNotificationProcessor { private void processNotification(final Long notificationId, final Map<String, String> secureProperties) { CompletableFuture.runAsync(() -> notificationProcessingService.processNotification(notificationId, secureProperties), executor).whenComplete((aVoid, th) -> { if (th != null) { logger.error("Failure when sending notifications directly, notification id is {}", notificationId, th); } else { logger.debug("Notification with id {} was successfully sent.", notificationId); } }); } DirectNotificationProcessor(final NotificationProcessingService notificationProcessingService, final PushNotificationSubscriptionRequestProcessingService pushNotificationSubscriptionRequestProcessingService, final ApplicationEventDistributionService applicationEventDistributionService, final Executor executor); }### Answer: @Test public void testSendingNotification() { final StartSendingNotificationEvent event = new StartSendingNotificationEvent(1L, Collections.singletonMap("testKey", "testValue")); doAnswer(invocation -> { final Runnable runnable = invocation.getArgument(0); runnable.run(); return null; }).when(persistenceUtilityService).runInPersistenceSession(isA(Runnable.class)); applicationEventDistributionService.publishAsynchronousEvent(event); verify(notificationProcessingService).processNotification(event.getNotificationId(), event.getSecureProperties()); }
### Question: AmazonSnsPushMessageSender implements PushMessageSender { @Override public PushMessageSendingResult send(final PushMessage message) { Assert.notNull(message, "Null was passed as an argument for parameter 'message'."); final SendPushNotificationRequestMessageInformation messageInformation = new SendPushNotificationRequestMessageInformation( message.subject(), message.body(), message.properties(), message.platformType() ); return PushMessageSendingResult.of(amazonSnsApiCommunicator .sendPushNotification(messageInformation, message.destinationRouteToken() ) .getMessageId() ); } AmazonSnsPushMessageSender(final AmazonSnsApiCommunicator amazonSnsApiCommunicator); @Override PushMessageSendingResult send(final PushMessage message); }### Answer: @Test public void testSendWithInvalidArguments() { Assertions.assertThatThrownBy(() -> pushMessageSender.send(null)) .isInstanceOf(IllegalArgumentException.class); } @Test public void testSend() { final PushMessage message = PushMessage.of( uuid(), uuid(), uuid(), PlatformType.APNS, Collections.singletonMap(uuid(), uuid())); final String messageId = uuid(); when(amazonSnsApiCommunicator.sendPushNotification(isA(SendPushNotificationRequestMessageInformation.class),eq(message.destinationRouteToken()))).then(invocation -> { assertThat((SendPushNotificationRequestMessageInformation)invocation.getArgument(0)) .hasFieldOrPropertyWithValue("messageSubject",message.subject()) .hasFieldOrPropertyWithValue("messageBody",message.body()) .hasFieldOrPropertyWithValue("messageProperties",message.properties()) .hasFieldOrPropertyWithValue("amazonSNSPlatformType",message.platformType()); assertThat((String)invocation.getArgument(1)).isEqualTo(message.destinationRouteToken()); return new SendPushNotificationResponse(messageId); }); assertThat( pushMessageSender.send(message).messageId()).isEqualTo(messageId); verify(amazonSnsApiCommunicator).sendPushNotification(isA(SendPushNotificationRequestMessageInformation.class),eq(message.destinationRouteToken())); }
### Question: DefaultPermissionChecker implements PermissionChecker { @Override public boolean isPermitted(final String permission, final String accessToken) { Assert.hasText(permission, "Null or empty text was passed as an argument for parameter 'permission'."); Assert.hasText(accessToken, "Null or empty text was passed as an argument for parameter 'accessToken'."); return Try.ofSupplier(() -> resourceServerTokenServices.loadAuthentication(accessToken) ) .filter(authentication -> isPermitted(authentication, permission)) .isSuccess(); } DefaultPermissionChecker(final ResourceServerTokenServices resourceServerTokenServices); @Override boolean isPermitted(final String permission, final String accessToken); }### Answer: @Test public void isPermittedWithInvalidArguments() { assertThatThrownBy(() -> permissionChecker.isPermitted(null, uuid())).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> permissionChecker.isPermitted("", uuid())).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> permissionChecker.isPermitted(uuid(), null)).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> permissionChecker.isPermitted(uuid(), "")).isInstanceOf(IllegalArgumentException.class); } @Test public void isPermittedTrue() { final String permission = uuid(); final String token = uuid(); expect(oAuth2Authentication.getAuthorities()).andReturn(Collections.singleton(new SimpleGrantedAuthority(permission))); expect(resourceServerTokenServices.loadAuthentication(token)).andReturn(oAuth2Authentication); replayAll(); assertThat(permissionChecker.isPermitted(permission, token)).isTrue(); verifyAll(); } @Test public void isPermittedFalse() { final String permission = uuid(); final String token = uuid(); expect(oAuth2Authentication.getAuthorities()).andReturn(Collections.singleton(new SimpleGrantedAuthority(uuid()))); expect(resourceServerTokenServices.loadAuthentication(token)).andReturn(oAuth2Authentication); replayAll(); assertThat(permissionChecker.isPermitted(permission, token)).isFalse(); verifyAll(); }
### Question: DefaultPermissionNameResolver implements PermissionNameResolver { @Override public <R extends NotificationDto<?>> Optional<String> resolve(final R creationRequest) { Assert.notNull(creationRequest, "Null was passed as an argument for parameter 'creationRequest'."); final String permissionNameKey = permissionNameKey(creationRequest); final String permissionName = permissionMappings.getProperty(permissionNameKey(creationRequest)); if (StringUtils.isBlank(permissionName)) { logger.warn("No permission was configured for '{}' notification.", permissionNameKey); return Optional.empty(); } return Optional.of(permissionName); } DefaultPermissionNameResolver(final Properties permissionMappings); @Override Optional<String> resolve(final R creationRequest); }### Answer: @Test public void resolveWithIllegalArguments() { assertThatThrownBy(() -> permissionNameResolver.resolve(null)) .isInstanceOf(IllegalArgumentException.class); } @Test public void resolveForTemplatedNotificationCreation() { final EmailNotificationDto notificationDto = new EmailNotificationDto(); notificationDto.setTemplateName(uuid()); final String permissionName = uuid(); expect(permissionMappings.getProperty(notificationDto.getTemplateName())).andReturn(permissionName); replayAll(); assertThat(permissionNameResolver.resolve(notificationDto).orElseThrow(() -> new AssertionError("PermissionName should be present!"))) .isEqualTo(permissionName); verifyAll(); } @Test public void resolveForNonTemplatedNotificationCreation() { final EmailNotificationDto notificationDto = new EmailNotificationDto(); final String permissionName = uuid(); expect(permissionMappings.getProperty("nontemplated")).andReturn(permissionName); replayAll(); assertThat(permissionNameResolver.resolve(notificationDto).orElseThrow(() -> new AssertionError("PermissionName should be present!"))) .isEqualTo(permissionName); verifyAll(); } @Test public void resolveMissingPermissionMapping() { final EmailNotificationDto notificationDto = new EmailNotificationDto(); notificationDto.setTemplateName(uuid()); expect(permissionMappings.getProperty(notificationDto.getTemplateName())).andReturn(null); replayAll(); assertThat(permissionNameResolver.resolve(notificationDto)).isEmpty(); verifyAll(); }
### Question: NotificationCreationPermissionCheckerAspect { @Around("execution(* com.sflpro.notifier.services.notification..*.create* (..)) " + "&& args(notification,..)") public <N extends NotificationDto<?>> Object aroundNotificationCreation(final ProceedingJoinPoint point, final N notification) throws Throwable { logger.debug("Checking permission for sending {} notification with subject {}", notification.getType(), notification.getSubject()); return executeAuthorized(point, notification); } NotificationCreationPermissionCheckerAspect(final NotificationCreationPermissionChecker permissionChecker); @Around("execution(* com.sflpro.notifier.services.notification..*.create* (..)) " + "&& args(notification,..)") Object aroundNotificationCreation(final ProceedingJoinPoint point, final N notification); @Around("execution(* com.sflpro.notifier.services.notification..*.createNotificationsForUserActiveRecipients* (..)) " + "&& args(userId,pushNotification,..)") Object aroundPushNotificationCreation(final ProceedingJoinPoint point, final Long userId, final PushNotificationDto pushNotification); }### Answer: @Test public void testAroundNotificationCreationNotAllowed() throws Throwable { final NotificationDto notification = getServiceFacadeImplTestHelper().createEmailNotificationDto(); expect(permissionChecker.isNotificationCreationAllowed(notification)).andReturn(false); replayAll(); assertThatThrownBy(() -> notificationCreationPermissionCheckerAspect.aroundNotificationCreation(proceedingJoinPoint, notification)) .isInstanceOf(PermissionDeniedException.class); verifyAll(); } @Test public void testAroundNotificationCreationAllowed() throws Throwable { final NotificationDto notification = getServiceFacadeImplTestHelper().createEmailNotificationDto(); final EmailNotification result = new EmailNotification(); expect(permissionChecker.isNotificationCreationAllowed(notification)).andReturn(true); expect(proceedingJoinPoint.proceed()).andReturn(result); replayAll(); assertThat(notificationCreationPermissionCheckerAspect.aroundNotificationCreation(proceedingJoinPoint, notification)) .isEqualTo(result); verifyAll(); }
### Question: TemplatedEmailMessageBuilder { public TemplatedEmailMessageBuilder withLocale(final Locale locale) { Assert.notNull(locale, "Null was passed as an argument for parameter 'locale'."); this.locale = locale; return this; } TemplatedEmailMessageBuilder(final String from, final String to, final String templateId, final Map<String, ?> variables, final Set<SpiEmailNotificationFileAttachment> fileAttachments); TemplatedEmailMessageBuilder withLocale(final Locale locale); TemplatedEmailMessageBuilder withSubject(final String subject); TemplatedEmailMessage build(); }### Answer: @Test public void withLocaleWithIllegalArgument() { assertThatThrownBy(() -> new TemplatedEmailMessageBuilder( uuid(), uuid(), uuid(), Collections.emptyMap(), Collections.emptySet() ).withLocale(null) ).isInstanceOf(IllegalArgumentException.class); }
### Question: TemplatedEmailMessageBuilder { public TemplatedEmailMessageBuilder withSubject(final String subject) { Assert.notNull(subject, "Null was passed as an argument for parameter 'subject'."); this.subject = subject; return this; } TemplatedEmailMessageBuilder(final String from, final String to, final String templateId, final Map<String, ?> variables, final Set<SpiEmailNotificationFileAttachment> fileAttachments); TemplatedEmailMessageBuilder withLocale(final Locale locale); TemplatedEmailMessageBuilder withSubject(final String subject); TemplatedEmailMessage build(); }### Answer: @Test public void withSubjectWithIllegalArgument() { assertThatThrownBy(() -> new TemplatedEmailMessageBuilder( uuid(), uuid(), uuid(), Collections.emptyMap(), Collections.emptySet() ).withSubject(null) ).isInstanceOf(IllegalArgumentException.class); }
### Question: TemplatedEmailMessageBuilder { public TemplatedEmailMessage build() { return new ImmutableTemplatedEmailMessage( from, to, templateId, subject, variables, locale, fileAttachments); } TemplatedEmailMessageBuilder(final String from, final String to, final String templateId, final Map<String, ?> variables, final Set<SpiEmailNotificationFileAttachment> fileAttachments); TemplatedEmailMessageBuilder withLocale(final Locale locale); TemplatedEmailMessageBuilder withSubject(final String subject); TemplatedEmailMessage build(); }### Answer: @Test public void build() { final String from = uuid(); final String to = uuid(); final String subject = uuid(); final String templateId = uuid(); final Map<String, String> variables = Collections.singletonMap(uuid(), uuid()); final Locale locale = Locale.forLanguageTag("hy"); assertThat(new TemplatedEmailMessageBuilder( from, to, templateId, variables, Collections.emptySet() ) .withSubject(subject) .withLocale(locale).build()) .hasFieldOrPropertyWithValue("from", from) .hasFieldOrPropertyWithValue("to", to) .hasFieldOrPropertyWithValue("subject", subject) .hasFieldOrPropertyWithValue("templateId", templateId) .hasFieldOrPropertyWithValue("locale", locale) .hasFieldOrPropertyWithValue("variables", variables); }
### Question: UserServiceImpl implements UserService { @Transactional @Nonnull @Override public User getOrCreateUserForUuId(final String uuId) { assertUserUuIdNotNull(uuId); logger.debug("Getting or creating user for uuid - {}", uuId); Optional<User> user = userRepository.findByUuId(uuId); if (!user.isPresent()) { logger.debug("No user was found for uuid - {}, creating new one", uuId); return createUser(new UserDto(uuId)); } logger.debug("User for uuid already exists, using it, uuid - {}, user - {}", uuId, user); return user.get(); } UserServiceImpl(); @Nonnull @Override User getUserById(@Nonnull final Long id); @Transactional @Nonnull @Override User createUser(@Nonnull final UserDto userDto); @Nonnull @Override boolean checkIfUserExistsForUuId(@Nonnull final String uuId); @Nonnull @Override User getUserByUuId(@Nonnull final String uuId); @Transactional @Nonnull @Override User getOrCreateUserForUuId(final String uuId); UserRepository getUserRepository(); void setUserRepository(final UserRepository userRepository); }### Answer: @Test public void testGetOrCreateUserForUuIdWithInvalidArguments() { resetAll(); replayAll(); try { userService.getOrCreateUserForUuId(null); fail("Exception should be thrown"); } catch (final IllegalArgumentException ex) { } verifyAll(); } @Test public void testGetOrCreateUserForUuIdWhenUserDoesNotExist() { final String userUuId = "JKIBOBPUHUPGGIO"; resetAll(); expect(userRepository.findByUuId(eq(userUuId))).andReturn(Optional.empty()).times(2); expect(userRepository.save(isA(User.class))).andAnswer(() -> (User) getCurrentArguments()[0]).once(); replayAll(); final User result = userService.getOrCreateUserForUuId(userUuId); getServicesImplTestHelper().assertUser(result, new UserDto(userUuId)); verifyAll(); }
### Question: UserServiceImpl implements UserService { @Nonnull @Override public boolean checkIfUserExistsForUuId(@Nonnull final String uuId) { assertUserUuIdNotNull(uuId); logger.debug("Checking if user exists for uuid - {}", uuId); return userRepository.findByUuId(uuId).isPresent(); } UserServiceImpl(); @Nonnull @Override User getUserById(@Nonnull final Long id); @Transactional @Nonnull @Override User createUser(@Nonnull final UserDto userDto); @Nonnull @Override boolean checkIfUserExistsForUuId(@Nonnull final String uuId); @Nonnull @Override User getUserByUuId(@Nonnull final String uuId); @Transactional @Nonnull @Override User getOrCreateUserForUuId(final String uuId); UserRepository getUserRepository(); void setUserRepository(final UserRepository userRepository); }### Answer: @Test public void testCheckIfUserExistsForUuIdWithInvalidArguments() { resetAll(); replayAll(); try { userService.checkIfUserExistsForUuId(null); fail("Exception should be thrown"); } catch (final IllegalArgumentException ex) { } verifyAll(); } @Test public void testCheckIfUserExistsForUuIdWhenUserDoesNotExist() { final String uuId = "JBYIUYFITYDR^DITDTTYCTK"; resetAll(); expect(userRepository.findByUuId(eq(uuId))).andReturn(Optional.empty()).once(); replayAll(); final boolean result = userService.checkIfUserExistsForUuId(uuId); assertFalse(result); verifyAll(); }
### Question: UserServiceImpl implements UserService { @Nonnull @Override public User getUserById(@Nonnull final Long id) { Assert.notNull(id, "User id should not be null"); logger.debug("Getting user for id - {}", id); final User user = userRepository.findById(id).orElseThrow(() -> new UserNotFoundForIdException(id)); logger.debug("Successfully retrieved user for id - {}, user - {}", user.getId(), user); return user; } UserServiceImpl(); @Nonnull @Override User getUserById(@Nonnull final Long id); @Transactional @Nonnull @Override User createUser(@Nonnull final UserDto userDto); @Nonnull @Override boolean checkIfUserExistsForUuId(@Nonnull final String uuId); @Nonnull @Override User getUserByUuId(@Nonnull final String uuId); @Transactional @Nonnull @Override User getOrCreateUserForUuId(final String uuId); UserRepository getUserRepository(); void setUserRepository(final UserRepository userRepository); }### Answer: @Test public void testGetUserByIdWithInvalidArguments() { resetAll(); replayAll(); try { userService.getUserById(null); fail("Exception should be thrown"); } catch (final IllegalArgumentException ex) { } verifyAll(); } @Test public void testGetUserByIdWithNotExistingUser() { final Long userId = 1L; resetAll(); expect(userRepository.findById(eq(userId))).andReturn(Optional.empty()).once(); replayAll(); try { userService.getUserById(userId); fail("Exception should be thrown"); } catch (final UserNotFoundForIdException ex) { assertUserNotFoundForIdException(ex, userId); } verifyAll(); } @Test public void testGetUserById() { final Long userId = 1L; final User user = getServicesImplTestHelper().createUser(); user.setId(userId); resetAll(); expect(userRepository.findById(eq(userId))).andReturn(Optional.of(user)).once(); replayAll(); final User result = userService.getUserById(userId); assertEquals(user, result); verifyAll(); }
### Question: ApplicationEventDistributionServiceImpl implements ApplicationEventDistributionService { @Override public void publishSynchronousEvent(@Nonnull final ApplicationEvent applicationEvent) { assertApplicationEventNotNull(applicationEvent); LOGGER.debug("Processing Synchronous event - {}", applicationEvent); final Runnable runnable = new EventListenersSynchronousIteratorTask(applicationEvent); runnable.run(); } ApplicationEventDistributionServiceImpl(); @Override void subscribe(@Nonnull final ApplicationEventListener eventListener); @Override void publishAsynchronousEvent(@Nonnull final ApplicationEvent applicationEvent); @Override void publishSynchronousEvent(@Nonnull final ApplicationEvent applicationEvent); PersistenceUtilityService getPersistenceUtilityService(); void setPersistenceUtilityService(final PersistenceUtilityService persistenceUtilityService); void setExecutorService(final ExecutorService executorService); }### Answer: @Test public void testPublishSynchronousEventWithInvalidArguments() { resetAll(); replayAll(); try { applicationEventDistributionService.publishSynchronousEvent(null); fail("Exception should be thrown"); } catch (final IllegalArgumentException ex) { } verifyAll(); } @Test public void testPublishSynchronousEvent() { final Long stationId = 1l; final ApplicationEvent applicationEvent = new MockApplicationEvent(); resetAll(); expect(applicationEventListener.subscribed(eq(applicationEvent))).andReturn(true).once(); applicationEventListener.process(eq(applicationEvent)); expectLastCall().once(); persistenceUtilityService.runInNewTransaction(isA(Runnable.class)); expectLastCall().andAnswer(() -> { final Runnable runnable = (Runnable) getCurrentArguments()[0]; runnable.run(); return null; }).once(); replayAll(); applicationEventDistributionService.subscribe(applicationEventListener); applicationEventDistributionService.publishSynchronousEvent(applicationEvent); verifyAll(); }
### Question: ApplicationEventDistributionServiceImpl implements ApplicationEventDistributionService { @Override public void subscribe(@Nonnull final ApplicationEventListener eventListener) { Assert.notNull(eventListener, "Event listener should not be null"); LOGGER.debug("Subscribing event listener - {}", eventListener); this.eventListeners.add(eventListener); } ApplicationEventDistributionServiceImpl(); @Override void subscribe(@Nonnull final ApplicationEventListener eventListener); @Override void publishAsynchronousEvent(@Nonnull final ApplicationEvent applicationEvent); @Override void publishSynchronousEvent(@Nonnull final ApplicationEvent applicationEvent); PersistenceUtilityService getPersistenceUtilityService(); void setPersistenceUtilityService(final PersistenceUtilityService persistenceUtilityService); void setExecutorService(final ExecutorService executorService); }### Answer: @Test public void testSubscribeWithInvalidArguments() { resetAll(); replayAll(); try { applicationEventDistributionService.subscribe(null); fail("Exception should be thrown"); } catch (final IllegalArgumentException ex) { } verifyAll(); } @Test public void testSubscribe() { resetAll(); replayAll(); applicationEventDistributionService.subscribe(new ApplicationEventListener() { @Nonnull @Override public boolean subscribed(@Nonnull ApplicationEvent applicationEvent) { return false; } @Override public void process(@Nonnull ApplicationEvent applicationEvent) { } }); verifyAll(); }
### Question: ApplicationEventDistributionServiceImpl implements ApplicationEventDistributionService { @Override public void publishAsynchronousEvent(@Nonnull final ApplicationEvent applicationEvent) { assertApplicationEventNotNull(applicationEvent); LOGGER.debug("Processing Asynchronous event - {}", applicationEvent); this.executorService.submit(new EventListenersAsynchronousIteratorTask(applicationEvent)); } ApplicationEventDistributionServiceImpl(); @Override void subscribe(@Nonnull final ApplicationEventListener eventListener); @Override void publishAsynchronousEvent(@Nonnull final ApplicationEvent applicationEvent); @Override void publishSynchronousEvent(@Nonnull final ApplicationEvent applicationEvent); PersistenceUtilityService getPersistenceUtilityService(); void setPersistenceUtilityService(final PersistenceUtilityService persistenceUtilityService); void setExecutorService(final ExecutorService executorService); }### Answer: @Test public void testPublishAsynchronousEventWithInvalidArguments() { resetAll(); replayAll(); try { applicationEventDistributionService.publishAsynchronousEvent(null); fail("Exception should be thrown"); } catch (final IllegalArgumentException ex) { } verifyAll(); } @Test public void testPublishAsynchronousEvent() { final Long stationId = 1l; final ApplicationEvent applicationEvent = new MockApplicationEvent(); resetAll(); expect(executorService.submit(isA(Runnable.class))).andAnswer(() -> { final Runnable runnable = (Runnable) getCurrentArguments()[0]; runnable.run(); return null; }).times(2); expect(applicationEventListener.subscribed(eq(applicationEvent))).andReturn(true).once(); applicationEventListener.process(eq(applicationEvent)); expectLastCall().once(); persistenceUtilityService.runInPersistenceSession(isA(Runnable.class)); expectLastCall().andAnswer(() -> { final Runnable runnable = (Runnable) getCurrentArguments()[0]; runnable.run(); return null; }).once(); replayAll(); applicationEventDistributionService.subscribe(applicationEventListener); applicationEventDistributionService.publishAsynchronousEvent(applicationEvent); verifyAll(); }
### Question: UserDeviceServiceImpl implements UserDeviceService { @Nonnull @Override public boolean checkIfUserDeviceExistsForUuId(@Nonnull final Long userId, @Nonnull final String uuId) { assertUserId(userId); assertUuIdNotNull(uuId); LOGGER.debug("Checking if user device exists for user with id - {}, device uuid - {}", userId, uuId); final User user = userService.getUserById(userId); final UserDevice userDevice = userDeviceRepository.findByUserAndUuId(user, uuId); final boolean exists = (userDevice != null); LOGGER.debug("User device lookup result for user with id - {} and device uuid - {} is - {}", userId, uuId, exists); return exists; } UserDeviceServiceImpl(); @Nonnull @Override UserDevice getUserDeviceById(@Nonnull final Long userDeviceId); @Transactional @Nonnull @Override UserDevice createUserDevice(@Nonnull final Long userId, @Nonnull final UserDeviceDto userDeviceDto); @Nonnull @Override UserDevice getUserDeviceByUuId(@Nonnull final Long userId, @Nonnull final String uuId); @Nonnull @Override boolean checkIfUserDeviceExistsForUuId(@Nonnull final Long userId, @Nonnull final String uuId); @Transactional @Nonnull @Override UserDevice getOrCreateUserDevice(@Nonnull final Long userId, @Nonnull final UserDeviceDto userDeviceDto); UserDeviceRepository getUserDeviceRepository(); void setUserDeviceRepository(final UserDeviceRepository userDeviceRepository); }### Answer: @Test public void testCheckIfUserDeviceExistsForUuId() { final Long userId = 1L; final String deviceUuId = "JBIYITCTUFFVIFIFOYFTII"; resetAll(); replayAll(); try { userDeviceService.checkIfUserDeviceExistsForUuId(null, deviceUuId); fail("Exception should be thrown"); } catch (final IllegalArgumentException ex) { } try { userDeviceService.checkIfUserDeviceExistsForUuId(userId, null); fail("Exception should be thrown"); } catch (final IllegalArgumentException ex) { } verifyAll(); }
### Question: XLMUtils { public static BigDecimal decimalStringToXLM(final String amount) { BigDecimal bd = new BigDecimal(amount); bd = bd.setScale(7, ROUNDING_MODE); return bd; } private XLMUtils(); static BigDecimal decimalStringToXLM(final String amount); static BigDecimal stroopToXLM(final long amount); static long XLMToStroop(final BigDecimal amount); static String formatBalance(final long amount); static String formatBalance(final BigDecimal amount); static String formatBalanceFullPrecision(final long amount); static String formatBalanceFullPrecision(final BigDecimal amount); static boolean isStroopFormat(final String amount); static boolean isPositiveStroopFormat(final String amount); static boolean isNegativeStroopFormat(final String amount); static boolean isDecimalFormat(final String amount); static boolean isPositiveDecimalFormat(final String amount); static boolean isPublicKeyValidFormat(final String publicKey); static boolean isSecretKeyValidFormat(final String secretKey); static boolean isNegativeDecimalFormat(final String amount); static final DecimalFormat XLM_FORMATTER; static final DecimalFormat XLM_PRECISION_FORMATTER; static final BigDecimal STROOPS_IN_XLM; }### Answer: @Test void decimalStringToXLM() { }
### Question: XLMUtils { public static boolean isNegativeDecimalFormat(final String amount) { return amount.matches(negativeDecimalNumberPattern); } private XLMUtils(); static BigDecimal decimalStringToXLM(final String amount); static BigDecimal stroopToXLM(final long amount); static long XLMToStroop(final BigDecimal amount); static String formatBalance(final long amount); static String formatBalance(final BigDecimal amount); static String formatBalanceFullPrecision(final long amount); static String formatBalanceFullPrecision(final BigDecimal amount); static boolean isStroopFormat(final String amount); static boolean isPositiveStroopFormat(final String amount); static boolean isNegativeStroopFormat(final String amount); static boolean isDecimalFormat(final String amount); static boolean isPositiveDecimalFormat(final String amount); static boolean isPublicKeyValidFormat(final String publicKey); static boolean isSecretKeyValidFormat(final String secretKey); static boolean isNegativeDecimalFormat(final String amount); static final DecimalFormat XLM_FORMATTER; static final DecimalFormat XLM_PRECISION_FORMATTER; static final BigDecimal STROOPS_IN_XLM; }### Answer: @Test void isNegativeDecimalFormat() { }
### Question: XLMUtils { public static BigDecimal stroopToXLM(final long amount) { BigDecimal bd = new BigDecimal(amount); bd = bd.setScale(7, ROUNDING_MODE); bd = bd.divide(STROOPS_IN_XLM, ROUNDING_MODE); return bd; } private XLMUtils(); static BigDecimal decimalStringToXLM(final String amount); static BigDecimal stroopToXLM(final long amount); static long XLMToStroop(final BigDecimal amount); static String formatBalance(final long amount); static String formatBalance(final BigDecimal amount); static String formatBalanceFullPrecision(final long amount); static String formatBalanceFullPrecision(final BigDecimal amount); static boolean isStroopFormat(final String amount); static boolean isPositiveStroopFormat(final String amount); static boolean isNegativeStroopFormat(final String amount); static boolean isDecimalFormat(final String amount); static boolean isPositiveDecimalFormat(final String amount); static boolean isPublicKeyValidFormat(final String publicKey); static boolean isSecretKeyValidFormat(final String secretKey); static boolean isNegativeDecimalFormat(final String amount); static final DecimalFormat XLM_FORMATTER; static final DecimalFormat XLM_PRECISION_FORMATTER; static final BigDecimal STROOPS_IN_XLM; }### Answer: @Test void stroopToXLM() { }
### Question: XLMUtils { public static long XLMToStroop(final BigDecimal amount) { return amount.setScale(7, ROUNDING_MODE).multiply(STROOPS_IN_XLM).longValue(); } private XLMUtils(); static BigDecimal decimalStringToXLM(final String amount); static BigDecimal stroopToXLM(final long amount); static long XLMToStroop(final BigDecimal amount); static String formatBalance(final long amount); static String formatBalance(final BigDecimal amount); static String formatBalanceFullPrecision(final long amount); static String formatBalanceFullPrecision(final BigDecimal amount); static boolean isStroopFormat(final String amount); static boolean isPositiveStroopFormat(final String amount); static boolean isNegativeStroopFormat(final String amount); static boolean isDecimalFormat(final String amount); static boolean isPositiveDecimalFormat(final String amount); static boolean isPublicKeyValidFormat(final String publicKey); static boolean isSecretKeyValidFormat(final String secretKey); static boolean isNegativeDecimalFormat(final String amount); static final DecimalFormat XLM_FORMATTER; static final DecimalFormat XLM_PRECISION_FORMATTER; static final BigDecimal STROOPS_IN_XLM; }### Answer: @Test void XLMToStroop() { }
### Question: XLMUtils { public static String formatBalance(final long amount) { return XLM_FORMATTER.format(stroopToXLM(amount)); } private XLMUtils(); static BigDecimal decimalStringToXLM(final String amount); static BigDecimal stroopToXLM(final long amount); static long XLMToStroop(final BigDecimal amount); static String formatBalance(final long amount); static String formatBalance(final BigDecimal amount); static String formatBalanceFullPrecision(final long amount); static String formatBalanceFullPrecision(final BigDecimal amount); static boolean isStroopFormat(final String amount); static boolean isPositiveStroopFormat(final String amount); static boolean isNegativeStroopFormat(final String amount); static boolean isDecimalFormat(final String amount); static boolean isPositiveDecimalFormat(final String amount); static boolean isPublicKeyValidFormat(final String publicKey); static boolean isSecretKeyValidFormat(final String secretKey); static boolean isNegativeDecimalFormat(final String amount); static final DecimalFormat XLM_FORMATTER; static final DecimalFormat XLM_PRECISION_FORMATTER; static final BigDecimal STROOPS_IN_XLM; }### Answer: @Test void formatBalance() { }
### Question: XLMUtils { public static String formatBalanceFullPrecision(final long amount) { return XLM_PRECISION_FORMATTER.format(stroopToXLM(amount)); } private XLMUtils(); static BigDecimal decimalStringToXLM(final String amount); static BigDecimal stroopToXLM(final long amount); static long XLMToStroop(final BigDecimal amount); static String formatBalance(final long amount); static String formatBalance(final BigDecimal amount); static String formatBalanceFullPrecision(final long amount); static String formatBalanceFullPrecision(final BigDecimal amount); static boolean isStroopFormat(final String amount); static boolean isPositiveStroopFormat(final String amount); static boolean isNegativeStroopFormat(final String amount); static boolean isDecimalFormat(final String amount); static boolean isPositiveDecimalFormat(final String amount); static boolean isPublicKeyValidFormat(final String publicKey); static boolean isSecretKeyValidFormat(final String secretKey); static boolean isNegativeDecimalFormat(final String amount); static final DecimalFormat XLM_FORMATTER; static final DecimalFormat XLM_PRECISION_FORMATTER; static final BigDecimal STROOPS_IN_XLM; }### Answer: @Test void formatBalanceFullPrecision() { }
### Question: XLMUtils { public static boolean isStroopFormat(final String amount) { return amount.matches(stroopFormatPattern); } private XLMUtils(); static BigDecimal decimalStringToXLM(final String amount); static BigDecimal stroopToXLM(final long amount); static long XLMToStroop(final BigDecimal amount); static String formatBalance(final long amount); static String formatBalance(final BigDecimal amount); static String formatBalanceFullPrecision(final long amount); static String formatBalanceFullPrecision(final BigDecimal amount); static boolean isStroopFormat(final String amount); static boolean isPositiveStroopFormat(final String amount); static boolean isNegativeStroopFormat(final String amount); static boolean isDecimalFormat(final String amount); static boolean isPositiveDecimalFormat(final String amount); static boolean isPublicKeyValidFormat(final String publicKey); static boolean isSecretKeyValidFormat(final String secretKey); static boolean isNegativeDecimalFormat(final String amount); static final DecimalFormat XLM_FORMATTER; static final DecimalFormat XLM_PRECISION_FORMATTER; static final BigDecimal STROOPS_IN_XLM; }### Answer: @Test void isStroopFormat() { }
### Question: XLMUtils { public static boolean isPositiveStroopFormat(final String amount) { return amount.matches(positiveStroopFormatPattern); } private XLMUtils(); static BigDecimal decimalStringToXLM(final String amount); static BigDecimal stroopToXLM(final long amount); static long XLMToStroop(final BigDecimal amount); static String formatBalance(final long amount); static String formatBalance(final BigDecimal amount); static String formatBalanceFullPrecision(final long amount); static String formatBalanceFullPrecision(final BigDecimal amount); static boolean isStroopFormat(final String amount); static boolean isPositiveStroopFormat(final String amount); static boolean isNegativeStroopFormat(final String amount); static boolean isDecimalFormat(final String amount); static boolean isPositiveDecimalFormat(final String amount); static boolean isPublicKeyValidFormat(final String publicKey); static boolean isSecretKeyValidFormat(final String secretKey); static boolean isNegativeDecimalFormat(final String amount); static final DecimalFormat XLM_FORMATTER; static final DecimalFormat XLM_PRECISION_FORMATTER; static final BigDecimal STROOPS_IN_XLM; }### Answer: @Test void isPositiveStroopFormat() { }
### Question: XLMUtils { public static boolean isNegativeStroopFormat(final String amount) { return amount.matches(negativeStroopFormatPattern); } private XLMUtils(); static BigDecimal decimalStringToXLM(final String amount); static BigDecimal stroopToXLM(final long amount); static long XLMToStroop(final BigDecimal amount); static String formatBalance(final long amount); static String formatBalance(final BigDecimal amount); static String formatBalanceFullPrecision(final long amount); static String formatBalanceFullPrecision(final BigDecimal amount); static boolean isStroopFormat(final String amount); static boolean isPositiveStroopFormat(final String amount); static boolean isNegativeStroopFormat(final String amount); static boolean isDecimalFormat(final String amount); static boolean isPositiveDecimalFormat(final String amount); static boolean isPublicKeyValidFormat(final String publicKey); static boolean isSecretKeyValidFormat(final String secretKey); static boolean isNegativeDecimalFormat(final String amount); static final DecimalFormat XLM_FORMATTER; static final DecimalFormat XLM_PRECISION_FORMATTER; static final BigDecimal STROOPS_IN_XLM; }### Answer: @Test void isNegativeStroopFormat() { }
### Question: XLMUtils { public static boolean isDecimalFormat(final String amount) { return amount.matches(decimalNumberPattern); } private XLMUtils(); static BigDecimal decimalStringToXLM(final String amount); static BigDecimal stroopToXLM(final long amount); static long XLMToStroop(final BigDecimal amount); static String formatBalance(final long amount); static String formatBalance(final BigDecimal amount); static String formatBalanceFullPrecision(final long amount); static String formatBalanceFullPrecision(final BigDecimal amount); static boolean isStroopFormat(final String amount); static boolean isPositiveStroopFormat(final String amount); static boolean isNegativeStroopFormat(final String amount); static boolean isDecimalFormat(final String amount); static boolean isPositiveDecimalFormat(final String amount); static boolean isPublicKeyValidFormat(final String publicKey); static boolean isSecretKeyValidFormat(final String secretKey); static boolean isNegativeDecimalFormat(final String amount); static final DecimalFormat XLM_FORMATTER; static final DecimalFormat XLM_PRECISION_FORMATTER; static final BigDecimal STROOPS_IN_XLM; }### Answer: @Test void isDecimalFormat() { }
### Question: XLMUtils { public static boolean isPositiveDecimalFormat(final String amount) { return amount.matches(positiveDecimalNumberPattern); } private XLMUtils(); static BigDecimal decimalStringToXLM(final String amount); static BigDecimal stroopToXLM(final long amount); static long XLMToStroop(final BigDecimal amount); static String formatBalance(final long amount); static String formatBalance(final BigDecimal amount); static String formatBalanceFullPrecision(final long amount); static String formatBalanceFullPrecision(final BigDecimal amount); static boolean isStroopFormat(final String amount); static boolean isPositiveStroopFormat(final String amount); static boolean isNegativeStroopFormat(final String amount); static boolean isDecimalFormat(final String amount); static boolean isPositiveDecimalFormat(final String amount); static boolean isPublicKeyValidFormat(final String publicKey); static boolean isSecretKeyValidFormat(final String secretKey); static boolean isNegativeDecimalFormat(final String amount); static final DecimalFormat XLM_FORMATTER; static final DecimalFormat XLM_PRECISION_FORMATTER; static final BigDecimal STROOPS_IN_XLM; }### Answer: @Test void isPositiveDecimalFormat() { }
### Question: UseSMT implements Serializable { public static Term checkSat(Term term, TermContext termContext) { SMTOptions options = termContext.global().krunOptions.experimental.smt; if (options.smt != SMTSolver.Z3) { return null; } BuiltinMap.Builder resultBuilder = BuiltinMap.builder(termContext.global()); try { ConjunctiveFormula constraint = ConjunctiveFormula.of(termContext.global()) .add(term, BoolToken.TRUE); com.microsoft.z3.Context context = new com.microsoft.z3.Context(); Solver solver = context.mkSolver(); BoolExpr query = context.parseSMTLIB2String( "(declare-sort IntSeq)" + KILtoSMTLib.translateConstraint(constraint), null, null, null, null); solver.add(query); if(solver.check() == Status.SATISFIABLE){ Model model = solver.getModel(); FuncDecl[] consts = model.getConstDecls(); for(int i=0 ; i < consts.length; ++i){ Expr resultFrg = model.getConstInterp(consts[i]); Variable akey = new Variable(consts[i].getName().toString(), Sort.of(consts[i].getRange().toString())); IntToken avalue = IntToken.of(Integer.parseInt(resultFrg.toString())); resultBuilder.put(akey, avalue); } } context.dispose(); } catch (Z3Exception e) { e.printStackTrace(); } catch (UnsupportedOperationException e) { e.printStackTrace(); } return resultBuilder.build(); } static Term checkSat(Term term, TermContext termContext); }### Answer: @Test @Ignore public void testGetModel() { System.err.println(System.getProperty("java.library.path")); BuiltinMap.Builder builder = new BuiltinMap.Builder(tc.global()); SMTOptions options = new SMTOptions(); assertEquals(builder.build(), UseSMT.checkSat(BoolToken.TRUE, tc)); options.smt = SMTSolver.Z3; }
### Question: Poset implements Serializable { public Set<T> getMaximalLowerBounds(Set<T> subset) { return getClosestBounds(subset, lowerBound); } static Poset<T> create(); java.util.Set<T> getElements(); void addElement(T element); void add(Poset<T> poset); void addRelation(T big, T small); boolean isInRelation(T big, T small); void transitiveClosure(); T getMaxim(T start); T getLUB(Set<T> subset); T getGLB(Set<T> subset); Set<T> getMaximalLowerBounds(Set<T> subset); Set<T> getMinimalUpperBounds(Set<T> subset); List<T> checkForCycles(); }### Answer: @Test public void testGetMaximalLowerBounds() throws Exception { Assert.assertEquals(Sets.newHashSet("B0", "B1"), poset.getMaximalLowerBounds(Sets.newHashSet("A0", "A1", "A2"))); }
### Question: Poset implements Serializable { public Set<T> getMinimalUpperBounds(Set<T> subset) { return getClosestBounds(subset, upperBound); } static Poset<T> create(); java.util.Set<T> getElements(); void addElement(T element); void add(Poset<T> poset); void addRelation(T big, T small); boolean isInRelation(T big, T small); void transitiveClosure(); T getMaxim(T start); T getLUB(Set<T> subset); T getGLB(Set<T> subset); Set<T> getMaximalLowerBounds(Set<T> subset); Set<T> getMinimalUpperBounds(Set<T> subset); List<T> checkForCycles(); }### Answer: @Test public void testGetMinimalUpperBounds() throws Exception { Assert.assertEquals(Sets.newHashSet("A0", "A1", "A2"), poset.getMinimalUpperBounds(Sets.newHashSet("B0", "B1"))); }
### Question: Poset implements Serializable { public T getGLB(Set<T> subset) { return getUniqueBound(subset, lowerBound); } static Poset<T> create(); java.util.Set<T> getElements(); void addElement(T element); void add(Poset<T> poset); void addRelation(T big, T small); boolean isInRelation(T big, T small); void transitiveClosure(); T getMaxim(T start); T getLUB(Set<T> subset); T getGLB(Set<T> subset); Set<T> getMaximalLowerBounds(Set<T> subset); Set<T> getMinimalUpperBounds(Set<T> subset); List<T> checkForCycles(); }### Answer: @Test public void testGetGLB() throws Exception { Assert.assertNull(poset.getGLB(Sets.newHashSet("A0", "A1", "A2"))); poset.addRelation("A0", "GLB"); poset.addRelation("A1", "GLB"); poset.addRelation("A2", "GLB"); poset.addRelation("GLB", "B0"); poset.addRelation("GLB", "B1"); poset.transitiveClosure(); Assert.assertEquals("GLB", poset.getGLB(Sets.newHashSet("A0", "A1", "A2"))); }
### Question: Poset implements Serializable { public T getLUB(Set<T> subset) { return getUniqueBound(subset, upperBound); } static Poset<T> create(); java.util.Set<T> getElements(); void addElement(T element); void add(Poset<T> poset); void addRelation(T big, T small); boolean isInRelation(T big, T small); void transitiveClosure(); T getMaxim(T start); T getLUB(Set<T> subset); T getGLB(Set<T> subset); Set<T> getMaximalLowerBounds(Set<T> subset); Set<T> getMinimalUpperBounds(Set<T> subset); List<T> checkForCycles(); }### Answer: @Test public void testGetLUB() throws Exception { Assert.assertNull(poset.getLUB(Sets.newHashSet("B0", "B1"))); poset.addRelation("A0", "LUB"); poset.addRelation("A1", "LUB"); poset.addRelation("A2", "LUB"); poset.addRelation("LUB", "B0"); poset.addRelation("LUB", "B1"); poset.transitiveClosure(); Assert.assertEquals("LUB", poset.getLUB(Sets.newHashSet("B0", "B1"))); }
### Question: TreeCleanerVisitor extends SetsTransformerWithErrors<ParseFailedException> { @Override public Either<Set<ParseFailedException>, Term> apply(TermCons tc) { if (tc.production().isSyntacticSubsort()) { Either<java.util.Set<ParseFailedException>, Term> rez = new TreeCleanerVisitor2(tc).apply(tc.get(0)); if (rez.isLeft()) return rez; if (tc.production().klabel().isEmpty()) return apply(rez.right().get()); } else { int a = 1 + 2; } if (!tc.production().att().contains("bracket") && tc.production().klabel().isEmpty()) { return Left.apply(Sets.newHashSet(new ParseFailedException(new KException( KException.ExceptionType.ERROR, KException.KExceptionGroup.INNER_PARSER, "Only subsort productions are allowed to have no #klabel attribute", tc.source().get(), tc.location().get())))); } return super.apply(tc); } @Override Either<Set<ParseFailedException>, Term> apply(TermCons tc); @Override Either<Set<ParseFailedException>, Term> apply(KList node); }### Answer: @Test public void testAmb() throws Exception { assertCleanup(Ambiguity.apply(foo), foo); } @Test public void testAmb2() throws Exception { Ambiguity two = Ambiguity.apply(foo, bar); assertCleanup(two, two); } @Test(expected = ParseFailedException.class) public void testNoKLabel() throws Exception { throwFirstLeftException(TermCons.apply(ConsPStack.from(Arrays.asList(bar, foo)), noKLabelProduction, new Location(0, 0, 0, 0), new Source(""))); } @Test public void testKList() throws Exception { assertCleanup(Ambiguity.apply(KList.apply(ConsPStack.singleton(foo))), foo); }
### Question: KompileOptions implements Serializable { public String docStyle() { if (backend == Backends.HTML) { if (docStyle == null) { return "k-definition.css"; } return docStyle; } if (docStyle == null) { return DEFAULT_DOC_STYLE; } if (docStyle.startsWith("+")) { return DEFAULT_DOC_STYLE + "," + docStyle.substring(1); } return docStyle; } String docStyle(); String mainModule(FileUtil files); String syntaxModule(FileUtil files); boolean strict(); @ParametersDelegate transient GlobalOptions global; @ParametersDelegate public OuterParsingOptions outerParsing; @Parameter(names="--backend", description="Choose a backend. <backend> is one of [coq|java|skala]. Each creates the kompiled K definition.") public String backend; @Parameter(names="--transition", listConverter=StringListConverter.class, description="<string> is a whitespace-separated list of tags designating rules to become transitions.") public List<String> transition; static final String DEFAULT_TRANSITION; @ParametersDelegate public Experimental experimental; }### Answer: @Test public void testHtmlDocStyle() { parse("--backend", "html", "foo.k"); assertEquals(Backends.HTML, options.backend); assertEquals("k-definition.css", options.docStyle()); } @Test public void testDocStylePlus() { parse("--doc-style", "+foo", "foo.k"); assertEquals("poster,style=bubble,foo", options.docStyle()); }
### Question: KompileOptions implements Serializable { public String mainModule(FileUtil files) { if (mainModule == null) { return FilenameUtils.getBaseName(outerParsing.mainDefinitionFile(files).getName()).toUpperCase(); } return mainModule; } String docStyle(); String mainModule(FileUtil files); String syntaxModule(FileUtil files); boolean strict(); @ParametersDelegate transient GlobalOptions global; @ParametersDelegate public OuterParsingOptions outerParsing; @Parameter(names="--backend", description="Choose a backend. <backend> is one of [coq|java|skala]. Each creates the kompiled K definition.") public String backend; @Parameter(names="--transition", listConverter=StringListConverter.class, description="<string> is a whitespace-separated list of tags designating rules to become transitions.") public List<String> transition; static final String DEFAULT_TRANSITION; @ParametersDelegate public Experimental experimental; }### Answer: @Test public void testDefaultModuleName() { parse("foo.k"); assertEquals("FOO", options.mainModule(files)); }
### Question: KompileOptions implements Serializable { public String syntaxModule(FileUtil files) { if (syntaxModule == null) { return mainModule(files) + "-SYNTAX"; } return syntaxModule; } String docStyle(); String mainModule(FileUtil files); String syntaxModule(FileUtil files); boolean strict(); @ParametersDelegate transient GlobalOptions global; @ParametersDelegate public OuterParsingOptions outerParsing; @Parameter(names="--backend", description="Choose a backend. <backend> is one of [coq|java|skala]. Each creates the kompiled K definition.") public String backend; @Parameter(names="--transition", listConverter=StringListConverter.class, description="<string> is a whitespace-separated list of tags designating rules to become transitions.") public List<String> transition; static final String DEFAULT_TRANSITION; @ParametersDelegate public Experimental experimental; }### Answer: @Test public void testDefaultSyntaxModuleName() { parse("--main-module", "BAR", "foo.k"); assertEquals("BAR-SYNTAX", options.syntaxModule(files)); }
### Question: ColorUtil { public synchronized static String RgbToAnsi(String rgb, ColorSetting colorSetting, String terminalColor) { initColors(terminalColor); switch(colorSetting) { case OFF: return ""; case ON: return getClosestTerminalCode(colors.get(rgb), ansiColorsToTerminalCodes, colors.get(terminalColor)); case EXTENDED: return getClosestTerminalCode(colors.get(rgb), eightBitColorsToTerminalCodes, colors.get(terminalColor)); default: throw new UnsupportedOperationException("colorSettung: " + colorSetting); } } private ColorUtil(); static Map<String, Color> colors(); synchronized static String RgbToAnsi(String rgb, ColorSetting colorSetting, String terminalColor); static Color getColorByName(String colorName); static final String ANSI_NORMAL; }### Answer: @Test public void testGetColor() { System.setProperty("java.awt.headless", "true"); assertEquals("", ColorUtil.RgbToAnsi("red", ColorSetting.OFF, "black")); assertEquals("\u001b[31m", ColorUtil.RgbToAnsi("red", ColorSetting.ON, "black")); assertEquals("", ColorUtil.RgbToAnsi("red", ColorSetting.OFF, "red")); }
### Question: PowerPointSystem extends SimpleSystemImpl { @Override public SimpleSystem connect(String ... params) throws Exception { return this; } PowerPointSystem(); @Override SimpleNode moveTo(String nodeQuery, String ...keys); @Override SimpleSystem connect(String ... params); @Override Class<? extends SimpleNode> getNodeClass(); }### Answer: @Test public void testPowerPointCreateWikiData() throws Exception { MediaWikiSystem mws = new MediaWikiSystem(); mws.connect("https: String props[] = { "P21", "P22", "P25", "P109", "P569", "P19", "P570", "P20", "P1543" }; SimpleStepNode queenVictoria = TestWikiDataSystem.getQueenVictoria(props); String pptFilePath = "../simplegraph-powerpoint/QueenVictoria.pptx"; SlideShow sls = this.getPPT(pptFilePath, "Queen Victoria"); if (debug) queenVictoria.printNameValues(System.out); String slideprops[] = { "picture", "wikidata_id", "image", "sex or gender", "father", "mother", "date of birth", "place of birth", "date of death", "place of death", "wiki_en", "label_en", "source" }; this.addSlides(sls, mws, queenVictoria, slideprops, 1, debug); sls.save(); TestWikiDataSystem.wikiDataSystem.close(); }
### Question: HtmlSystem extends SimpleSystemImpl { public static HtmlSystem forUrl(String url) throws Exception { HtmlSystem hs = new HtmlSystem(); hs.connect(); HtmlNode htmlNode = (HtmlNode) hs.moveTo(url); htmlNode.recursiveOut("child", Integer.MAX_VALUE); return hs; } HtmlCleaner getCleaner(); @Override SimpleSystem connect(String... connectionParams); @Override SimpleNode moveTo(String nodeQuery, String... keys); @Override Class<? extends SimpleNode> getNodeClass(); static HtmlSystem forUrl(String url); }### Answer: @Test public void testRootNodeAttributes() throws Exception { HtmlSystem hs = HtmlSystem.forUrl("http: HtmlNode htmlNode = (HtmlNode) hs.getStartNode(); assertEquals("html", htmlNode.getRootNode().getName()); if (debug) { htmlNode.forAll(SimpleNode.printDebug); } GraphTraversal<Vertex, Vertex> links = hs.g().V().hasLabel("a"); assertEquals(72, links.count().next().longValue()); links = hs.g().V().hasLabel("a"); if (debug) links.forEachRemaining( link -> System.out.println(link.property("href").value())); } @Test public void testPDFLinks() throws Exception { HtmlSystem hs = HtmlSystem.forUrl( "http: HtmlNode htmlNode = (HtmlNode) hs.getStartNode(); assertEquals("html", htmlNode.getRootNode().getName()); if (debug) { htmlNode.forAll(SimpleNode.printDebug); } GraphTraversal<Vertex, Vertex> links = hs.g().V().hasLabel("a").has("href", RegexPredicate.regex(".*pdf")); assertEquals(4, links.count().next().longValue()); links = hs.g().V().hasLabel("a").has("href", RegexPredicate.regex(".*pdf")); links.forEachRemaining( link -> System.out.println(link.property("href").value())); }
### Question: WikiDataSystem extends SimpleSystemImpl { public static Optional<EntityIdValue> createEntityIdValue(String id) { if (!id.matches("^[QP][0-9]+$")) { return Optional.empty(); } try { Constructor<? extends EntityIdValue> constructor; Class<? extends EntityIdValue> clazz=ItemIdValueImpl.class; if (id.startsWith("P")) { clazz=PropertyIdValueImpl.class; }; constructor=clazz.getDeclaredConstructor(String.class,String.class); constructor.setAccessible(true); EntityIdValue idValue = constructor.newInstance(id, siteiri); return Optional.of(idValue); } catch (Throwable th) { throw new RuntimeException(th); } } WikiDataSystem(); WikiDataSystem(String... languageCodes); private WikiDataSystem(WikibaseDataFetcher wbdf, String... languageCodes); @Override SimpleNode moveTo(String entityId, String... keys); @Override SimpleSystem connect(String... connectionParams); void addLanguage(String languageCode); List<String> getLanguages(); Cache useCache(File cacheFile, String purpose); SimpleNode cache(EntityIdValue entityId, boolean optional); static Optional<EntityIdValue> createEntityIdValue(String id); Optional<SimpleNode> cache(String id, boolean optional); @Override Class<? extends SimpleNode> getNodeClass(); static final String PURPOSE_PROPERTY; static final String PURPOSE_ITEM; static String siteiri; }### Answer: @Test public void testCreateEntityIdValue() { Optional<EntityIdValue> optIdValue = WikiDataSystem.createEntityIdValue("P20"); assertTrue(optIdValue.isPresent()); EntityIdValue idValue = optIdValue.get(); assertEquals("P20", idValue.getId()); if (debug) System.out.println(idValue.getIri()); }
### Question: WikiDataSystem extends SimpleSystemImpl { @Override public SimpleNode moveTo(String entityId, String... keys) { if (wbdf == null) throw new IllegalStateException("not connected"); EntityDocument entityDocument; try { entityDocument = wbdf.getEntityDocument(entityId); } catch (MediaWikiApiErrorException e) { throw new RuntimeException(e); } if (entityDocument == null) throw new IllegalArgumentException( "Entity Document for " + entityId + " not found"); WikiDataNode node = new WikiDataNode(this, entityDocument, keys); if (this.getStartNode() == null) this.setStartNode(node); return node; } WikiDataSystem(); WikiDataSystem(String... languageCodes); private WikiDataSystem(WikibaseDataFetcher wbdf, String... languageCodes); @Override SimpleNode moveTo(String entityId, String... keys); @Override SimpleSystem connect(String... connectionParams); void addLanguage(String languageCode); List<String> getLanguages(); Cache useCache(File cacheFile, String purpose); SimpleNode cache(EntityIdValue entityId, boolean optional); static Optional<EntityIdValue> createEntityIdValue(String id); Optional<SimpleNode> cache(String id, boolean optional); @Override Class<? extends SimpleNode> getNodeClass(); static final String PURPOSE_PROPERTY; static final String PURPOSE_ITEM; static String siteiri; }### Answer: @Test public void testMoveWithoutConnect() { WikiDataSystem lwikiDataSystem = new WikiDataSystem(); Exception foundException = null; try { lwikiDataSystem.moveTo("Q44"); } catch (Exception e) { foundException = e; } assertNotNull(foundException); assertTrue(foundException instanceof java.lang.IllegalStateException); assertEquals("not connected", foundException.getMessage()); }
### Question: JavaSystem extends SimpleSystemImpl { @Override public SimpleNode moveTo(String nodeQuery, String... keys) { SimpleNode javaSourceNode=new JavaSourceNode(this,nodeQuery,keys); optionalStartNode(javaSourceNode); return javaSourceNode; } @Override SimpleSystem connect(String... connectionParams); @Override SimpleNode moveTo(String nodeQuery, String... keys); @Override Class<? extends SimpleNode> getNodeClass(); }### Answer: @Test public void testJavaSystem() { JavaSystem js = new JavaSystem(); JavaSourceNode jsn = (JavaSourceNode) js.moveTo( "../simplegraph-java/src/test/java/com/bitplan/simplegraph/java/TestJavaSystem.java"); debug = true; if (debug) { js.forAll(SimpleNode.printDebug); CompilationUnit cu = jsn.compilationUnit; cu.walk(node -> { System.out.println(node.getClass().getName()); }); } MethodDeclaration md = (MethodDeclaration) js.g().V() .hasLabel("MethodDeclaration").has("name", "testJavaSystem").next() .property("node").value(); assertTrue(md.getComment().isPresent()); assertTrue(md.getComment().get().getContent() .contains("test for the Java System")); } @Test public void testClasses() { JavaSystem js = new JavaSystem(); JavaSourceNode jsn = (JavaSourceNode) js.moveTo( "../simplegraph-java/src/test/java/com/bitplan/simplegraph/java/TestJavaSystem.java"); List<Vertex> cdNodes=js.g().V() .hasLabel("ClassOrInterfaceDeclaration").toList(); assertEquals(2,cdNodes.size()); for (Vertex cdNode:cdNodes) { SimpleNode.printDebug.accept(cdNode); } }
### Question: RandomUtil { public static int randomInt(int fromInclusive, int toExclusive) { return randomInt(fromInclusive, toExclusive, rand); } static void setDefaultRandom(Random rand); static double pseudoRandomFromString(String str); static int randomInt(int fromInclusive, int toExclusive); static int randomInt(int fromInclusive, int toExclusive, Random rand); static T randomMember(Collection<T> col); static int sampleFromCDF(double[] cdf, double p); static int sampleFromCDF(double[] cdf, Random rand); static int sampleFromWeighted(double[] weights, double zero2one); static T randomMember(Collection<T> col, Random rand); static T removeRandom(Collection<T> col); static Map.Entry<K, V> randomEntry(Map<K, V> map); static T randomFromIterator(Iterator<T> iter); static T randomFromIterator(Iterator<T> iter, Random rand); static T removeRandomFast(ArrayList<T> list, Random rand); static ArrayList<T> getSample(Iterable<T> from, int size); static String randomAlphaNumericString(int length, Random rand); static ArrayList<T> getSample(Iterable<T> from, int size, Random rand); static void shuffleIntArray(int[] s, Random rand); static int[] toShuffledIntArray(Collection<Integer> c, Random rand); static void main(String[] args); }### Answer: @Test public void testRandomInt() { for (int i = 0; i < 100; i++) { assertEquals(0, RandomUtil.randomInt(0, 1)); } }
### Question: Lang { public static String RPAD(String str, int len) { if (str == null) { return ""; } int padLen = len - str.length(); if (padLen < 0) { return str.substring(0, len); } StringBuffer sb = new StringBuffer(str); for (int i = 0; i < padLen; i++) { sb.append(' '); } return sb.toString(); } static String RPAD(String str, int len); static String RPAD(String str, char c, int len); static String LPAD(String str, int len); static String LPAD(String str, char c, int len); static String truncate(String str, int len); static T NVL(T first, T second); static int linearSearch(Object[] oArray, Object obj); static int linearSearch(Iterable<?> oArray, Object obj); static boolean isInteger(String s); static boolean isDouble(String s); static String stringList(Object[] array, String separator); static String stringList(Iterable<?> array, String separator); static String dblStr(double x); static String milliStr(long milliseconds); static T setAtFill(List<T> list, int ndx, T item); static String getClasspath(); static void addPath(URLClassLoader urlClassLoader, URL u); static void loadedDependencies(String verboseclassOut); static String stackString(Throwable t); static String urlEncode(String preEncode); static String fullURLEncode(String preEncode); static String urlDecode(String encoded); static T error(Throwable t); static T deepCopy(T obj); static final String pWhite_Space; }### Answer: @Test public void testRPADStringCharInt() { assertEquals("ThisI", Lang.RPAD("ThisIsAString", ' ', 5)); assertEquals("ThisI", Lang.RPAD("ThisI", ' ', 5)); assertEquals("This ", Lang.RPAD("This", ' ', 5)); assertEquals(" ", Lang.RPAD("", ' ', 5)); assertEquals(null, Lang.RPAD(null, ' ', 5)); assertEquals("This#", Lang.RPAD("This", '#', 5)); }
### Question: Lang { public static String LPAD(String str, int len) { return LPAD(str, ' ', len); } static String RPAD(String str, int len); static String RPAD(String str, char c, int len); static String LPAD(String str, int len); static String LPAD(String str, char c, int len); static String truncate(String str, int len); static T NVL(T first, T second); static int linearSearch(Object[] oArray, Object obj); static int linearSearch(Iterable<?> oArray, Object obj); static boolean isInteger(String s); static boolean isDouble(String s); static String stringList(Object[] array, String separator); static String stringList(Iterable<?> array, String separator); static String dblStr(double x); static String milliStr(long milliseconds); static T setAtFill(List<T> list, int ndx, T item); static String getClasspath(); static void addPath(URLClassLoader urlClassLoader, URL u); static void loadedDependencies(String verboseclassOut); static String stackString(Throwable t); static String urlEncode(String preEncode); static String fullURLEncode(String preEncode); static String urlDecode(String encoded); static T error(Throwable t); static T deepCopy(T obj); static final String pWhite_Space; }### Answer: @Test public void testLPADStringInt() { assertEquals("ThisI", Lang.LPAD("ThisIsAString", ' ', 5)); assertEquals("ThisI", Lang.LPAD("ThisI", ' ', 5)); assertEquals(" This", Lang.LPAD("This", ' ', 5)); assertEquals(" ", Lang.LPAD("", ' ', 5)); assertEquals(null, Lang.LPAD(null, ' ', 5)); assertEquals("#This", Lang.LPAD("This", '#', 5)); }
### Question: Lang { public static String truncate(String str, int len) { if (str ==null) { return str; } int tLen = len - str.length(); if (tLen < 0) { return str.substring(0, len); } return str; } static String RPAD(String str, int len); static String RPAD(String str, char c, int len); static String LPAD(String str, int len); static String LPAD(String str, char c, int len); static String truncate(String str, int len); static T NVL(T first, T second); static int linearSearch(Object[] oArray, Object obj); static int linearSearch(Iterable<?> oArray, Object obj); static boolean isInteger(String s); static boolean isDouble(String s); static String stringList(Object[] array, String separator); static String stringList(Iterable<?> array, String separator); static String dblStr(double x); static String milliStr(long milliseconds); static T setAtFill(List<T> list, int ndx, T item); static String getClasspath(); static void addPath(URLClassLoader urlClassLoader, URL u); static void loadedDependencies(String verboseclassOut); static String stackString(Throwable t); static String urlEncode(String preEncode); static String fullURLEncode(String preEncode); static String urlDecode(String encoded); static T error(Throwable t); static T deepCopy(T obj); static final String pWhite_Space; }### Answer: @Test public void testTruncate() { assertEquals("ThisI", Lang.truncate("ThisIsAString", 5)); assertEquals("ThisI", Lang.truncate("ThisI", 5)); assertEquals("", Lang.truncate("", 5)); assertEquals(null, Lang.truncate(null, 5)); }
### Question: Lang { public static <T> T NVL(T first, T second) { return first == null ? second : first; } static String RPAD(String str, int len); static String RPAD(String str, char c, int len); static String LPAD(String str, int len); static String LPAD(String str, char c, int len); static String truncate(String str, int len); static T NVL(T first, T second); static int linearSearch(Object[] oArray, Object obj); static int linearSearch(Iterable<?> oArray, Object obj); static boolean isInteger(String s); static boolean isDouble(String s); static String stringList(Object[] array, String separator); static String stringList(Iterable<?> array, String separator); static String dblStr(double x); static String milliStr(long milliseconds); static T setAtFill(List<T> list, int ndx, T item); static String getClasspath(); static void addPath(URLClassLoader urlClassLoader, URL u); static void loadedDependencies(String verboseclassOut); static String stackString(Throwable t); static String urlEncode(String preEncode); static String fullURLEncode(String preEncode); static String urlDecode(String encoded); static T error(Throwable t); static T deepCopy(T obj); static final String pWhite_Space; }### Answer: @Test public void testNVL() { assertEquals("ThisIsAString", Lang.NVL("ThisIsAString", null)); assertEquals(null, Lang.NVL(null, null)); assertEquals("ThisIsAString", Lang.NVL("ThisIsAString", "ThisIsAnotherString")); }
### Question: Lang { public static int linearSearch(Object[] oArray, Object obj) { if (oArray == null || obj == null) { return -1; } int oLen = oArray.length; for (int i = 0; i < oLen; i++) { if (oArray[i].equals(obj)) { return i; } } return -1; } static String RPAD(String str, int len); static String RPAD(String str, char c, int len); static String LPAD(String str, int len); static String LPAD(String str, char c, int len); static String truncate(String str, int len); static T NVL(T first, T second); static int linearSearch(Object[] oArray, Object obj); static int linearSearch(Iterable<?> oArray, Object obj); static boolean isInteger(String s); static boolean isDouble(String s); static String stringList(Object[] array, String separator); static String stringList(Iterable<?> array, String separator); static String dblStr(double x); static String milliStr(long milliseconds); static T setAtFill(List<T> list, int ndx, T item); static String getClasspath(); static void addPath(URLClassLoader urlClassLoader, URL u); static void loadedDependencies(String verboseclassOut); static String stackString(Throwable t); static String urlEncode(String preEncode); static String fullURLEncode(String preEncode); static String urlDecode(String encoded); static T error(Throwable t); static T deepCopy(T obj); static final String pWhite_Space; }### Answer: @Test public void testLinearSearch() { String[] animals = {"Dog", "Cat", "Mouse", "Dog"}; assertEquals(1, Lang.linearSearch(animals, "Cat")); assertEquals(-1, Lang.linearSearch(animals, "NotAnAnimal")); assertEquals(0, Lang.linearSearch(animals, "Dog")); assertEquals(-1, Lang.linearSearch((Object[])null, "Dog")); assertEquals(-1, Lang.linearSearch(animals, null)); }
### Question: Lang { public static boolean isInteger(String s) { try { Integer.parseInt(s); } catch (NumberFormatException e) { return false; } return true; } static String RPAD(String str, int len); static String RPAD(String str, char c, int len); static String LPAD(String str, int len); static String LPAD(String str, char c, int len); static String truncate(String str, int len); static T NVL(T first, T second); static int linearSearch(Object[] oArray, Object obj); static int linearSearch(Iterable<?> oArray, Object obj); static boolean isInteger(String s); static boolean isDouble(String s); static String stringList(Object[] array, String separator); static String stringList(Iterable<?> array, String separator); static String dblStr(double x); static String milliStr(long milliseconds); static T setAtFill(List<T> list, int ndx, T item); static String getClasspath(); static void addPath(URLClassLoader urlClassLoader, URL u); static void loadedDependencies(String verboseclassOut); static String stackString(Throwable t); static String urlEncode(String preEncode); static String fullURLEncode(String preEncode); static String urlDecode(String encoded); static T error(Throwable t); static T deepCopy(T obj); static final String pWhite_Space; }### Answer: @Test public void testIsInteger() { assertEquals(true, Lang.isInteger("1")); assertEquals(false, Lang.isInteger("1.0")); assertEquals(false, Lang.isInteger("1f")); assertEquals(false, Lang.isInteger(null)); assertEquals(true, Lang.isInteger(String.valueOf(Integer.MAX_VALUE))); assertEquals(true, Lang.isInteger(String.valueOf(Integer.MIN_VALUE))); }
### Question: Lang { public static boolean isDouble(String s) { try { Double.parseDouble(s); return true; } catch (Exception e) { } return false; } static String RPAD(String str, int len); static String RPAD(String str, char c, int len); static String LPAD(String str, int len); static String LPAD(String str, char c, int len); static String truncate(String str, int len); static T NVL(T first, T second); static int linearSearch(Object[] oArray, Object obj); static int linearSearch(Iterable<?> oArray, Object obj); static boolean isInteger(String s); static boolean isDouble(String s); static String stringList(Object[] array, String separator); static String stringList(Iterable<?> array, String separator); static String dblStr(double x); static String milliStr(long milliseconds); static T setAtFill(List<T> list, int ndx, T item); static String getClasspath(); static void addPath(URLClassLoader urlClassLoader, URL u); static void loadedDependencies(String verboseclassOut); static String stackString(Throwable t); static String urlEncode(String preEncode); static String fullURLEncode(String preEncode); static String urlDecode(String encoded); static T error(Throwable t); static T deepCopy(T obj); static final String pWhite_Space; }### Answer: @Test public void testIsDouble() { assertEquals(true, Lang.isDouble("1")); assertEquals(true, Lang.isDouble("1.0")); assertEquals(true, Lang.isDouble("1f")); assertEquals(true, Lang.isDouble("1d")); assertEquals(false, Lang.isDouble(null)); assertEquals(true, Lang.isDouble(String.valueOf(Double.MAX_VALUE))); assertEquals(true, Lang.isDouble(String.valueOf(Double.MIN_VALUE))); }
### Question: RandomUtil { public static <K, V> Map.Entry<K, V> randomEntry(Map<K, V> map) { if (map == null || map.size() == 0) { return null; } int index = randomInt(0, map.size()); int counter = 0; Map.Entry<K, V> ret = null; for (Map.Entry<K, V> entry : map.entrySet()) { if (counter == index) { ret = entry; } counter++; } return ret; } static void setDefaultRandom(Random rand); static double pseudoRandomFromString(String str); static int randomInt(int fromInclusive, int toExclusive); static int randomInt(int fromInclusive, int toExclusive, Random rand); static T randomMember(Collection<T> col); static int sampleFromCDF(double[] cdf, double p); static int sampleFromCDF(double[] cdf, Random rand); static int sampleFromWeighted(double[] weights, double zero2one); static T randomMember(Collection<T> col, Random rand); static T removeRandom(Collection<T> col); static Map.Entry<K, V> randomEntry(Map<K, V> map); static T randomFromIterator(Iterator<T> iter); static T randomFromIterator(Iterator<T> iter, Random rand); static T removeRandomFast(ArrayList<T> list, Random rand); static ArrayList<T> getSample(Iterable<T> from, int size); static String randomAlphaNumericString(int length, Random rand); static ArrayList<T> getSample(Iterable<T> from, int size, Random rand); static void shuffleIntArray(int[] s, Random rand); static int[] toShuffledIntArray(Collection<Integer> c, Random rand); static void main(String[] args); }### Answer: @Test public void testRandomEntry() { Map<Integer, Integer> integers = new HashMap<Integer, Integer>(); for (int i = 0; i < 10000; i++) { integers.put(i,i); } for (int i = 0; i < 10000; i++) { assertTrue(integers.containsKey(RandomUtil.randomEntry(integers).getKey())); } }
### Question: PropertyLoader { public static Properties loadProperties(String name) { return getProperties(getClassLoader(), getName(name)); } static void setFieldsFromProperties(Object obj, Map<Object,Object> props); static String toString(Properties props); static Properties fromString(String propStr); static Properties getPropertiesWithSubstitutions(String name); static Properties propertiesWithSubstitutions(Properties props); static Properties loadProperties(String name); static URL getUrl(String name); static void main(String[] args); static final String DFLT_ETN; }### Answer: @Test public void testLoadProperties() { assertEquals("value", PropertyLoader.loadProperties("com.ibm.research.ai.ki.util.1").get("name")); assertEquals("value", PropertyLoader.loadProperties("/com/ibm/research/ai/ki/util/1").get("name")); }
### Question: EventBus { public void subscribe(Class<? extends Subscriber> subscriber) { try { monitor.lock(); if (subscriber.isAnnotationPresent(InterestedEvent.class)) { InterestedEvent ann = subscriber.getAnnotation(InterestedEvent.class); for (Class<? extends Event> interestedEvent : ann.events()) { if (!subscribers.containsKey(interestedEvent)) { subscribers.put(interestedEvent, new LinkedList<Class<? extends Subscriber>>()); } subscribers.get(interestedEvent).add(subscriber); } } } finally { monitor.unlock(); } } void setEventPublisher(EventPublisher eventPublisher); void subscribe(Class<? extends Subscriber> subscriber); @SuppressWarnings("unchecked") void publish(Event event); }### Answer: @Test public void subscribeTest() { replay(this.consumerOne, this.consumerTwo, this.publisher); assertFalse(bus.subscribers.containsKey(EventOne.class)); assertFalse(bus.subscribers.containsKey(EventTwo.class)); bus.subscribe(SubscriberOne.class); bus.subscribe(SubscriberTwo.class); assertTrue(bus.subscribers.containsKey(EventOne.class)); assertEquals(1, bus.subscribers.get(EventOne.class).size()); assertTrue(bus.subscribers.containsKey(EventTwo.class)); assertEquals(2, bus.subscribers.get(EventTwo.class).size()); verify(this.consumerOne, this.consumerTwo, this.publisher); }
### Question: EventBus { @SuppressWarnings("unchecked") public void publish(Event event) { try { monitor.lock(); if (subscribers.containsKey(event.getClass())) { eventPublisher.publish((LinkedList<Class<? extends Subscriber>>) subscribers.get(event.getClass()).clone(), event); } } finally { monitor.unlock(); } } void setEventPublisher(EventPublisher eventPublisher); void subscribe(Class<? extends Subscriber> subscriber); @SuppressWarnings("unchecked") void publish(Event event); }### Answer: @SuppressWarnings("unchecked") @Test public void publishTest() { Event event = new EventTwo(); this.publisher.publish(Arrays.asList(SubscriberOne.class, SubscriberTwo.class), event); replay(this.consumerOne, this.consumerTwo, this.publisher); bus.subscribe(SubscriberOne.class); bus.subscribe(SubscriberTwo.class); bus.publish(event); verify(this.consumerOne, this.consumerTwo, this.publisher); }
### Question: GitPathResolver { String relativize(String absoluteNativePath) { if (!absoluteNativePath.startsWith(repositoryRootDir)) { throw new RuntimeException("Cannot relativize path '" + absoluteNativePath + "' to directory '" + repositoryRootDir + "'"); } String result = absoluteNativePath.substring(repositoryRootDir.length()); if (nativePathSeparator != CANONICAL_PATH_SEPARATOR) { result = result.replace(nativePathSeparator, CANONICAL_PATH_SEPARATOR); } return result; } GitPathResolver(String repositoryRootDir); GitPathResolver(String repositoryRootDir, char nativePathSeparator); String relativize(File path); }### Answer: @Test public void relativize() throws Exception { assertRelativized("/path/to/my/git/repo", '/', "/path/to/my/git/repo/dir/file.txt", "dir/file.txt"); assertRelativized("/path/to/my/git/repo/", '/', "/path/to/my/git/repo/dir/file.txt", "dir/file.txt"); assertFail("/path/to/my/git/repo/", '/', "/path/to/other/git/repo/dir/file.txt"); assertRelativized("c:\\path\\to\\my\\repo", '\\', "c:\\path\\to\\my\\repo\\dir\\file.txt", "dir/file.txt"); assertRelativized("c:\\path\\to\\my\\repo\\", '\\', "c:\\path\\to\\my\\repo\\dir\\file.txt", "dir/file.txt"); assertRelativized("\\\\path\\to\\my\\repo", '\\', "\\\\path\\to\\my\\repo\\dir\\file.txt", "dir/file.txt"); assertRelativized("\\\\path\\to\\my\\repo\\", '\\', "\\\\path\\to\\my\\repo\\dir\\file.txt", "dir/file.txt"); assertFail("c:\\path\\to\\my\\repo\\", '\\', "c:\\path\\to\\other\\repo\\dir\\file.txt"); }
### Question: Document { public boolean hasHeader(Header header, boolean strictCheck) { if (!strictCheck) { try { String fileHeader = readFirstLines(file, header.getLineCount() + 10, encoding); String fileHeaderOneLine = remove(fileHeader, headerDefinition.getFirstLine().trim(), headerDefinition.getEndLine().trim(), headerDefinition.getBeforeEachLine().trim(), "\n", "\r", "\t", " "); String headerOnOnelIne = mergeProperties(header.asOneLineString()); return fileHeaderOneLine.contains(remove(headerOnOnelIne, headerDefinition.getFirstLine().trim(), headerDefinition.getEndLine().trim(), headerDefinition.getBeforeEachLine().trim())); } catch (IOException e) { throw new IllegalStateException("Cannot read file " + getFilePath() + ". Cause: " + e.getMessage(), e); } } try { return header.isMatchForText(this, headerDefinition, true, encoding); } catch (IOException e) { throw new IllegalStateException("Cannot read file " + getFilePath() + ". Cause: " + e.getMessage(), e); } } Document(File file, HeaderDefinition headerDefinition, String encoding, String[] keywords, DocumentPropertiesLoader documentPropertiesLoader); HeaderDefinition getHeaderDefinition(); File getFile(); String getFilePath(); String getEncoding(); boolean isNotSupported(); boolean hasHeader(Header header, boolean strictCheck); void updateHeader(Header header); String mergeProperties(String str); void save(); void saveTo(File dest); String getContent(); void removeHeader(); boolean is(Header header); void parseHeader(); boolean headerDetected(); @Override String toString(); }### Answer: @Test public void test_hasHeader() throws Exception { Document doc = new Document( new File("src/test/resources/doc/doc1.txt"), DocumentType.TXT.getDefaultHeaderType().getDefinition(), System.getProperty("file.encoding"), new String[]{"copyright"}, loader); assertFalse(doc.hasHeader(header, true)); }
### Question: HeaderSource { public static HeaderSource of(String headerPath, String encoding, ResourceFinder finder) { return of(null, encoding, finder); } HeaderSource(String content, boolean inline); static HeaderSource of(String headerPath, String encoding, ResourceFinder finder); static HeaderSource of(Multi multi, String inlineHeader, String headerPath, String encoding, ResourceFinder finder); String getContent(); boolean isInline(); abstract boolean isFromUrl(URL location); }### Answer: @Test(expected=IllegalArgumentException.class) public void testOfNulls() { HeaderSource.of(null, null, null, "utf-8", finder); } @Test(expected=IllegalArgumentException.class) public void testOfEmptyAndNull() { HeaderSource.of(null, "", null, "utf-8", finder); } @Test(expected=IllegalArgumentException.class) public void testOfMultiNulls() { HeaderSource.of(new Multi(), null, null, "utf-8", finder); } @Test(expected=IllegalArgumentException.class) public void testOfMultiEmptyAndNull() { final Multi multi = new Multi(); multi.setInlineHeaders(new String[0]); HeaderSource.of(multi, "", null, "utf-8", finder); }
### Question: HeaderParser { public boolean gotAnyHeader() { return existingHeader; } HeaderParser(FileContent fileContent, HeaderDefinition headerDefinition, String[] keywords); int getBeginPosition(); int getEndPosition(); boolean gotAnyHeader(); FileContent getFileContent(); HeaderDefinition getHeaderDefinition(); }### Answer: @Test public void test_no_header() throws Exception { HeaderParser parser = new HeaderParser(new FileContent(new File("src/test/resources/doc/doc1.txt"), System.getProperty("file.encoding")), HeaderType.TEXT.getDefinition(), new String[]{"copyright"}); assertFalse(parser.gotAnyHeader()); } @Test public void test_parsing_xml3() throws Exception { HeaderParser parser = new HeaderParser(new FileContent(new File("src/test/resources/doc/doc6.xml"), System.getProperty("file.encoding")), HeaderType.XML_STYLE.getDefinition(), new String[]{"copyright"}); assertFalse(parser.gotAnyHeader()); } @Test public void test_parsing_xml4() throws Exception { HeaderParser parser = new HeaderParser(new FileContent(new File("src/test/resources/doc/doc7.xml"), System.getProperty("file.encoding")), HeaderType.XML_STYLE.getDefinition(), new String[]{"copyright"}); assertFalse(parser.gotAnyHeader()); } @Test public void test_parsing_xml5() throws Exception { HeaderParser parser = new HeaderParser(new FileContent(new File("src/test/resources/doc/doc8.xml"), System.getProperty("file.encoding")), HeaderType.XML_STYLE.getDefinition(), new String[]{"copyright"}); assertFalse(parser.gotAnyHeader()); }
### Question: Document { public boolean is(Header header) { try { return header.getLocation().isFromUrl(this.file.toURI().toURL()); } catch (Exception e) { throw new IllegalStateException("Error comparing document " + this.file + " with file " + file + ". Cause: " + e.getMessage(), e); } } Document(File file, HeaderDefinition headerDefinition, String encoding, String[] keywords, DocumentPropertiesLoader documentPropertiesLoader); HeaderDefinition getHeaderDefinition(); File getFile(); String getFilePath(); String getEncoding(); boolean isNotSupported(); boolean hasHeader(Header header, boolean strictCheck); void updateHeader(Header header); String mergeProperties(String str); void save(); void saveTo(File dest); String getContent(); void removeHeader(); boolean is(Header header); void parseHeader(); boolean headerDetected(); @Override String toString(); }### Answer: @Test public void test_isHeader() throws Exception { Document doc = new Document( new File("src/test/resources/doc/doc1.txt"), DocumentType.TXT.getDefaultHeaderType().getDefinition(), System.getProperty("file.encoding"), new String[]{"copyright"}, loader); assertFalse(doc.is(header)); doc = new Document( new File("src/test/resources/test-header1.txt"), DocumentType.TXT.getDefaultHeaderType().getDefinition(), System.getProperty("file.encoding"), new String[]{"copyright"}, loader); assertTrue(doc.is(header)); }
### Question: FileUtils { public static String readFirstLines(File file, int lineCount, String encoding) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); try { String line; StringBuilder sb = new StringBuilder(); while (lineCount > 0 && (line = reader.readLine()) != null) { lineCount--; sb.append(line).append("\n"); } return sb.toString(); } finally { reader.close(); } } private FileUtils(); static void write(File file, String content, String encoding); static String read(URL location, String encoding, Map<String, String> properties); static String read(URL location, String encoding); static String[] read(final URL[] locations, final String encoding); static String read(File file, String encoding); static String readFirstLines(File file, int lineCount, String encoding); static String remove(String str, String... chars); static void copyFileToFolder(File file, File folder); static Path asPath(final File file); }### Answer: @Test public void test_read_first_lines() throws Exception { String s = FileUtils.readFirstLines(new File("src/test/data/compileCP/test2.txt"), 3, "ISO-8859-1"); assertTrue(s.contains("c")); assertFalse(s.contains("d")); }
### Question: FiberRestAdapterBuilder extends RestAdapter.Builder { @Override public RestAdapter build() { if (okHttpClient != null) { super.setClient(providerFor(new OkClient(okHttpClient))); } else { if (httpClient == null) this.httpClient = FiberHttpClientBuilder.create().setUserAgent("").build(); super.setClient(providerFor(new ApacheClient(httpClient))); } return super.build(); } @Override final RestAdapter.Builder setClient(Client.Provider clientProvider); @Override final RestAdapter.Builder setClient(Client client); final RestAdapter.Builder setClient(FiberHttpClient client); final RestAdapter.Builder setClient(FiberOkHttpClient client); @Override RestAdapter build(); }### Answer: @Test public void testGet() throws IOException, InterruptedException, Exception { final MyGitHub github = new FiberRestAdapterBuilder().setEndpoint("http: new Fiber<Void>(new MyGitHubRunner(github)).start().join(); }
### Question: FiberDataSource implements DataSource { @Override @Suspendable public FiberConnection getConnection() throws SQLException { return JDBCFiberAsync.exec(executor, new CheckedCallable<FiberConnection, SQLException>() { @Override public FiberConnection call() throws SQLException { return new FiberConnection(ds.getConnection(), executor); } }); } protected FiberDataSource(final DataSource ds, final ExecutorService exec); static DataSource wrap(final DataSource ds, final ExecutorService executor); static DataSource wrap(final DataSource ds, final int numThreads); static DataSource wrap(final DataSource ds); @Override @Suspendable FiberConnection getConnection(); @Override @Suspendable FiberConnection getConnection(final String username, final String password); @Override @Suspendable PrintWriter getLogWriter(); @Override @Suspendable void setLogWriter(final PrintWriter out); @Override @Suspendable void setLoginTimeout(final int seconds); @Override @Suspendable int getLoginTimeout(); @Override Logger getParentLogger(); @Override T unwrap(final Class<T> iface); @Override boolean isWrapperFor(final Class<?> iface); @Override int hashCode(); @Override @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") boolean equals(final Object obj); @Override String toString(); }### Answer: @Test public void testGetConnection() throws IOException, InterruptedException, Exception { final DataSource fiberDs = FiberDataSource.wrap(ds); new Fiber<Void>(new SuspendableRunnable() { @Override public void run() throws SuspendExecution, InterruptedException { try { Connection conn = fiberDs.getConnection(); conn.close(); } catch (SQLException ex) { fail(ex.getMessage()); } } }).start().join(); }
### Question: WXRefresh extends WXBaseRefresh implements WXSwipeLayout.WXOnRefreshListener { @Override public void onRefresh() { if(isDestoryed()){ return; } ImmutableDomObject dom; if ((dom = getDomObject())!= null && dom.getEvents().contains(Constants.Event.ONREFRESH)) { fireEvent(Constants.Event.ONREFRESH); } } @Deprecated WXRefresh(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy); WXRefresh(WXSDKInstance instance, WXDomObject node, WXVContainer parent, boolean lazy); @Override void onRefresh(); @Override int getLayoutTopOffsetForSibling(); @Override void onPullingDown(float dy, int pullOutDistance, float viewHeight); @WXComponentProp(name = Constants.Name.DISPLAY) void setDisplay(String display); static final String HIDE; }### Answer: @Test public void testOnRefresh() throws Exception { component.onRefresh(); }
### Question: WXUtils { public static int getInt(Object value) { return getInteger(value, 0); } static boolean isUiThread(); static boolean isUndefined(float value); static float getFloat(Object value); static Float getFloat(Object value, @Nullable Float df); static float fastGetFloat(String raw, int precision); static float fastGetFloat(String raw); static int getInt(Object value); static Integer getInteger(@Nullable Object value, @Nullable Integer df); @Deprecated static long getLong(Object value); @Deprecated static double getDouble(Object value); static boolean isTabletDevice(); static Boolean getBoolean(@Nullable Object value, @Nullable Boolean df); static long getAvailMemory(Context context); static String getString(@Nullable Object value,@Nullable String df); static int parseUnitOrPercent(String raw, int unit); static final char PERCENT; }### Answer: @Test public void testGetInt() throws Exception { int test_int = WXUtils.getInt("23px"); assertEquals(23, test_int); } @Test public void testGetIntWX() throws Exception { Integer test_int = WXUtils.getInt("100wx"); Integer want = (int)(100 * TEST_DENSITY * TEST_VIEW_PORT / TEST_SCREEN_WIDTH); assertEquals(test_int, want); test_int = WXUtils.getInt("100px"); want = 100; assertEquals(test_int, want); test_int = WXUtils.getInt("100"); want = 100; assertEquals(test_int, want); test_int = WXUtils.getInt(100); want = 100; assertEquals(test_int, want); test_int = WXUtils.getInt(100.1); want = 0; assertEquals(test_int, want); }
### Question: WXUtils { @Deprecated public static long getLong(Object value) { if (value == null) { return 0; } long result = 0; String temp = value.toString().trim(); if (temp.endsWith("wx")) { try { return (long)transferWx(temp); } catch (NumberFormatException e) { WXLogUtils.e("Argument format error! value is " + value, e); } catch (Exception e) { WXLogUtils.e("Argument error! value is " + value, e); } }else if (temp.endsWith("px")) { try { temp = temp.substring(0, temp.indexOf("px")); return Long.parseLong(temp); } catch (NumberFormatException nfe) { WXLogUtils.e("Argument format error! value is " + value, nfe); } catch (Exception e) { WXLogUtils.e("Argument error! value is " + value, e); } }else { try { return Long.parseLong(temp); } catch (NumberFormatException nfe) { WXLogUtils.e("Argument format error! value is " + value, nfe); } catch (Exception e) { WXLogUtils.e("Argument error! value is " + value, e); } } return result; } static boolean isUiThread(); static boolean isUndefined(float value); static float getFloat(Object value); static Float getFloat(Object value, @Nullable Float df); static float fastGetFloat(String raw, int precision); static float fastGetFloat(String raw); static int getInt(Object value); static Integer getInteger(@Nullable Object value, @Nullable Integer df); @Deprecated static long getLong(Object value); @Deprecated static double getDouble(Object value); static boolean isTabletDevice(); static Boolean getBoolean(@Nullable Object value, @Nullable Boolean df); static long getAvailMemory(Context context); static String getString(@Nullable Object value,@Nullable String df); static int parseUnitOrPercent(String raw, int unit); static final char PERCENT; }### Answer: @Test public void testGetLong() throws Exception { long test_long = WXUtils.getLong("8098px"); assertEquals(8098, test_long); }
### Question: MathUtils { public static Integer sum(List<Integer> vals) { var sum = vals.stream().reduce(Integer::sum); return sum.get(); } static Integer sum(List<Integer> vals); static List<Integer> positive(List<Integer> vals); static List<Integer> negative(List<Integer> vals); }### Answer: @Test @DisplayName("testing sum of values") void sumTest() { var sum = MathUtils.sum(vals); assertEquals(Integer.valueOf(2), sum); }
### Question: HelloService { public String getMessage() { return "Hello there!"; } String getMessage(); }### Answer: @Test void testHelloMessage() { when(helloService.getMessage()).thenReturn("Hello!"); assertEquals(helloService.getMessage(), "Hello!"); }
### Question: MessageService { public String getMessage(String message, LocalDateTime dateTime) { return String.format("%s %s", message, dateTime); } String getMessage(String message, LocalDateTime dateTime); }### Answer: @Test void testGetMessage() { messageService.getMessage("Hello!", LocalDateTime.of(2019, 8, 20, 20, 18)); Mockito.verify(messageService).getMessage(captor1.capture(), captor2.capture()); assertEquals("Hello!", captor1.getValue()); assertEquals(LocalDateTime.of(2019, 8, 20, 20, 18), captor2.getValue()); }
### Question: MathUtils { public static List<Integer> positive(List<Integer> vals) { return vals.stream().filter(val -> val > 0).collect(Collectors.toList()); } static Integer sum(List<Integer> vals); static List<Integer> positive(List<Integer> vals); static List<Integer> negative(List<Integer> vals); }### Answer: @Test @DisplayName("should get positive values") void positiveTest() { var positiveValues = MathUtils.positive(vals); assertEquals(positiveValues, List.of(2, 1, 3)); }
### Question: MathUtils { public static List<Integer> negative(List<Integer> vals) { return vals.stream().filter(val -> val < 0).collect(Collectors.toList()); } static Integer sum(List<Integer> vals); static List<Integer> positive(List<Integer> vals); static List<Integer> negative(List<Integer> vals); }### Answer: @Test @DisplayName("should get negative values") void negativeTest() { var negativeValues = MathUtils.negative(vals); assertEquals(negativeValues, List.of(-2, -1, -1)); }
### Question: ColorBag { public void add(String color) { colors.add(color); } void add(String color); void remove(String color); List<String> toList(); boolean contains(String color); int size(); }### Answer: @Test @DisplayName("added color value should be in bag") void add() { var newColor = "pink"; colorBag.add(newColor); assertTrue(colorBag.contains(newColor), "failure - added colour not it the bag"); }
### Question: ColorBag { public void remove(String color) { colors.remove(color); } void add(String color); void remove(String color); List<String> toList(); boolean contains(String color); int size(); }### Answer: @Test @DisplayName("removed color should not be in bag") void remove() { var color = "green"; colorBag.remove(color); assertFalse(colorBag.contains(color), "failure - removed color still in bag"); }
### Question: ColorBag { public List<String> toList() { return new ArrayList<>(colors); } void add(String color); void remove(String color); List<String> toList(); boolean contains(String color); int size(); }### Answer: @Test @DisplayName("color bag should be transformed into List") void toList() { var myList = Arrays.asList("red","green", "yellow", "blue", "magenta", "brown"); var colorList = colorBag.toList(); Collections.sort(myList); Collections.sort(colorList); assertEquals(colorList, myList, "failure - color bag not transformed into List"); }
### Question: ColorBag { public int size() { return colors.size(); } void add(String color); void remove(String color); List<String> toList(); boolean contains(String color); int size(); }### Answer: @Test @DisplayName("size of a color bag should match") void size() { int bagSize = colorBag.size(); assertEquals(6, bagSize, "failure - size of bag does not match"); }
### Question: MessageService { public void say() { count++; if (count == 1) { System.out.printf("Method called %d time%n", count); } else { System.out.printf("Method called %d times%n", count); } } void say(); }### Answer: @Test void testSayMessage() { messageService.say(); messageService.say(); messageService.say(); Mockito.verify(messageService, Mockito.times(3)).say(); }
### Question: StringUtils { public String reverse(String original) { if (original == null) { throw new IllegalArgumentException("The word cannot be null"); } char[] data = original.toCharArray(); Stack<Character> stack = new Stack<>(); for (char c: data) { stack.push(c); } char[] data2 = new char[data.length]; int len = stack.size(); for (int i = 0; i < len; i++) { data2[i] = stack.pop(); } return new String(data2); } String reverse(String original); }### Answer: @Test void testReverseWithNull() { when(utils.reverse(null)) .thenThrow(new IllegalArgumentException()); assertThrows(IllegalArgumentException.class, () -> utils.reverse(null)); } @Test void testReverse() { when(utils.reverse("falcon")) .thenReturn("noclaf"); assertEquals(utils.reverse("falcon"), "noclaf"); }
### Question: Position { static double distance(Disk firstPoint, Disk secondPoint) { double a = Math.abs(firstPoint.getPosition().y - secondPoint.getPosition().y); double b = Math.abs(firstPoint.getPosition().x - secondPoint.getPosition().x); return Math.sqrt(a * a + b * b); } Position(double x, double y, double z); public Double x; public Double y; public Double z; }### Answer: @Test void distanceTest() { double distance = Position.distance(disk1, disk2); assertEquals(1.4142135623730951, distance); }
### Question: Position { static double angleBetweenPoints_XasKatethe(Disk firstPoint, Disk secondPoint) { double a = Math.abs(firstPoint.getPosition().y - secondPoint.getPosition().y); double b = Math.abs(firstPoint.getPosition().x - secondPoint.getPosition().x); double c = Math.sqrt(a * a + b * b); return Math.abs(Math.toDegrees(Math.asin(b / c))); } Position(double x, double y, double z); public Double x; public Double y; public Double z; }### Answer: @Test void angleBetweenPoints_XasKatetheTest() { double angle = Position.angleBetweenPoints_XasKatethe(disk1, disk2); assertEquals(44.99999999999999, angle); }
### Question: Position { static double angleBetweenPoints_YasKatethe(Disk firstPoint, Disk secondPoint) { double a = Math.abs(firstPoint.getPosition().y - secondPoint.getPosition().y); double b = Math.abs(firstPoint.getPosition().x - secondPoint.getPosition().x); double c = Math.sqrt(a * a + b * b); return Math.abs(Math.toDegrees(Math.asin(a / c))); } Position(double x, double y, double z); public Double x; public Double y; public Double z; }### Answer: @Test void angleBetweenPoints_YasKatetheTest() { double angle = Position.angleBetweenPoints_YasKatethe(disk1, disk2); assertEquals(44.99999999999999, angle); }
### Question: Position { static boolean intersect(Disk firstPoint, Disk secondPoint) { double a = Math.abs(firstPoint.getPosition().y - secondPoint.getPosition().y); double b = Math.abs(firstPoint.getPosition().x - secondPoint.getPosition().x); return (Math.sqrt(a * a + b * b) <= firstPoint.getRadius() + secondPoint.getRadius() - 0.001); } Position(double x, double y, double z); public Double x; public Double y; public Double z; }### Answer: @Test void intersectTest() { boolean result = Position.intersect(disk1, disk2); assertTrue(result); }
### Question: HibernateGroupDAO extends HibernatePersistentObjectDAO<Group> implements GroupDAO { @Override public Group findByName(String name, long tenantId) { Group group = null; try { Collection<Group> coll = findByWhere( "_entity.tenantId=" + tenantId + " and _entity.name = '" + SqlUtil.doubleQuotes(name) + "'", null, null); if (coll.size() > 0) { group = coll.iterator().next(); if (group.getDeleted() == 1) group = null; } } catch (PersistenceException e) { log.error(e.getMessage(), e); } return group; } private HibernateGroupDAO(); MenuDAO getMenuDAO(); void setMenuDAO(MenuDAO menuDAO); boolean delete(long groupId, int code); boolean exists(String groupname, long tenantId); @Override Collection<String> findAllGroupNames(long tenantId); @Override Group findByName(String name, long tenantId); @Override boolean insert(Group group, long parentGroupId); @Override void inheritACLs(Group group, long parentGroupId); @Override Collection<Group> findByLikeName(String name, long tenantId); @Override int count(); @Override void initialize(Group group); @Override boolean store(Group group); @Override void fixGuestPermissions(Group group); }### Answer: @Test public void testFindByName() { Group group = dao.findByName("admin", 1); Assert.assertNotNull(group); Assert.assertEquals("admin", group.getName()); group = dao.findByName("xxxx", 1); Assert.assertNull(group); group = dao.findByName("admin", 99); Assert.assertNull(group); }
### Question: HibernateGroupDAO extends HibernatePersistentObjectDAO<Group> implements GroupDAO { @Override public Collection<String> findAllGroupNames(long tenantId) { Collection<String> coll = new ArrayList<String>(); try { Collection<Group> coll2 = findAll(); for (Group group : coll2) { if (group.getTenantId() == tenantId) coll.add(group.getName()); } } catch (Throwable e) { log.error(e.getMessage()); } return coll; } private HibernateGroupDAO(); MenuDAO getMenuDAO(); void setMenuDAO(MenuDAO menuDAO); boolean delete(long groupId, int code); boolean exists(String groupname, long tenantId); @Override Collection<String> findAllGroupNames(long tenantId); @Override Group findByName(String name, long tenantId); @Override boolean insert(Group group, long parentGroupId); @Override void inheritACLs(Group group, long parentGroupId); @Override Collection<Group> findByLikeName(String name, long tenantId); @Override int count(); @Override void initialize(Group group); @Override boolean store(Group group); @Override void fixGuestPermissions(Group group); }### Answer: @Test public void testFindAllGroupNames() { Collection<String> groupNames = dao.findAllGroupNames(1); Assert.assertNotNull(groupNames); Assert.assertFalse(groupNames.isEmpty()); Assert.assertTrue(groupNames.contains("admin")); Assert.assertTrue(groupNames.contains("testGroup")); }
### Question: HibernateGroupDAO extends HibernatePersistentObjectDAO<Group> implements GroupDAO { @Override public boolean store(Group group) throws PersistenceException { boolean ret = super.store(group); fixGuestPermissions((Group) group); return ret; } private HibernateGroupDAO(); MenuDAO getMenuDAO(); void setMenuDAO(MenuDAO menuDAO); boolean delete(long groupId, int code); boolean exists(String groupname, long tenantId); @Override Collection<String> findAllGroupNames(long tenantId); @Override Group findByName(String name, long tenantId); @Override boolean insert(Group group, long parentGroupId); @Override void inheritACLs(Group group, long parentGroupId); @Override Collection<Group> findByLikeName(String name, long tenantId); @Override int count(); @Override void initialize(Group group); @Override boolean store(Group group); @Override void fixGuestPermissions(Group group); }### Answer: @Test public void testStore() throws PersistenceException { Assert.assertNull(dao.findByName("LogicalObjects", 1)); Group group = new Group(); group.setName("LogicalObjects"); group.setDescription("Test group for store method"); boolean result = dao.store(group); Assert.assertNotNull(dao.findByName("LogicalObjects", 1)); Assert.assertTrue(result); Group group2 = dao.findByName("LogicalObjects", 1); Assert.assertEquals(group, group2); }
### Question: HibernateGroupDAO extends HibernatePersistentObjectDAO<Group> implements GroupDAO { @Override public boolean insert(Group group, long parentGroupId) { if (!checkStoringAspect()) return false; boolean result = true; if (group == null) return false; try { saveOrUpdate(group); flush(); if (parentGroupId != 0) { inheritACLs(group, parentGroupId); } else { fixGuestPermissions(group); } } catch (Throwable e) { log.error(e.getMessage(), e); result = false; } return result; } private HibernateGroupDAO(); MenuDAO getMenuDAO(); void setMenuDAO(MenuDAO menuDAO); boolean delete(long groupId, int code); boolean exists(String groupname, long tenantId); @Override Collection<String> findAllGroupNames(long tenantId); @Override Group findByName(String name, long tenantId); @Override boolean insert(Group group, long parentGroupId); @Override void inheritACLs(Group group, long parentGroupId); @Override Collection<Group> findByLikeName(String name, long tenantId); @Override int count(); @Override void initialize(Group group); @Override boolean store(Group group); @Override void fixGuestPermissions(Group group); }### Answer: @Test public void testInsert() { Assert.assertNull(dao.findByName("parentNone", 1)); Group group = new Group(); group.setName("parentNone"); group.setDescription("Test group for insert method parent = none"); Assert.assertTrue(dao.insert(group, 90)); Assert.assertNotNull(dao.findByName("parentNone", 1)); Assert.assertNull(dao.findByName("parentNotEmpty", 1)); group = new Group(); group.setName("parentNotEmpty"); group.setDescription("Test group for insertX method parentGroup Not Empty"); Assert.assertTrue(dao.insert(group, 90)); Assert.assertNotNull(dao.findByName("parentNotEmpty", 1)); }
### Question: HibernateUserDAO extends HibernatePersistentObjectDAO<User> implements UserDAO { @Override public User findById(long id) { User user = super.findById(id); if (user != null) initialize(user); return user; } private HibernateUserDAO(); static boolean ignoreCaseLogin(); @Override boolean delete(long userId, int code); @Override List<User> findByName(String name); @Override User findByUsername(String username); @Override User findByUsernameIgnoreCase(String username); List<User> findByLikeUsername(String username); @Override List<User> findByUsernameAndName(String username, String name); @Override boolean store(User user); @Override boolean store(User user, UserHistory transaction); boolean validateUser(String username, String password); @Override boolean validateUser(String username); int getPasswordTtl(); @Override boolean isPasswordExpired(String username); @Override int count(Long tenantId); @Override int countGuests(Long tenantId); @Override boolean delete(long userId, UserHistory transaction); UserHistoryDAO getUserHistoryDAO(); void setUserHistoryDAO(UserHistoryDAO userHistoryDAO); void setUserListenerManager(UserListenerManager userListenerManager); UserListenerManager getUserListenerManager(); @Override void initialize(User user); @Override Map<String, Generic> findUserSettings(long userId, String namePrefix); void setGenericDAO(GenericDAO genericDAO); @Override User findAdminUser(String tenantName); void setConfig(ContextProperties config); @Override Set<User> findByGroup(long groupId); @Override User findById(long id); @Override User getUser(String username); }### Answer: @Test public void testFindById() { User user = dao.findById(1, true); Assert.assertNotNull(user); Assert.assertEquals("admin", user.getUsername()); user.setDecodedPassword("admin"); Assert.assertEquals(CryptUtil.cryptString("admin"), user.getPassword()); Assert.assertEquals("admin@admin.net", user.getEmail()); Assert.assertEquals(2, user.getGroups().size()); user = dao.findById(9999); Assert.assertNull(user); }
### Question: HibernateUserDAO extends HibernatePersistentObjectDAO<User> implements UserDAO { @Override public int count(Long tenantId) { String query = "select count(*) from ld_user where ld_type=" + User.TYPE_DEFAULT + " and not(ld_deleted=1) " + (tenantId != null ? " and ld_tenantid=" + tenantId : ""); try { return queryForInt(query); } catch (PersistenceException e) { log.error(e.getMessage(), e); return 0; } } private HibernateUserDAO(); static boolean ignoreCaseLogin(); @Override boolean delete(long userId, int code); @Override List<User> findByName(String name); @Override User findByUsername(String username); @Override User findByUsernameIgnoreCase(String username); List<User> findByLikeUsername(String username); @Override List<User> findByUsernameAndName(String username, String name); @Override boolean store(User user); @Override boolean store(User user, UserHistory transaction); boolean validateUser(String username, String password); @Override boolean validateUser(String username); int getPasswordTtl(); @Override boolean isPasswordExpired(String username); @Override int count(Long tenantId); @Override int countGuests(Long tenantId); @Override boolean delete(long userId, UserHistory transaction); UserHistoryDAO getUserHistoryDAO(); void setUserHistoryDAO(UserHistoryDAO userHistoryDAO); void setUserListenerManager(UserListenerManager userListenerManager); UserListenerManager getUserListenerManager(); @Override void initialize(User user); @Override Map<String, Generic> findUserSettings(long userId, String namePrefix); void setGenericDAO(GenericDAO genericDAO); @Override User findAdminUser(String tenantName); void setConfig(ContextProperties config); @Override Set<User> findByGroup(long groupId); @Override User findById(long id); @Override User getUser(String username); }### Answer: @Test public void testCount() { Assert.assertEquals(5, dao.count(null)); }
### Question: HibernateSessionDAO extends HibernatePersistentObjectDAO<Session> implements SessionDAO { @Override public void deleteCurrentNodeSessions() { try { bulkUpdate(" set deleted=1 where node=?1 and deleted=0", new Object[] { SystemInfo.get().getInstallationId() }); } catch (PersistenceException e) { log.warn(e.getMessage(), e); } try { bulkUpdate(" set status=" + Session.STATUS_EXPIRED + " where node=?1 and status=?2", new Object[] { SystemInfo.get().getInstallationId(), Session.STATUS_OPEN }); } catch (PersistenceException e) { log.error(e.getMessage(), e); } } protected HibernateSessionDAO(); @Override void deleteCurrentNodeSessions(); @Override int countSessions(Long tenantId, Integer status); @Override Session findBySid(String sid); @Override void initialize(Session session); @Override List<Session> findByNode(String node); @Override void cleanOldSessions(int ttl); }### Answer: @Test public void testDeleteCurrentNodeSessions() { Assert.assertEquals(1, dao.countSessions(1L, null)); dao.deleteCurrentNodeSessions(); Assert.assertEquals(0, dao.countSessions(1L, null)); }
### Question: HibernateSessionDAO extends HibernatePersistentObjectDAO<Session> implements SessionDAO { @Override public List<Session> findByNode(String node) { try { if (StringUtils.isEmpty(node)) return findByWhere(" 1=1 ", null, "order by _entity.creation desc", null); else return findByWhere("_entity.node = ?1", new Object[] { node }, "order by _entity.creation desc", null); } catch (PersistenceException e) { log.error(e.getMessage(), e); return new ArrayList<Session>(); } } protected HibernateSessionDAO(); @Override void deleteCurrentNodeSessions(); @Override int countSessions(Long tenantId, Integer status); @Override Session findBySid(String sid); @Override void initialize(Session session); @Override List<Session> findByNode(String node); @Override void cleanOldSessions(int ttl); }### Answer: @Test public void testFindByNode() { List<Session> sessions = dao.findByNode("saert536yy"); Assert.assertEquals(1, sessions.size()); sessions = dao.findByNode(null); Assert.assertEquals(1, sessions.size()); sessions = dao.findByNode("xxxx"); Assert.assertEquals(0, sessions.size()); }
### Question: HibernateSessionDAO extends HibernatePersistentObjectDAO<Session> implements SessionDAO { @Override public Session findBySid(String sid) { try { List<Session> sessions = findByWhere("_entity.sid = ?1", new Object[] { sid }, null, null); for (Session session : sessions) { if (session.getDeleted() == 0) return session; } } catch (PersistenceException e) { log.error(e.getMessage(), e); } return null; } protected HibernateSessionDAO(); @Override void deleteCurrentNodeSessions(); @Override int countSessions(Long tenantId, Integer status); @Override Session findBySid(String sid); @Override void initialize(Session session); @Override List<Session> findByNode(String node); @Override void cleanOldSessions(int ttl); }### Answer: @Test public void testFindBySid() { Session session = dao.findBySid("sid1"); Assert.assertNotNull(session); Assert.assertEquals("addr1", session.getClient().getAddress()); session = dao.findBySid("sid2"); Assert.assertNull(session); }