index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/incomingnotifications/services
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/incomingnotifications/services/userstatus/BusinessKYCUserLOAStatusNotificationStrategy.java
package com.paypal.kyc.incomingnotifications.services.userstatus; import com.hyperwallet.clientsdk.model.HyperwalletUser; import com.hyperwallet.clientsdk.model.HyperwalletUser.LetterOfAuthorizationStatus; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdateShop; import com.mirakl.client.mmp.operator.request.shop.MiraklUpdateShopsRequest; import com.mirakl.client.mmp.request.additionalfield.MiraklRequestAdditionalFieldValue.MiraklSimpleRequestAdditionalFieldValue; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletProgramsConfiguration; import com.paypal.infrastructure.hyperwallet.services.UserHyperwalletSDKService; import com.paypal.infrastructure.mirakl.client.MiraklClient; import com.paypal.kyc.documentextractioncommons.model.KYCConstants; import com.paypal.kyc.incomingnotifications.model.KYCBusinessStakeholderStatusNotificationBodyModel; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service @Slf4j public class BusinessKYCUserLOAStatusNotificationStrategy extends AbstractKYCBusinessStakeholderNotificationStrategy { protected final MiraklClient miraklMarketplacePlatformOperatorApiClient; public BusinessKYCUserLOAStatusNotificationStrategy(final UserHyperwalletSDKService userHyperwalletSDKService, final HyperwalletProgramsConfiguration hyperwalletProgramsConfiguration, final MiraklClient miraklMarketplacePlatformOperatorApiClient) { super(userHyperwalletSDKService, hyperwalletProgramsConfiguration); this.miraklMarketplacePlatformOperatorApiClient = miraklMarketplacePlatformOperatorApiClient; } @Override public Void execute( final KYCBusinessStakeholderStatusNotificationBodyModel kycBusinessStakeholderStatusNotificationBodyModel) { Optional.ofNullable(getHyperWalletUser(kycBusinessStakeholderStatusNotificationBodyModel)) .ifPresent(hyperWalletUser -> updateMiraklLOAStatus(hyperWalletUser.getClientUserId(), hyperWalletUser.getLetterOfAuthorizationStatus())); return null; } @Override public boolean isApplicable( final KYCBusinessStakeholderStatusNotificationBodyModel kycBusinessStakeholderStatusNotificationBodyModel) { return kycBusinessStakeholderStatusNotificationBodyModel.getIsBusinessContact() && kycBusinessStakeholderStatusNotificationBodyModel.getIsDirector() && KYCConstants.HwWebhookNotificationType.USERS_BUSINESS_STAKEHOLDERS_CREATED.equals( kycBusinessStakeholderStatusNotificationBodyModel.getHyperwalletWebhookNotificationType()); } protected void updateMiraklLOAStatus(final String miraklShopId, final HyperwalletUser.LetterOfAuthorizationStatus letterOfAuthorizationStatus) { final MiraklUpdateShop updateShop = new MiraklUpdateShop(); final String isLetterOfAuthorizationRequired = Boolean .toString(isLetterOfAuthorizationRequired(letterOfAuthorizationStatus)); final MiraklSimpleRequestAdditionalFieldValue miraklSimpleRequestAdditionalFieldValue = new MiraklSimpleRequestAdditionalFieldValue( KYCConstants.HYPERWALLET_KYC_REQUIRED_PROOF_AUTHORIZATION_BUSINESS_FIELD, isLetterOfAuthorizationRequired); updateShop.setShopId(Long.valueOf(miraklShopId)); updateShop.setAdditionalFieldValues(List.of(miraklSimpleRequestAdditionalFieldValue)); log.info("Updating KYC Letter of authorization flag in Mirakl for business Stakeholder for shopId [{}]", miraklShopId); final MiraklUpdateShopsRequest miraklUpdateShopsRequest = new MiraklUpdateShopsRequest(List.of(updateShop)); miraklMarketplacePlatformOperatorApiClient.updateShops(miraklUpdateShopsRequest); log.info("Letter of authorization flag updated to '{}', for business Stakeholder in shopId [{}]", isLetterOfAuthorizationRequired, miraklShopId); } protected boolean isLetterOfAuthorizationRequired(final LetterOfAuthorizationStatus letterOfAuthorizationStatus) { return LetterOfAuthorizationStatus.REQUIRED.equals(letterOfAuthorizationStatus) || LetterOfAuthorizationStatus.FAILED.equals(letterOfAuthorizationStatus); } }
5,400
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/incomingnotifications/services
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/incomingnotifications/services/userstatus/BusinessKYCUserStatusNotificationStrategy.java
package com.paypal.kyc.incomingnotifications.services.userstatus; import com.hyperwallet.clientsdk.model.HyperwalletUser; import com.mirakl.client.mmp.domain.shop.MiraklShopKycStatus; import com.paypal.infrastructure.support.converter.Converter; import com.paypal.infrastructure.mail.services.MailNotificationUtil; import com.paypal.infrastructure.mirakl.client.MiraklClient; import com.paypal.kyc.incomingnotifications.model.KYCDocumentNotificationModel; import com.paypal.kyc.incomingnotifications.model.KYCUserStatusNotificationBodyModel; import com.paypal.kyc.incomingnotifications.services.KYCRejectionReasonService; import com.paypal.kyc.sellersdocumentextraction.services.MiraklSellerDocumentsExtractService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.Triple; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service @Slf4j public class BusinessKYCUserStatusNotificationStrategy extends AbstractKYCUserStatusNotificationStrategy { private static final String REQUIRED = "REQUIRED"; private static final String UNDER_REVIEW = "UNDER_REVIEW"; public BusinessKYCUserStatusNotificationStrategy(final MiraklClient miraklOperatorClient, final MailNotificationUtil mailNotificationUtil, final KYCRejectionReasonService kycRejectionReasonService, final MiraklSellerDocumentsExtractService miraklSellerDocumentsExtractService, final Converter<KYCDocumentNotificationModel, List<String>> kycDocumentNotificationModelListConverter) { super(miraklOperatorClient, mailNotificationUtil, kycRejectionReasonService, miraklSellerDocumentsExtractService, kycDocumentNotificationModelListConverter); } @Override protected MiraklShopKycStatus expectedKycMiraklStatus( final KYCUserStatusNotificationBodyModel incomingNotification) { final String verificationStatus = Optional.ofNullable(incomingNotification.getVerificationStatus()) .map(Enum::name).orElse(null); final String businessStakeHolderStatus = Optional .ofNullable(incomingNotification.getBusinessStakeholderVerificationStatus()).map(Enum::name) .orElse(null); final String letterStatus = Optional.ofNullable(incomingNotification.getLetterOfAuthorizationStatus()) .map(Enum::name).orElse(null); final Triple<String, String, String> statuses = Triple.of(verificationStatus, businessStakeHolderStatus, letterStatus); if (REQUIRED.equals(statuses.getLeft()) || REQUIRED.equals(statuses.getMiddle()) || REQUIRED.equals(statuses.getRight())) { return MiraklShopKycStatus.REFUSED; } if (UNDER_REVIEW.equals(statuses.getLeft()) || UNDER_REVIEW.equals(statuses.getMiddle()) || UNDER_REVIEW.equals(statuses.getRight())) { return MiraklShopKycStatus.PENDING_APPROVAL; } return MiraklShopKycStatus.APPROVED; } /** * {@inheritDoc} */ @Override public boolean isApplicable(final KYCUserStatusNotificationBodyModel source) { return (HyperwalletUser.ProfileType.BUSINESS.equals(source.getProfileType())); } }
5,401
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/incomingnotifications/services
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/incomingnotifications/services/userstatus/AbstractKYCUserStatusNotificationStrategy.java
package com.paypal.kyc.incomingnotifications.services.userstatus; import com.hyperwallet.clientsdk.model.HyperwalletUser; import com.mirakl.client.core.exception.MiraklException; import com.mirakl.client.domain.common.error.ErrorBean; import com.mirakl.client.mmp.domain.shop.MiraklShopKyc; import com.mirakl.client.mmp.domain.shop.MiraklShopKycStatus; import com.mirakl.client.mmp.domain.shop.document.MiraklShopDocument; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdateShop; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdateShopWithErrors; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdatedShopReturn; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdatedShops; import com.mirakl.client.mmp.operator.request.shop.MiraklUpdateShopsRequest; import com.mirakl.client.mmp.request.additionalfield.MiraklRequestAdditionalFieldValue; import com.mirakl.client.mmp.request.additionalfield.MiraklRequestAdditionalFieldValue.MiraklSimpleRequestAdditionalFieldValue; import com.paypal.infrastructure.mirakl.settings.MiraklClientSettingsHolder; import com.paypal.infrastructure.support.converter.Converter; import com.paypal.infrastructure.support.exceptions.HMCException; import com.paypal.infrastructure.mail.services.MailNotificationUtil; import com.paypal.infrastructure.mirakl.client.MiraklClient; import com.paypal.infrastructure.support.strategy.Strategy; import com.paypal.infrastructure.support.logging.MiraklLoggingErrorsUtil; import com.paypal.kyc.documentextractioncommons.model.KYCDocumentInfoModel; import com.paypal.kyc.incomingnotifications.model.KYCDocumentNotificationModel; import com.paypal.kyc.incomingnotifications.model.KYCDocumentStatusEnum; import com.paypal.kyc.incomingnotifications.model.KYCUserStatusNotificationBodyModel; import com.paypal.kyc.incomingnotifications.services.KYCRejectionReasonService; import com.paypal.kyc.sellersdocumentextraction.services.MiraklSellerDocumentsExtractService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.springframework.beans.factory.annotation.Value; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; import static com.paypal.kyc.documentextractioncommons.model.KYCConstants.HYPERWALLET_KYC_REQUIRED_PROOF_AUTHORIZATION_BUSINESS_FIELD; import static com.paypal.kyc.documentextractioncommons.model.KYCConstants.HYPERWALLET_KYC_REQUIRED_PROOF_IDENTITY_BUSINESS_FIELD; @Slf4j public abstract class AbstractKYCUserStatusNotificationStrategy implements Strategy<KYCUserStatusNotificationBodyModel, Void> { protected static final String COMMA = ","; protected static final String MAIL_SUBJECT = "Issue detected updating KYC information in Mirakl"; protected static final String MSG_ERROR_DETECTED = "Something went wrong updating KYC information of shop [%s]%n%s"; protected static final String ERROR_MESSAGE_PREFIX = "There was an error, please check the logs for further information:\n"; @Value("${hmc.toggle-features.automated-kyc}") protected boolean isKycAutomated; protected final MailNotificationUtil mailNotificationUtil; protected final KYCRejectionReasonService kycRejectionReasonService; protected final MiraklClient miraklOperatorClient; protected final MiraklSellerDocumentsExtractService miraklSellerDocumentsExtractService; protected final Converter<KYCDocumentNotificationModel, List<String>> kycDocumentNotificationModelListConverter; protected AbstractKYCUserStatusNotificationStrategy(final MiraklClient miraklOperatorClient, final MailNotificationUtil mailNotificationUtil, final KYCRejectionReasonService kycRejectionReasonService, final MiraklSellerDocumentsExtractService miraklSellerDocumentsExtractService, final Converter<KYCDocumentNotificationModel, List<String>> kycDocumentNotificationModelListConverter) { this.miraklOperatorClient = miraklOperatorClient; this.mailNotificationUtil = mailNotificationUtil; this.kycRejectionReasonService = kycRejectionReasonService; this.miraklSellerDocumentsExtractService = miraklSellerDocumentsExtractService; this.kycDocumentNotificationModelListConverter = kycDocumentNotificationModelListConverter; } /** * {@inheritDoc} */ @Override public Void execute(final KYCUserStatusNotificationBodyModel kycUserNotification) { updateShop(kycUserNotification); return null; } protected void updateShop(final KYCUserStatusNotificationBodyModel kycUserStatusNotificationBodyModel) { final MiraklShopKycStatus status = expectedKycMiraklStatus(kycUserStatusNotificationBodyModel); if (Objects.nonNull(status)) { final String shopId = kycUserStatusNotificationBodyModel.getClientUserId(); final MiraklUpdateShopsRequest request = createUpdateShopRequest(kycUserStatusNotificationBodyModel, status); log.info("Updating KYC status for shop [{}]", shopId); try { final MiraklUpdatedShops response = miraklOperatorClient.updateShops(request); if (response == null) { log.error("No response was received for update request for shop [{}]", shopId); } else { final List<MiraklUpdatedShopReturn> shopReturns = response.getShopReturns(); shopReturns.forEach(this::logShopUpdates); } // If change staging is enabled, document deletion is omitted, since it // implies retrieving shops for each notification and then do a shop // update // for the deletion, and this would exceed Mirakl API rate limit. if (!MiraklClientSettingsHolder.getMiraklClientSettings().isStageChanges()) { deleteInvalidDocuments(kycUserStatusNotificationBodyModel); } } catch (final MiraklException ex) { final String errorMessage = MSG_ERROR_DETECTED.formatted(shopId, MiraklLoggingErrorsUtil.stringify(ex)); log.error(errorMessage, ex); mailNotificationUtil.sendPlainTextEmail(MAIL_SUBJECT, ERROR_MESSAGE_PREFIX + errorMessage); // Rethrow exception to handle it in AbstractNotificationListener throw ex; } } } protected void deleteInvalidDocuments(final KYCUserStatusNotificationBodyModel kycUserNotification) { final String clientUserId = kycUserNotification.getClientUserId(); final KYCDocumentInfoModel kycDocumentInfoModel = miraklSellerDocumentsExtractService .extractKYCSellerDocuments(clientUserId); final Map<String, LocalDateTime> documentsToBeDeleted = kycUserNotification.getDocuments().stream() .filter(kycDocumentNotificationModel -> KYCDocumentStatusEnum.INVALID .equals(kycDocumentNotificationModel.getDocumentStatus())) .map(kycDocumentNotificationModel -> Pair.of( kycDocumentNotificationModelListConverter.convert(kycDocumentNotificationModel), kycDocumentNotificationModel.getCreatedOn())) .map(this::getMapDocumentUploadTime).flatMap(map -> map.entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); if (MapUtils.isNotEmpty(documentsToBeDeleted)) { final List<MiraklShopDocument> miraklDocumentsToBeDeleted = kycDocumentInfoModel.getMiraklShopDocuments() .stream() .filter(miraklShopDocument -> documentsToBeDeleted.containsKey(miraklShopDocument.getTypeCode())) .filter(Predicate .not(miraklShopDocument -> isANewMiraklDocument(documentsToBeDeleted, miraklShopDocument))) .collect(Collectors.toList()); final String documentTypeCodesToBeDeleted = miraklDocumentsToBeDeleted.stream() .map(MiraklShopDocument::getTypeCode).collect(Collectors.joining(COMMA)); if (!StringUtils.isEmpty(documentTypeCodesToBeDeleted)) { log.info("Deleting documents [{}] for shop [{}]", documentTypeCodesToBeDeleted, clientUserId); miraklSellerDocumentsExtractService.deleteDocuments(miraklDocumentsToBeDeleted); log.info("Documents deleted"); } } } private boolean isANewMiraklDocument(final Map<String, LocalDateTime> documentsToBeDeleted, final MiraklShopDocument miraklShopDocument) { final LocalDateTime hyperwalletDateUploaded = documentsToBeDeleted.get(miraklShopDocument.getTypeCode()); final LocalDateTime miraklDateUploaded = getLocalDateTimeFromDate(miraklShopDocument.getDateUploaded()); return miraklDateUploaded.isAfter(hyperwalletDateUploaded); } protected abstract MiraklShopKycStatus expectedKycMiraklStatus( final KYCUserStatusNotificationBodyModel incomingNotification); private MiraklUpdateShopsRequest createUpdateShopRequest( final KYCUserStatusNotificationBodyModel kycUserStatusNotificationBodyModel, final MiraklShopKycStatus status) { final String shopId = kycUserStatusNotificationBodyModel.getClientUserId(); final MiraklUpdateShop miraklUpdateShop = new MiraklUpdateShop(); miraklUpdateShop.setShopId(Long.valueOf(shopId)); //@formatter:off miraklUpdateShop.setKyc(new MiraklShopKyc(status, kycRejectionReasonService.getRejectionReasonDescriptions(kycUserStatusNotificationBodyModel.getReasonsType()))); //@formatter:on if (isKycAutomated()) { final List<MiraklRequestAdditionalFieldValue> additionalFieldValues = new ArrayList<>(); if (HyperwalletUser.VerificationStatus.REQUIRED .equals(kycUserStatusNotificationBodyModel.getVerificationStatus())) { final MiraklSimpleRequestAdditionalFieldValue kycVerificationStatusCustomField = new MiraklSimpleRequestAdditionalFieldValue(); kycVerificationStatusCustomField.setCode(HYPERWALLET_KYC_REQUIRED_PROOF_IDENTITY_BUSINESS_FIELD); kycVerificationStatusCustomField.setValue(Boolean.TRUE.toString()); additionalFieldValues.add(kycVerificationStatusCustomField); } if (HyperwalletUser.LetterOfAuthorizationStatus.REQUIRED .equals(kycUserStatusNotificationBodyModel.getLetterOfAuthorizationStatus())) { final MiraklSimpleRequestAdditionalFieldValue kycLetterOfAuthorizationStatusCustomField = new MiraklSimpleRequestAdditionalFieldValue(); kycLetterOfAuthorizationStatusCustomField .setCode(HYPERWALLET_KYC_REQUIRED_PROOF_AUTHORIZATION_BUSINESS_FIELD); kycLetterOfAuthorizationStatusCustomField.setValue(Boolean.TRUE.toString()); additionalFieldValues.add(kycLetterOfAuthorizationStatusCustomField); } if (!CollectionUtils.isEmpty(additionalFieldValues)) { miraklUpdateShop.setAdditionalFieldValues(additionalFieldValues); } } return new MiraklUpdateShopsRequest(List.of(miraklUpdateShop)); } private Map<String, LocalDateTime> getMapDocumentUploadTime(final Pair<List<String>, LocalDateTime> documents) { return documents.getLeft().stream().map(documentType -> Pair.of(documentType, documents.getRight())) .collect(Collectors.toMap(Pair::getLeft, Pair::getRight)); } private LocalDateTime getLocalDateTimeFromDate(final Date date) { return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); } private void logShopUpdates(final MiraklUpdatedShopReturn updatedShopReturn) { Optional.ofNullable(updatedShopReturn.getShopUpdated()).ifPresent( shop -> log.info("KYC status updated to [{}] for shop [{}]", shop.getKyc().getStatus(), shop.getId())); Optional.ofNullable(updatedShopReturn.getShopError()).ifPresent(this::logErrorMessage); } private void logErrorMessage(final MiraklUpdateShopWithErrors shopError) { final Long shopId = shopError.getInput().getShopId(); //@formatter:off final String miraklUpdateErrors = shopError.getErrors().stream() .map(ErrorBean::toString) .collect(Collectors.joining(",")); //@formatter:on final String errorMessage = MSG_ERROR_DETECTED.formatted(shopId, miraklUpdateErrors); log.error(errorMessage); mailNotificationUtil.sendPlainTextEmail(MAIL_SUBJECT, ERROR_MESSAGE_PREFIX + errorMessage); throw new HMCException(errorMessage); } protected boolean isKycAutomated() { return isKycAutomated; } }
5,402
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/incomingnotifications/services
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/incomingnotifications/services/userstatus/IndividualKYCBusinessStakeholderStatusNotificationStrategy.java
package com.paypal.kyc.incomingnotifications.services.userstatus; import com.hyperwallet.clientsdk.model.HyperwalletUser; import com.mchange.v2.lang.StringUtils; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdateShop; import com.mirakl.client.mmp.operator.request.shop.MiraklUpdateShopsRequest; import com.mirakl.client.mmp.request.additionalfield.MiraklRequestAdditionalFieldValue; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletProgramsConfiguration; import com.paypal.infrastructure.hyperwallet.services.UserHyperwalletSDKService; import com.paypal.infrastructure.mirakl.client.MiraklClient; import com.paypal.kyc.documentextractioncommons.model.KYCConstants; import com.paypal.kyc.incomingnotifications.model.KYCBusinessStakeholderStatusNotificationBodyModel; import com.paypal.kyc.stakeholdersdocumentextraction.services.MiraklBusinessStakeholderDocumentsExtractService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.springframework.stereotype.Service; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; @Service @Slf4j public class IndividualKYCBusinessStakeholderStatusNotificationStrategy extends AbstractKYCBusinessStakeholderNotificationStrategy { protected final MiraklBusinessStakeholderDocumentsExtractService miraklBusinessStakeholderDocumentsExtractService; protected final MiraklClient miraklMarketplacePlatformOperatorApiClient; public IndividualKYCBusinessStakeholderStatusNotificationStrategy( final UserHyperwalletSDKService userHyperwalletSDKService, final HyperwalletProgramsConfiguration hyperwalletProgramsConfiguration, final MiraklBusinessStakeholderDocumentsExtractService miraklBusinessStakeholderDocumentsExtractService, final MiraklClient miraklMarketplacePlatformOperatorApiClient) { super(userHyperwalletSDKService, hyperwalletProgramsConfiguration); this.miraklBusinessStakeholderDocumentsExtractService = miraklBusinessStakeholderDocumentsExtractService; this.miraklMarketplacePlatformOperatorApiClient = miraklMarketplacePlatformOperatorApiClient; } /** * {@inheritDoc} */ @Override public Void execute( final KYCBusinessStakeholderStatusNotificationBodyModel kycBusinessStakeholderStatusNotificationBodyModel) { final HyperwalletUser hyperWalletUser = getHyperWalletUser(kycBusinessStakeholderStatusNotificationBodyModel); if (Objects.nonNull(hyperWalletUser)) { final List<String> miraklProofOfIdentityCustomFieldNames = miraklBusinessStakeholderDocumentsExtractService .getKYCCustomValuesRequiredVerificationBusinessStakeholders(hyperWalletUser.getClientUserId(), List.of(kycBusinessStakeholderStatusNotificationBodyModel.getToken())); final HyperwalletUser.VerificationStatus verificationStatus = kycBusinessStakeholderStatusNotificationBodyModel .getVerificationStatus(); if (CollectionUtils.isNotEmpty(miraklProofOfIdentityCustomFieldNames)) { updateMiraklProofIdentityFlagStatus(hyperWalletUser.getClientUserId(), miraklProofOfIdentityCustomFieldNames.get(0), verificationStatus); } } return null; } /** * {@inheritDoc} */ @Override public boolean isApplicable(final KYCBusinessStakeholderStatusNotificationBodyModel source) { return HyperwalletUser.ProfileType.INDIVIDUAL.equals(source.getProfileType()) && source.getHyperwalletWebhookNotificationType().contains( KYCConstants.HwWebhookNotificationType.USERS_BUSINESS_STAKEHOLDERS_VERIFICATION_STATUS); } protected void updateMiraklProofIdentityFlagStatus(final String miraklShopId, final String kycCustomValuesRequiredVerificationBusinessStakeholder, final HyperwalletUser.VerificationStatus verificationStatus) { if (StringUtils.nonEmptyString(kycCustomValuesRequiredVerificationBusinessStakeholder)) { final MiraklUpdateShop updateShop = new MiraklUpdateShop(); final List<MiraklRequestAdditionalFieldValue> additionalFieldValues = Optional .of(kycCustomValuesRequiredVerificationBusinessStakeholder).stream() .map(kycCustomValueRequiredVerification -> new MiraklRequestAdditionalFieldValue.MiraklSimpleRequestAdditionalFieldValue( kycCustomValueRequiredVerification, Boolean.toString(HyperwalletUser.VerificationStatus.REQUIRED.equals(verificationStatus)))) .collect(Collectors.toList()); updateShop.setShopId(Long.valueOf(miraklShopId)); updateShop.setAdditionalFieldValues(additionalFieldValues); log.info("Updating KYC proof of identity flag in Mirakl for business Stakeholder for shopId [{}]", miraklShopId); final MiraklUpdateShopsRequest miraklUpdateShopsRequest = new MiraklUpdateShopsRequest(List.of(updateShop)); miraklMarketplacePlatformOperatorApiClient.updateShops(miraklUpdateShopsRequest); log.info("Proof of identity flag updated for business Stakeholder for shopId [{}]", miraklShopId); } } }
5,403
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/incomingnotifications/services
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/incomingnotifications/services/userstatus/AbstractKYCBusinessStakeholderNotificationStrategy.java
package com.paypal.kyc.incomingnotifications.services.userstatus; import com.hyperwallet.clientsdk.Hyperwallet; import com.hyperwallet.clientsdk.model.HyperwalletUser; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletProgramsConfiguration; import com.paypal.infrastructure.support.exceptions.HMCException; import com.paypal.infrastructure.hyperwallet.services.UserHyperwalletSDKService; import com.paypal.infrastructure.support.strategy.Strategy; import com.paypal.kyc.incomingnotifications.model.KYCBusinessStakeholderStatusNotificationBodyModel; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; @Slf4j public abstract class AbstractKYCBusinessStakeholderNotificationStrategy implements Strategy<KYCBusinessStakeholderStatusNotificationBodyModel, Void> { protected final UserHyperwalletSDKService userHyperwalletSDKService; protected final HyperwalletProgramsConfiguration hyperwalletProgramsConfiguration; protected AbstractKYCBusinessStakeholderNotificationStrategy( final UserHyperwalletSDKService userHyperwalletSDKService, final HyperwalletProgramsConfiguration hyperwalletProgramsConfiguration) { this.userHyperwalletSDKService = userHyperwalletSDKService; this.hyperwalletProgramsConfiguration = hyperwalletProgramsConfiguration; } protected HyperwalletUser getHyperWalletUser( final KYCBusinessStakeholderStatusNotificationBodyModel kycBusinessStakeholderStatusNotificationBodyModel) { //@formatter:off final List<HyperwalletUser> hyperWalletUser = hyperwalletProgramsConfiguration.getAllProgramConfigurations().stream() .map(HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration::getUsersProgramToken) .map(userHyperwalletSDKService::getHyperwalletInstanceByProgramToken) .map(hyperwallet -> callHyperwalletSDKCatchingException(hyperwallet, kycBusinessStakeholderStatusNotificationBodyModel.getUserToken())) .filter(Objects::nonNull).collect(Collectors.toList()); //@formatter:on if (CollectionUtils.isEmpty(hyperWalletUser)) { throw new HMCException( String.format("No Hyperwallet users were found for user token %s in the system instance(s)", kycBusinessStakeholderStatusNotificationBodyModel.getUserToken())); } return hyperWalletUser.get(0); } protected HyperwalletUser callHyperwalletSDKCatchingException(final Hyperwallet hyperwallet, final String userToken) { try { return hyperwallet.getUser(userToken); } catch (final RuntimeException e) { return null; } } }
5,404
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/incomingnotifications/services
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/incomingnotifications/services/userstatus/IndividualKYCUserStatusNotificationStrategy.java
package com.paypal.kyc.incomingnotifications.services.userstatus; import com.hyperwallet.clientsdk.model.HyperwalletUser; import com.mirakl.client.mmp.domain.shop.MiraklShopKycStatus; import com.paypal.infrastructure.support.converter.Converter; import com.paypal.infrastructure.mail.services.MailNotificationUtil; import com.paypal.infrastructure.mirakl.client.MiraklClient; import com.paypal.kyc.incomingnotifications.model.KYCDocumentNotificationModel; import com.paypal.kyc.incomingnotifications.model.KYCUserStatusNotificationBodyModel; import com.paypal.kyc.incomingnotifications.services.KYCRejectionReasonService; import com.paypal.kyc.sellersdocumentextraction.services.MiraklSellerDocumentsExtractService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.EnumMap; import java.util.List; @Service @Slf4j public class IndividualKYCUserStatusNotificationStrategy extends AbstractKYCUserStatusNotificationStrategy { private EnumMap<HyperwalletUser.VerificationStatus, MiraklShopKycStatus> statusMapping; public IndividualKYCUserStatusNotificationStrategy(final MiraklClient miraklOperatorClient, final MailNotificationUtil mailNotificationUtil, final KYCRejectionReasonService kycRejectionReasonService, final MiraklSellerDocumentsExtractService miraklSellerDocumentsExtractService, final Converter<KYCDocumentNotificationModel, List<String>> kycDocumentNotificationModelListConverter) { super(miraklOperatorClient, mailNotificationUtil, kycRejectionReasonService, miraklSellerDocumentsExtractService, kycDocumentNotificationModelListConverter); initializeMap(); } @Override protected MiraklShopKycStatus expectedKycMiraklStatus( final KYCUserStatusNotificationBodyModel incomingNotification) { return statusMapping.get(incomingNotification.getVerificationStatus()); } /** * {@inheritDoc} */ @Override public boolean isApplicable(final KYCUserStatusNotificationBodyModel source) { return (HyperwalletUser.ProfileType.INDIVIDUAL.equals(source.getProfileType())); } private void initializeMap() { statusMapping = new EnumMap<>(HyperwalletUser.VerificationStatus.class); statusMapping.put(HyperwalletUser.VerificationStatus.UNDER_REVIEW, MiraklShopKycStatus.PENDING_APPROVAL); statusMapping.put(HyperwalletUser.VerificationStatus.VERIFIED, MiraklShopKycStatus.APPROVED); statusMapping.put(HyperwalletUser.VerificationStatus.REQUIRED, MiraklShopKycStatus.REFUSED); statusMapping.put(HyperwalletUser.VerificationStatus.NOT_REQUIRED, MiraklShopKycStatus.APPROVED); } }
5,405
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/StatusSynchronizationJobsConfig.java
package com.paypal.kyc.statussynchronization; import com.paypal.kyc.documentextractioncommons.DocumentsExtractionJobsConfig; import com.paypal.kyc.documentextractioncommons.jobs.DocumentsExtractJob; import com.paypal.kyc.statussynchronization.jobs.KYCUserStatusResyncJob; import org.quartz.*; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class StatusSynchronizationJobsConfig { private static final String TRIGGER_SUFFIX = "Trigger"; private static final String JOB_NAME = "KYCUserStatusInfoJob"; @Value("${hmc.toggle-features.resync-jobs}") private boolean resyncJobsEnabled; /** * Creates a recurring job {@link DocumentsExtractJob} * @return the {@link JobDetail} */ @Bean public JobDetail kycUserStatusInfoJob() { //@formatter:off return JobBuilder.newJob(KYCUserStatusResyncJob.class) .withIdentity(JOB_NAME) .storeDurably() .build(); //@formatter:on } /** * Schedules the recurring job {@link DocumentsExtractJob} with the {@code jobDetails} * set on {@link DocumentsExtractionJobsConfig#documentsExtractJob()} * @param jobDetails the {@link JobDetail} * @return the {@link Trigger} */ @Bean public Trigger kycUserStatusInfoJobTrigger(@Qualifier("kycUserStatusInfoJob") final JobDetail jobDetails, @Value("${hmc.jobs.scheduling.resync-jobs.kycstatus}") final String cronExpression) { if (!resyncJobsEnabled) { return null; } //@formatter:off return TriggerBuilder.newTrigger() .forJob(jobDetails) .withIdentity(TRIGGER_SUFFIX + JOB_NAME) .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)) .build(); //@formatter:on } }
5,406
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/batchjobs/KYCUserStatusResyncBatchJob.java
package com.paypal.kyc.statussynchronization.batchjobs; import com.paypal.jobsystem.batchjob.model.BatchJobContext; import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemProcessor; import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemsExtractor; import com.paypal.jobsystem.batchjobsupport.support.AbstractExtractBatchJob; import org.springframework.stereotype.Component; /** * It takes the info in a Hyperwallet user and processes it as a status notification. */ @Component public class KYCUserStatusResyncBatchJob extends AbstractExtractBatchJob<BatchJobContext, KYCUserStatusResyncBatchJobItem> { private final KYCUserStatusResyncBatchJobItemProcessor kycUserStatusResyncBatchJobItemProcessor; private final KYCUserStatusResyncBatchJobItemExtractor kycUserStatusResyncBatchJobItemExtractor; public KYCUserStatusResyncBatchJob( final KYCUserStatusResyncBatchJobItemProcessor kycUserStatusResyncBatchJobItemProcessor, final KYCUserStatusResyncBatchJobItemExtractor kycUserStatusResyncBatchJobItemExtractor) { this.kycUserStatusResyncBatchJobItemProcessor = kycUserStatusResyncBatchJobItemProcessor; this.kycUserStatusResyncBatchJobItemExtractor = kycUserStatusResyncBatchJobItemExtractor; } @Override protected BatchJobItemProcessor<BatchJobContext, KYCUserStatusResyncBatchJobItem> getBatchJobItemProcessor() { return this.kycUserStatusResyncBatchJobItemProcessor; } @Override protected BatchJobItemsExtractor<BatchJobContext, KYCUserStatusResyncBatchJobItem> getBatchJobItemsExtractor() { return this.kycUserStatusResyncBatchJobItemExtractor; } }
5,407
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/batchjobs/KYCUserStatusResyncBatchJobItem.java
package com.paypal.kyc.statussynchronization.batchjobs; import com.paypal.jobsystem.batchjobsupport.support.AbstractBatchJobItem; import com.paypal.kyc.statussynchronization.model.KYCUserStatusInfoModel; public class KYCUserStatusResyncBatchJobItem extends AbstractBatchJobItem<KYCUserStatusInfoModel> { protected KYCUserStatusResyncBatchJobItem(final KYCUserStatusInfoModel item) { super(item); } @Override public String getItemId() { return getItem().getKycUserStatusNotificationBodyModel().getClientUserId(); } @Override public String getItemType() { return "KYCUserStatusInfo"; } }
5,408
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/batchjobs/KYCUserStatusResyncBatchJobItemProcessor.java
package com.paypal.kyc.statussynchronization.batchjobs; import com.paypal.infrastructure.mirakl.settings.MiraklClientSettings; import com.paypal.infrastructure.mirakl.settings.MiraklClientSettingsExecutor; import com.paypal.jobsystem.batchjob.model.BatchJobContext; import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemProcessor; import com.paypal.kyc.incomingnotifications.services.KYCUserDocumentFlagsExecutor; import com.paypal.kyc.incomingnotifications.services.KYCUserStatusExecutor; import com.paypal.kyc.statussynchronization.model.KYCUserStatusInfoModel; import org.springframework.stereotype.Component; /** * It takes the info in a Hyperwallet user and processes it as a status notification. */ @Component public class KYCUserStatusResyncBatchJobItemProcessor implements BatchJobItemProcessor<BatchJobContext, KYCUserStatusResyncBatchJobItem> { private final KYCUserStatusExecutor kyCUserStatusExecutor; private final KYCUserDocumentFlagsExecutor kycUserDocumentFlagsExecutor; protected boolean useStaging = true; public KYCUserStatusResyncBatchJobItemProcessor(final KYCUserStatusExecutor kyCUserStatusExecutor, final KYCUserDocumentFlagsExecutor kycUserDocumentFlagsExecutor) { this.kyCUserStatusExecutor = kyCUserStatusExecutor; this.kycUserDocumentFlagsExecutor = kycUserDocumentFlagsExecutor; } @Override public void processItem(final BatchJobContext ctx, final KYCUserStatusResyncBatchJobItem jobItem) { final KYCUserStatusInfoModel kYCUserStatusInfoModel = jobItem.getItem(); MiraklClientSettingsExecutor.runWithSettings(new MiraklClientSettings(useStaging), () -> processKYCUserStatusInfoModel(kYCUserStatusInfoModel)); } private void processKYCUserStatusInfoModel(final KYCUserStatusInfoModel kYCUserStatusInfoModel) { kyCUserStatusExecutor.execute(kYCUserStatusInfoModel.getKycUserStatusNotificationBodyModel()); kycUserDocumentFlagsExecutor.execute(kYCUserStatusInfoModel.getKycUserDocumentFlagsNotificationBodyModel()); } }
5,409
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/batchjobs/KYCUserStatusResyncBatchJobItemExtractor.java
package com.paypal.kyc.statussynchronization.batchjobs; import com.paypal.jobsystem.batchjob.model.BatchJobContext; import com.paypal.jobsystem.batchjobsupport.support.AbstractFixedWindowDeltaBatchJobItemsExtractor; import com.paypal.kyc.statussynchronization.services.HyperwalletKycUserStatusExtractService; import org.springframework.stereotype.Component; import java.util.Collection; import java.util.Date; import java.util.stream.Collectors; @Component public class KYCUserStatusResyncBatchJobItemExtractor extends AbstractFixedWindowDeltaBatchJobItemsExtractor<BatchJobContext, KYCUserStatusResyncBatchJobItem> { private final HyperwalletKycUserStatusExtractService hyperwalletKycUserStatusExtractService; public KYCUserStatusResyncBatchJobItemExtractor( final HyperwalletKycUserStatusExtractService hyperwalletKycUserStatusExtractService) { this.hyperwalletKycUserStatusExtractService = hyperwalletKycUserStatusExtractService; } /** * Retrieves all Hyperwallet users since the {@code delta} time and returns them as a * {@link Collection} of {@link KYCUserStatusResyncBatchJobItem} * @param delta the initial date for the creation date of the users {@link Date} * @return a {@link Collection} of {@link KYCUserStatusResyncBatchJobItem} */ @Override protected Collection<KYCUserStatusResyncBatchJobItem> getItems(final BatchJobContext ctx, final Date delta) { //@formatter:off return hyperwalletKycUserStatusExtractService.extractKycUserStatuses(delta, new Date()) .stream() .map(KYCUserStatusResyncBatchJobItem::new) .collect(Collectors.toList()); //@formatter:on } }
5,410
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/model/KYCUserStatusInfoModel.java
package com.paypal.kyc.statussynchronization.model; import com.paypal.kyc.incomingnotifications.model.KYCUserDocumentFlagsNotificationBodyModel; import com.paypal.kyc.incomingnotifications.model.KYCUserStatusNotificationBodyModel; import lombok.Value; @Value public class KYCUserStatusInfoModel { private KYCUserStatusNotificationBodyModel kycUserStatusNotificationBodyModel; private KYCUserDocumentFlagsNotificationBodyModel kycUserDocumentFlagsNotificationBodyModel; }
5,411
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/jobs/KYCUserStatusResyncJob.java
package com.paypal.kyc.statussynchronization.jobs; import com.paypal.jobsystem.quartzadapter.job.QuartzBatchJobAdapterFactory; import com.paypal.jobsystem.quartzadapter.support.AbstractBatchJobSupportQuartzJob; import com.paypal.kyc.statussynchronization.batchjobs.KYCUserStatusResyncBatchJob; import org.quartz.*; @PersistJobDataAfterExecution @DisallowConcurrentExecution public class KYCUserStatusResyncJob extends AbstractBatchJobSupportQuartzJob implements Job { private final KYCUserStatusResyncBatchJob kycUserStatusResyncBatchJob; protected KYCUserStatusResyncJob(final QuartzBatchJobAdapterFactory quartzBatchJobAdapterFactory, final KYCUserStatusResyncBatchJob kycUserStatusResyncBatchJob) { super(quartzBatchJobAdapterFactory); this.kycUserStatusResyncBatchJob = kycUserStatusResyncBatchJob; } @Override public void execute(final JobExecutionContext context) throws JobExecutionException { executeBatchJob(this.kycUserStatusResyncBatchJob, context); } }
5,412
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/controllers/KYCStatusResyncJobController.java
package com.paypal.kyc.statussynchronization.controllers; import com.paypal.jobsystem.quartzintegration.controllers.AbstractJobController; import com.paypal.kyc.statussynchronization.jobs.KYCUserStatusResyncJob; import lombok.extern.slf4j.Slf4j; import org.quartz.SchedulerException; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.Date; /** * Controller that calls the job to synchronize KYC status from Hyperwallet to Mirakl. */ @Slf4j @RestController @RequestMapping("/job") public class KYCStatusResyncJobController extends AbstractJobController { private static final String DEFAULT_KYC_USER_STATUS_RESYNC_JOB_NAME = "KYCUserStatusInfoJobSingleExecution"; /** * Triggers the {@link KYCUserStatusResyncJob} with the {@code delta} time to retrieve * hyperwallet users created since that {@code delta} and schedules the job with the * {@code name} provided. * @param delta the {@link Date} in {@link DateTimeFormat.ISO} * @param name the job name in {@link String} * @return a {@link ResponseEntity <String>} with the name of the job scheduled * @throws SchedulerException if quartz {@link org.quartz.Scheduler} fails */ @PostMapping("/kyc-userstatus-resync") public ResponseEntity<String> runJob( @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) final Date delta, @RequestParam(required = false, defaultValue = DEFAULT_KYC_USER_STATUS_RESYNC_JOB_NAME) final String name) throws SchedulerException { runSingleJob(name, KYCUserStatusResyncJob.class, delta); return ResponseEntity.accepted().body(name); } }
5,413
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/services/HyperwalletKycUserStatusExtractService.java
package com.paypal.kyc.statussynchronization.services; import com.paypal.kyc.statussynchronization.model.KYCUserStatusInfoModel; import java.util.Date; import java.util.List; public interface HyperwalletKycUserStatusExtractService { List<KYCUserStatusInfoModel> extractKycUserStatuses(Date from, Date to); }
5,414
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/services/HyperwalletKycUserStatusExtractServiceImpl.java
package com.paypal.kyc.statussynchronization.services; import com.hyperwallet.clientsdk.Hyperwallet; import com.hyperwallet.clientsdk.model.HyperwalletUser; import com.hyperwallet.clientsdk.model.HyperwalletUsersListPaginationOptions; import com.paypal.infrastructure.hyperwallet.services.HyperwalletPaginationSupport; import com.paypal.infrastructure.hyperwallet.services.UserHyperwalletSDKService; import com.paypal.infrastructure.support.converter.Converter; import com.paypal.kyc.statussynchronization.model.KYCUserStatusInfoModel; import org.springframework.stereotype.Component; import java.util.Date; import java.util.List; import java.util.stream.Collectors; @Component public class HyperwalletKycUserStatusExtractServiceImpl implements HyperwalletKycUserStatusExtractService { private final Hyperwallet hyperwallet; private final Converter<HyperwalletUser, KYCUserStatusInfoModel> kycUserStatusInfoModelConverter; public HyperwalletKycUserStatusExtractServiceImpl(final UserHyperwalletSDKService userHyperwalletSDKService, final Converter<HyperwalletUser, KYCUserStatusInfoModel> kycUserStatusInfoModelConverter) { this.hyperwallet = userHyperwalletSDKService.getHyperwalletInstance(); this.kycUserStatusInfoModelConverter = kycUserStatusInfoModelConverter; } @Override public List<KYCUserStatusInfoModel> extractKycUserStatuses(final Date from, final Date to) { final HyperwalletUsersListPaginationOptions options = new HyperwalletUsersListPaginationOptions(); options.setCreatedAfter(from); options.setCreatedBefore(to); final HyperwalletPaginationSupport hyperwalletPaginationSupport = new HyperwalletPaginationSupport(hyperwallet); final List<HyperwalletUser> hyperwalletUsers = hyperwalletPaginationSupport .get(() -> hyperwallet.listUsers(options)); return hyperwalletUsers.stream().map(kycUserStatusInfoModelConverter::convert).collect(Collectors.toList()); } }
5,415
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/services
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/services/converters/HyperwalletUserToKycUserDocumentFlagsNotificationBodyModelConverter.java
package com.paypal.kyc.statussynchronization.services.converters; import com.hyperwallet.clientsdk.model.HyperwalletUser; import com.paypal.infrastructure.support.converter.Converter; import com.paypal.kyc.incomingnotifications.model.KYCUserDocumentFlagsNotificationBodyModel; import org.springframework.stereotype.Component; @Component public class HyperwalletUserToKycUserDocumentFlagsNotificationBodyModelConverter extends AbstractKycNotificationBodyModelConverter<KYCUserDocumentFlagsNotificationBodyModel> implements Converter<HyperwalletUser, KYCUserDocumentFlagsNotificationBodyModel> { public HyperwalletUserToKycUserDocumentFlagsNotificationBodyModelConverter( final Converter<Object, KYCUserDocumentFlagsNotificationBodyModel> toNotificationBodyModelConverter) { super(toNotificationBodyModelConverter); } }
5,416
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/services
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/services/converters/HyperwalletUserToKYCUserStatusInfoModelConverter.java
package com.paypal.kyc.statussynchronization.services.converters; import com.hyperwallet.clientsdk.model.HyperwalletUser; import com.paypal.infrastructure.support.converter.Converter; import com.paypal.kyc.incomingnotifications.model.KYCUserDocumentFlagsNotificationBodyModel; import com.paypal.kyc.incomingnotifications.model.KYCUserStatusNotificationBodyModel; import com.paypal.kyc.statussynchronization.model.KYCUserStatusInfoModel; import org.springframework.stereotype.Component; @Component public class HyperwalletUserToKYCUserStatusInfoModelConverter implements Converter<HyperwalletUser, KYCUserStatusInfoModel> { private final Converter<HyperwalletUser, KYCUserDocumentFlagsNotificationBodyModel> hyperwalletUserToKycUserDocumentFlagsNotificationBodyModel; private final Converter<HyperwalletUser, KYCUserStatusNotificationBodyModel> hyperwalletUserToKycUserStatusNotificationBodyModelConverter; public HyperwalletUserToKYCUserStatusInfoModelConverter( final Converter<HyperwalletUser, KYCUserDocumentFlagsNotificationBodyModel> hyperwalletUserToKycUserDocumentFlagsNotificationBodyModel, final Converter<HyperwalletUser, KYCUserStatusNotificationBodyModel> hyperwalletUserToKycUserStatusNotificationBodyModelConverter) { this.hyperwalletUserToKycUserDocumentFlagsNotificationBodyModel = hyperwalletUserToKycUserDocumentFlagsNotificationBodyModel; this.hyperwalletUserToKycUserStatusNotificationBodyModelConverter = hyperwalletUserToKycUserStatusNotificationBodyModelConverter; } @Override public KYCUserStatusInfoModel convert(final HyperwalletUser source) { return new KYCUserStatusInfoModel(hyperwalletUserToKycUserStatusNotificationBodyModelConverter.convert(source), hyperwalletUserToKycUserDocumentFlagsNotificationBodyModel.convert(source)); } }
5,417
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/services
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/services/converters/HyperwalletUserToKycUserStatusNotificationBodyModelConverter.java
package com.paypal.kyc.statussynchronization.services.converters; import com.hyperwallet.clientsdk.model.HyperwalletUser; import com.paypal.infrastructure.support.converter.Converter; import com.paypal.kyc.incomingnotifications.model.KYCUserStatusNotificationBodyModel; import org.springframework.stereotype.Component; @Component public class HyperwalletUserToKycUserStatusNotificationBodyModelConverter extends AbstractKycNotificationBodyModelConverter<KYCUserStatusNotificationBodyModel> implements Converter<HyperwalletUser, KYCUserStatusNotificationBodyModel> { public HyperwalletUserToKycUserStatusNotificationBodyModelConverter( final Converter<Object, KYCUserStatusNotificationBodyModel> toNotificationBodyModelConverter) { super(toNotificationBodyModelConverter); } }
5,418
0
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/services
Create_ds/mirakl-hyperwallet-connector/hmc-kyc/src/main/java/com/paypal/kyc/statussynchronization/services/converters/AbstractKycNotificationBodyModelConverter.java
package com.paypal.kyc.statussynchronization.services.converters; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; import com.hyperwallet.clientsdk.model.HyperwalletUser; import com.hyperwallet.clientsdk.util.HyperwalletJsonConfiguration; import com.paypal.infrastructure.support.converter.Converter; import com.paypal.kyc.incomingnotifications.model.KYCNotificationBodyModel; import org.jetbrains.annotations.NotNull; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Map; import java.util.TimeZone; public abstract class AbstractKycNotificationBodyModelConverter<T extends KYCNotificationBodyModel> implements Converter<HyperwalletUser, T> { private final Converter<Object, T> toNotificationBodyModelConverter; protected AbstractKycNotificationBodyModelConverter(final Converter<Object, T> toNotificationBodyModelConverter) { this.toNotificationBodyModelConverter = toNotificationBodyModelConverter; } @Override public T convert(@NotNull final HyperwalletUser hyperwalletUser) { final ObjectMapper objectMapper = getObjectMapper(); final Map<String, Object> hyperwalletUserMap = objectMapper.convertValue(hyperwalletUser, Map.class); return toNotificationBodyModelConverter.convert(hyperwalletUserMap); } @SuppressWarnings("java:S1874") // Object mapper code comes from Hyperwallet SDK private ObjectMapper getObjectMapper() { final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); final SimpleFilterProvider filterProvider = new SimpleFilterProvider(); filterProvider.addFilter(HyperwalletJsonConfiguration.INCLUSION_FILTER, SimpleBeanPropertyFilter.serializeAll()); return new ObjectMapper().configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true) .configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true) .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false) .configure(SerializationFeature.WRITE_ENUMS_USING_INDEX, false).setDateFormat(dateFormat) .setFilterProvider(filterProvider).setSerializationInclusion(JsonInclude.Include.ALWAYS); } }
5,419
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/test/java/com/paypal
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/test/java/com/paypal/testsupport/TestDateUtilTest.java
package com.paypal.testsupport; import org.junit.jupiter.api.Test; import java.util.Date; import static org.assertj.core.api.Assertions.assertThat; class TestDateUtilTest { private TestDateUtil testObj; @Test void from() { assertThat(TestDateUtil.from("2020-01-01")).isEqualTo("2020-01-01"); } @Test void testFrom() { assertThat(TestDateUtil.from("yyyy-dd-MM", "2020-31-01")).isEqualTo("2020-01-31"); } @Test void withinInterval() { assertThat(TestDateUtil.withinInterval(new Date(), 1)).isTrue(); } @Test void currentDateMinusDays() { final Date currentDateMinus1Day = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000); assertThat(TestDateUtil.currentDateMinusDays(1)).isEqualTo(currentDateMinus1Day); } @Test void currentDateMinusDaysPlusSeconds() { final Date currentDateMinus1Day = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000 + 1000); assertThat(TestDateUtil.currentDateMinusDaysPlusSeconds(1, 1)).isEqualTo(currentDateMinus1Day); } }
5,420
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/integrationTest/java/com/paypal
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/integrationTest/java/com/paypal/testsupport/AbstractMockEnabledIntegrationTestTest.java
package com.paypal.testsupport; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; class AbstractMockEnabledIntegrationTestTest extends AbstractMockEnabledIntegrationTest { @Test void shouldStartIntegrationTestContext_AndCreateMocks() { assertNotNull(paymentsEndpointMock); assertNotNull(businessStakeHoldersEndpointMock); assertNotNull(usersEndpointMock); assertNotNull(miraklShopsEndpointMock); assertNotNull(miraklShopsDocumentsEndpointMock); assertNotNull(mockServerExpectationsLoader); assertNotNull(mockServerClient); } }
5,421
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/HyperwalletMiraklConnectorTestApplication.java
package com.paypal; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication @EnableJpaRepositories @EntityScan @SuppressWarnings("checkstyle:HideUtilityClassConstructor") public class HyperwalletMiraklConnectorTestApplication { protected HyperwalletMiraklConnectorTestApplication() { // Required by Checkstyle Rules } public static void main(final String[] args) { final SpringApplication app = new SpringApplication(HyperwalletMiraklConnectorTestApplication.class); app.run(args).getEnvironment(); } }
5,422
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/AbstractIntegrationTest.java
package com.paypal.testsupport; import org.mockserver.springtest.MockServerTest; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; @SpringBootTest(classes = IntegrationTestConfig.class) @MockServerTest("server.url=http://localhost:${mockServerPort}/api") @TestPropertySource({ "classpath:application-test.properties" }) @SuppressWarnings("java:S1610") public abstract class AbstractIntegrationTest { }
5,423
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/TestDateUtil.java
package com.paypal.testsupport; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public final class TestDateUtil { private TestDateUtil() { } public static Date from(final String date) { return from("yyyy-MM-dd", date); } public static Date from(final String format, final String date) { try { return new SimpleDateFormat(format).parse(date); } catch (final ParseException e) { throw new IllegalArgumentException(e); } } public static boolean withinInterval(final Date date, final int seconds) { final Date intervalStart = new Date(System.currentTimeMillis() - seconds * 1000); final Date intervalEnd = new Date(System.currentTimeMillis() + seconds * 1000); return date.after(intervalStart) && date.before(intervalEnd); } public static Date currentDateMinusDays(final long days) { return new Date(System.currentTimeMillis() - days * 24 * 60 * 60 * 1000); } public static Date currentDateMinusDaysPlusSeconds(final long days, final long seconds) { return new Date(System.currentTimeMillis() + (seconds * 1000) - (days * 24 * 60 * 60 * 1000)); } }
5,424
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/AbstractMockEnabledIntegrationTest.java
package com.paypal.testsupport; import com.paypal.testsupport.mocks.MockServerExpectationsLoader; import com.paypal.testsupport.mocks.hyperwallet.BusinessStakeHoldersEndpointMock; import com.paypal.testsupport.mocks.hyperwallet.PaymentsEndpointMock; import com.paypal.testsupport.mocks.hyperwallet.UsersEndpointMock; import com.paypal.testsupport.mocks.mirakl.MiraklShopsDocumentsEndpointMock; import com.paypal.testsupport.mocks.mirakl.MiraklShopsEndpointMock; import org.junit.jupiter.api.BeforeEach; import org.mockserver.client.MockServerClient; public abstract class AbstractMockEnabledIntegrationTest extends AbstractIntegrationTest { protected MockServerClient mockServerClient; protected PaymentsEndpointMock paymentsEndpointMock; protected BusinessStakeHoldersEndpointMock businessStakeHoldersEndpointMock; protected UsersEndpointMock usersEndpointMock; protected MiraklShopsEndpointMock miraklShopsEndpointMock; protected MiraklShopsDocumentsEndpointMock miraklShopsDocumentsEndpointMock; protected MockServerExpectationsLoader mockServerExpectationsLoader; @BeforeEach public void setMockEndpoints() { paymentsEndpointMock = new PaymentsEndpointMock(mockServerClient); businessStakeHoldersEndpointMock = new BusinessStakeHoldersEndpointMock(mockServerClient); usersEndpointMock = new UsersEndpointMock(mockServerClient); miraklShopsEndpointMock = new MiraklShopsEndpointMock(mockServerClient); miraklShopsDocumentsEndpointMock = new MiraklShopsDocumentsEndpointMock(mockServerClient); mockServerExpectationsLoader = new MockServerExpectationsLoader(mockServerClient); } }
5,425
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/TestJobExecutor.java
package com.paypal.testsupport; import com.paypal.infrastructure.support.date.DateUtil; import com.paypal.infrastructure.support.date.TimeMachine; import org.quartz.*; import org.quartz.listeners.JobListenerSupport; import org.springframework.lang.NonNull; import org.springframework.stereotype.Component; import java.time.ZoneId; import java.util.Date; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import static org.awaitility.Awaitility.await; @Component public class TestJobExecutor { private final Scheduler scheduler; protected static final Set<String> runningJobs = ConcurrentHashMap.newKeySet(); protected final JobRunningListener jobRunningListener = new JobRunningListener(); public TestJobExecutor(final Scheduler scheduler) { this.scheduler = scheduler; } public void executeJobAndWaitForCompletion(@NonNull final Class<? extends Job> clazz) { executeJobAndWaitForCompletion(clazz, Map.of()); } public void executeJobAndWaitForCompletion(@NonNull final Class<? extends Job> clazz, @NonNull final Map<String, Object> parameters) { //@formatter:off final Date scheduling = DateUtil.convertToDate(TimeMachine.now(), ZoneId.systemDefault()); final String jobName = clazz.getSimpleName() + "-" + System.nanoTime(); final JobDetail jobExecution = JobBuilder.newJob(clazz) .withIdentity(jobName) .usingJobData(new JobDataMap(parameters)) .storeDurably() .build(); final Trigger singleJobExecutionTrigger = TriggerBuilder.newTrigger() .forJob(jobExecution) .startAt(scheduling) .build(); //@formatter:on try { if (!scheduler.getListenerManager().getJobListeners().contains(jobRunningListener)) { scheduler.getListenerManager().addJobListener(jobRunningListener); } scheduler.addJob(jobExecution, true); runningJobs.add(jobName); scheduler.scheduleJob(singleJobExecutionTrigger); } catch (final SchedulerException e) { throw new IllegalArgumentException(e); } waitForJobToFinish(jobName); } protected void waitForJobToFinish(final String jobName) { await().atMost(2, TimeUnit.MINUTES).until(() -> !runningJobs.contains(jobName)); } protected static class JobRunningListener extends JobListenerSupport { @Override public String getName() { return "jobRunningListener"; } @Override public void jobWasExecuted(final JobExecutionContext context, final JobExecutionException jobException) { runningJobs.remove(context.getJobDetail().getKey().getName()); } } }
5,426
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/IntegrationTestConfig.java
package com.paypal.testsupport; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletConnectionConfiguration; import com.paypal.infrastructure.mirakl.configuration.MiraklApiClientConfig; import jakarta.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.TestConfiguration; @TestConfiguration //@formatter:off public class IntegrationTestConfig { @Value("${server.url}") private String serverUrl; private final MiraklApiClientConfig miraklApiClientConfig; private final HyperwalletConnectionConfiguration hyperwalletConnectionConfiguration; public IntegrationTestConfig(final MiraklApiClientConfig miraklApiClientConfig, final HyperwalletConnectionConfiguration hyperwalletConnectionConfiguration) { this.miraklApiClientConfig = miraklApiClientConfig; this.hyperwalletConnectionConfiguration = hyperwalletConnectionConfiguration; } @PostConstruct public void setupClients() { miraklApiClientConfig.setEnvironment(serverUrl); hyperwalletConnectionConfiguration.setServer(serverUrl); } }
5,427
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/mocks/AbstractMockServerFixtures.java
package com.paypal.testsupport.mocks; import org.mockserver.client.MockServerClient; import org.mockserver.model.MediaType; import org.mockserver.model.Parameter; import org.springframework.util.ResourceUtils; import java.io.File; import java.nio.file.Files; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; public abstract class AbstractMockServerFixtures { protected final MockServerClient mockServerClient; protected AbstractMockServerFixtures(final MockServerClient mockServerClient) { this.mockServerClient = mockServerClient; } protected void mockGet(final String path, final String responseFile, final int statusCode, final Map<String, String> pathParams) { //@formatter:off mockServerClient .when(request() .withMethod("GET") .withPath(path) .withPathParameters(pathParams.entrySet() .stream() .map(entry -> new Parameter(entry.getKey(), entry.getValue())) .collect(Collectors.toList()))) .respond(response() .withStatusCode(statusCode) .withContentType(MediaType.APPLICATION_JSON) .withBody(loadResource(responseFile))); //@formatter:on } protected void mockGet(final String path, final String responseFile, final int statusCode) { //@formatter:off mockServerClient .when(request() .withMethod("GET") .withPath(path)) .respond(response() .withStatusCode(statusCode) .withContentType(MediaType.APPLICATION_JSON) .withBody(loadResource(responseFile))); //@formatter:on } protected void mockGet(final String path, final Map<String, List<String>> queryParameters, final String responseFile, final int statusCode) { //@formatter:off mockServerClient .when(request() .withMethod("GET") .withPath(path) .withQueryStringParameters(queryParameters)) .respond(response() .withStatusCode(statusCode) .withContentType(MediaType.APPLICATION_JSON) .withBody(loadResource(responseFile))); //@formatter:on } protected String loadResource(final String responseFile) { return loadResource(responseFile, Map.of()); } protected String loadResource(final String responseFile, final Map<String, String> bodyReplacements) { try { final File file = ResourceUtils.getFile("classpath:" + getFolder() + "/" + responseFile); String body = new String(Files.readAllBytes(file.toPath())); for (final Map.Entry<String, String> entry : bodyReplacements.entrySet()) { body = body.replace(entry.getKey(), entry.getValue()); } return body; } catch (final Exception e) { throw new IllegalArgumentException(e); } } protected abstract String getFolder(); }
5,428
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/mocks/MockServerExpectationsLoader.java
package com.paypal.testsupport.mocks; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.mockserver.client.MockServerClient; import org.mockserver.mock.Expectation; import org.mockserver.serialization.ObjectMapperFactory; import org.mockserver.serialization.model.ExpectationDTO; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.lang.NonNull; import org.springframework.util.ResourceUtils; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Arrays; import java.util.Map; import java.util.Objects; public class MockServerExpectationsLoader { private final ObjectMapper objectMapper = ObjectMapperFactory.createObjectMapper(); private final MockServerClient mockServerClient; public MockServerExpectationsLoader(final MockServerClient mockServerClient) { this.mockServerClient = mockServerClient; } public void loadExpectationsFromFolder(final String folder, final String prefix, final Map<String, String> responseBodyReplacements) { //@formatter:off final Resource[] resources = getFolderResources(folder); Arrays.stream(resources) .map(Resource::getFilename) .filter(Objects::nonNull) .filter(filename -> filename.contains(prefix) && filename.endsWith("-expectation.json")) .map(fn -> "%s/%s".formatted(folder, fn)) .map(this::loadResource) .map(this::loadExpectation) .map(e -> applyBodyReplacements(e, responseBodyReplacements)) .forEach(mockServerClient::upsert); //@formatter:on } private Expectation applyBodyReplacements(final Expectation expectation, final Map<String, String> bodyReplacements) { final String newBody = applyBodyReplacements(new String(expectation.getHttpResponse().getBody().getRawBytes()), bodyReplacements); expectation.getHttpResponse().withBody(newBody); return expectation; } private String applyBodyReplacements(final String body, final Map<String, String> bodyReplacements) { String replacedBody = body; for (final Map.Entry<String, String> entry : bodyReplacements.entrySet()) { replacedBody = replacedBody.replace(entry.getKey(), entry.getValue()); } return replacedBody; } @NonNull private Expectation loadExpectation(final String expectationJson) { try { return objectMapper.readValue(expectationJson, ExpectationDTO.class).buildObject(); } catch (final JsonProcessingException e) { throw new IllegalStateException(e); } } @NonNull private Resource[] getFolderResources(final String folder) { final ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resources = new Resource[0]; try { resources = resolver.getResources("classpath:" + folder + "/*"); } catch (final IOException e) { throw new IllegalStateException(e); } return resources; } private String loadResource(final String responseFile) { try { final File file = ResourceUtils.getFile("classpath:" + responseFile); return new String(Files.readAllBytes(file.toPath())); } catch (final Exception e) { throw new IllegalArgumentException(e); } } }
5,429
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/mocks
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/mocks/hyperwallet/PaymentsEndpointMock.java
package com.paypal.testsupport.mocks.hyperwallet; import com.hyperwallet.clientsdk.model.HyperwalletList; import com.hyperwallet.clientsdk.model.HyperwalletPayment; import com.hyperwallet.clientsdk.util.HyperwalletJsonUtil; import com.nimbusds.jose.shaded.gson.Gson; import org.mockserver.client.MockServerClient; import org.mockserver.model.MediaType; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; public class PaymentsEndpointMock { private static final String URL = "/api/rest/v4/payments"; private static final String PARAMETER_CLIENT_PAYMENT_ID = "clientPaymentId"; private final MockServerClient mockServerClient; public PaymentsEndpointMock(final MockServerClient mockServerClient) { this.mockServerClient = mockServerClient; } public void createPaymentRequest(final HyperwalletPayment payment) { mockServerClient .when(request().withMethod(HttpMethod.POST.name()).withPath(URL) .withBody(HyperwalletJsonUtil.toJson(payment))) .respond( response().withStatusCode(HttpStatus.OK.value()).withBody(HyperwalletJsonUtil.toJson(payment))); } public void createPaymentErrorRequest(final HyperwalletPayment payment) { mockServerClient .when(request().withMethod(HttpMethod.POST.name()).withPath(URL) .withBody(HyperwalletJsonUtil.toJson(payment))) .respond(response().withStatusCode(HttpStatus.BAD_REQUEST.value())); } public void listPaymentsRequest(final String clientPaymentId, final Collection<String> statuses) { final HyperwalletList<HyperwalletPayment> response = createHyperwalletListWithStatus(statuses); mockServerClient .when(request().withMethod(HttpMethod.GET.name()).withPath(URL) .withQueryStringParameter(PARAMETER_CLIENT_PAYMENT_ID, clientPaymentId)) .respond(response().withStatusCode(HttpStatus.OK.value()).withContentType(MediaType.APPLICATION_JSON) .withBody(new Gson().toJson(response))); } public void listPaymentsErrorRequest(final String clientPaymentId) { mockServerClient .when(request().withMethod(HttpMethod.GET.name()).withPath(URL) .withQueryStringParameter(PARAMETER_CLIENT_PAYMENT_ID, clientPaymentId)) .respond(response().withStatusCode(HttpStatus.BAD_REQUEST.value()) .withContentType(MediaType.APPLICATION_JSON)); } private HyperwalletList<HyperwalletPayment> createHyperwalletListWithStatus(final Collection<String> statuses) { final HyperwalletList<HyperwalletPayment> response = new HyperwalletList<>(); final List<HyperwalletPayment> dataWithAllFailures = statuses.stream() .map(status -> new HyperwalletPayment().status(status)).collect(Collectors.toUnmodifiableList()); response.setData(dataWithAllFailures); return response; } }
5,430
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/mocks
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/mocks/hyperwallet/BusinessStakeHoldersEndpointMock.java
package com.paypal.testsupport.mocks.hyperwallet; import com.hyperwallet.clientsdk.model.HyperwalletBusinessStakeholder; import com.hyperwallet.clientsdk.util.HyperwalletJsonUtil; import org.mockserver.client.MockServerClient; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.verify.VerificationTimes.exactly; public class BusinessStakeHoldersEndpointMock { private static final String URL = "/api/rest/v4/users/%s/business-stakeholders/"; private final MockServerClient mockServerClient; public BusinessStakeHoldersEndpointMock(final MockServerClient mockServerClient) { this.mockServerClient = mockServerClient; } public void uploadDocument(final String userToken, final String token) { final String url = getUrl(userToken).concat(token); mockServerClient.when(request().withMethod(HttpMethod.PUT.name()).withPath(url)) .respond(response().withStatusCode(HttpStatus.OK.value()) .withBody(HyperwalletJsonUtil.toJson(new HyperwalletBusinessStakeholder()))); } public void verifyUploadDocument(final String userToken, final String token) { final String url = getUrl(userToken).concat(token); mockServerClient.verify(request().withMethod(HttpMethod.PUT.name()).withPath(url), exactly(1)); } private String getUrl(final String userToken) { return URL.formatted(userToken); } }
5,431
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/mocks
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/mocks/hyperwallet/UsersEndpointMock.java
package com.paypal.testsupport.mocks.hyperwallet; import com.hyperwallet.clientsdk.model.HyperwalletUser; import com.hyperwallet.clientsdk.util.HyperwalletJsonUtil; import org.mockserver.client.MockServerClient; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.verify.VerificationTimes.exactly; public class UsersEndpointMock { private static final String URL = "/api/rest/v4/users/%s"; private final MockServerClient mockServerClient; public UsersEndpointMock(final MockServerClient mockServerClient) { this.mockServerClient = mockServerClient; } public void updatedUser(final String userToken) { final String json = HyperwalletJsonUtil.toJson(createHyperwalletUser(userToken)); final String url = getUrl(userToken); mockServerClient.when(request().withMethod(HttpMethod.PUT.name()).withPath(url).withBody(json)) .respond(response().withStatusCode(HttpStatus.OK.value()).withBody(json)); } public void verifyUpdatedUser(final String userToken) { final String json = HyperwalletJsonUtil.toJson(createHyperwalletUser(userToken)); final String url = getUrl(userToken); mockServerClient.verify(request().withMethod(HttpMethod.PUT.name()).withPath(url).withBody(json), exactly(1)); } private static String getUrl(final String userToken) { return URL.formatted(userToken); } private static HyperwalletUser createHyperwalletUser(final String userToken) { final HyperwalletUser user = new HyperwalletUser(); user.setToken(userToken); user.setBusinessStakeholderVerificationStatus( HyperwalletUser.BusinessStakeholderVerificationStatus.READY_FOR_REVIEW); return user; } }
5,432
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/mocks
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/mocks/mirakl/MiraklShopsDocumentsEndpointMock.java
package com.paypal.testsupport.mocks.mirakl; import org.mockserver.client.MockServerClient; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import static org.springframework.http.HttpHeaders.CONTENT_DISPOSITION; import static org.springframework.http.HttpHeaders.CONTENT_TYPE; public class MiraklShopsDocumentsEndpointMock extends AbstractResourceLoadingEndpointMock { private static final String URL = "/api/shops/documents"; private static final String URL_DOWNLOAD = "/api/shops/documents/download"; public static final String MOCKS_FOLDER = "mocks/mirakl/shops/documents"; public MiraklShopsDocumentsEndpointMock(final MockServerClient mockServerClient) { super(mockServerClient); } public void getShopDocuments(final String shopId, final String responseFile) { final String responseFileContent = loadResource(responseFile); //@formatter:off mockServerClient .when(request() .withMethod(HttpMethod.GET.name()) .withPath(URL) .withQueryStringParameter("shop_ids", shopId)) .respond(response() .withStatusCode(HttpStatus.OK.value()) .withBody(responseFileContent)); //@formatter:on } public void getShopDocument(final String documentId, final String responseFile) { final byte[] responseFileContent = loadResourceAsBinary(responseFile); //@formatter:off mockServerClient .when(request() .withMethod(HttpMethod.GET.name()) .withPath(URL_DOWNLOAD) .withQueryStringParameter("document_ids", documentId)) .respond(response() .withStatusCode(HttpStatus.OK.value()) .withHeaders( header(CONTENT_TYPE, MediaType.IMAGE_PNG.toString()), header(CONTENT_DISPOSITION, "attachment; filename=\"" + responseFile + "\"") ) .withBody(binary(responseFileContent))); //@formatter:on } @Override protected String getFolder() { return MOCKS_FOLDER; } }
5,433
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/mocks
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/mocks/mirakl/MiraklShopsEndpointMock.java
package com.paypal.testsupport.mocks.mirakl; import com.fasterxml.jackson.core.JsonProcessingException; import com.mirakl.client.mmp.domain.shop.MiraklShop; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdateShop; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdateShops; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdatedShopReturn; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdatedShops; import com.mirakl.client.mmp.operator.request.shop.MiraklUpdateShopsRequest; import com.mirakl.client.mmp.request.additionalfield.MiraklRequestAdditionalFieldValue; import org.mockserver.client.MockServerClient; import org.mockserver.model.Parameter; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import java.util.Date; import java.util.List; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.verify.VerificationTimes.exactly; public class MiraklShopsEndpointMock extends AbstractResourceLoadingEndpointMock { private static final String URL = "/api/shops"; private static final String MOCKS_FOLDER = "mocks/mirakl/shops"; public MiraklShopsEndpointMock(final MockServerClient mockServerClient) { super(mockServerClient); } public void getShops(final Date updatedSince, final boolean paginate, final String responseFile) { final String jsonReturned = loadResource(responseFile); //@formatter:off mockServerClient .when(request() .withMethod(HttpMethod.GET.name()) .withPath(URL) .withQueryStringParameters( new Parameter("updated_since", updatedSince.toInstant().toString()), new Parameter("paginate", String.valueOf(paginate)))) .respond(response() .withStatusCode(HttpStatus.OK.value()) .withBody(jsonReturned)); //@formatter:on } public void updateDocument(final String shopId) throws JsonProcessingException { final MiraklUpdatedShops dtoReturned = createUpdateShopReturn(shopId); final MiraklUpdateShopsRequest dtoRequested = createUpdateShopRequest(Long.parseLong(shopId)); final String jsonReturned = mapper.writeValueAsString(dtoReturned); final String jsonRequested = mapper.writeValueAsString(new MiraklUpdateShops(dtoRequested.getShops())); mockServerClient.when(request().withMethod(HttpMethod.PUT.name()).withPath(URL).withBody(jsonRequested)) .respond(response().withStatusCode(HttpStatus.OK.value()).withBody(jsonReturned)); } public void verifyUpdateDocument(final Long shopId) throws JsonProcessingException { final MiraklUpdateShopsRequest expected = createUpdateShopRequest(shopId); final String jsonRequested = mapper.writeValueAsString(new MiraklUpdateShops(expected.getShops())); mockServerClient.verify(request().withMethod(HttpMethod.PUT.name()).withPath(URL).withBody(jsonRequested), exactly(1)); } private static MiraklUpdateShopsRequest createUpdateShopRequest(final long shopId) { final MiraklUpdateShop shop = new MiraklUpdateShop(); shop.setShopId(shopId); shop.setAdditionalFieldValues( List.of(new MiraklRequestAdditionalFieldValue.MiraklSimpleRequestAdditionalFieldValue( "hw-kyc-req-proof-authorization", "false"))); return new MiraklUpdateShopsRequest(List.of(shop)); } private static MiraklUpdatedShops createUpdateShopReturn(final String shopId) { final MiraklShop shop = new MiraklShop(); shop.setId(shopId); final MiraklUpdatedShopReturn returnWrapper = new MiraklUpdatedShopReturn(); returnWrapper.setShopUpdated(shop); final MiraklUpdatedShops value = new MiraklUpdatedShops(); value.setShopReturns(List.of(returnWrapper)); return value; } @Override protected String getFolder() { return MOCKS_FOLDER; } }
5,434
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/mocks
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/mocks/mirakl/AbstractResourceLoadingEndpointMock.java
package com.paypal.testsupport.mocks.mirakl; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import org.mockserver.client.MockServerClient; import org.springframework.util.ResourceUtils; import java.io.File; import java.nio.file.Files; public abstract class AbstractResourceLoadingEndpointMock { protected final ObjectMapper mapper; protected final MockServerClient mockServerClient; @SuppressWarnings("java:S1874") protected AbstractResourceLoadingEndpointMock(final MockServerClient mockServerClient) { this.mapper = new ObjectMapper(); this.mockServerClient = mockServerClient; this.mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); this.mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); } protected String loadResource(final String responseFile) { try { final File file = ResourceUtils.getFile("classpath:" + getFolder() + "/" + responseFile); return new String(Files.readAllBytes(file.toPath())); } catch (final Exception e) { throw new IllegalArgumentException(e); } } protected byte[] loadResourceAsBinary(final String responseFile) { try { final File file = ResourceUtils.getFile("classpath:" + getFolder() + "/" + responseFile); return Files.readAllBytes(file.toPath()); } catch (final Exception e) { throw new IllegalArgumentException(e); } } protected abstract String getFolder(); }
5,435
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/archrules/SliceLayeredModuleWeakenedLayerProtectionRules.java
package com.paypal.testsupport.archrules; import com.tngtech.archunit.junit.ArchTest; import com.tngtech.archunit.lang.ArchRule; import static com.tngtech.archunit.library.Architectures.layeredArchitecture; public final class SliceLayeredModuleWeakenedLayerProtectionRules { private SliceLayeredModuleWeakenedLayerProtectionRules() { // Deliberately empty } @ArchTest public static final ArchRule layerAccessProtections = layeredArchitecture().consideringAllDependencies() .layer("Controller").definedBy("..controllers..").layer("Persistence").definedBy("..repositories") .layer("Connector").definedBy("..connectors..").layer("Service").definedBy("..services..") .withOptionalLayers(true).whereLayer("Controller").mayNotBeAccessedByAnyLayer(); }
5,436
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/archrules/SliceLayeredModuleLayerProtectionRules.java
package com.paypal.testsupport.archrules; import com.tngtech.archunit.junit.ArchTest; import com.tngtech.archunit.lang.ArchRule; import static com.tngtech.archunit.library.Architectures.layeredArchitecture; import static com.tngtech.archunit.library.dependencies.SlicesRuleDefinition.slices; public final class SliceLayeredModuleLayerProtectionRules { private SliceLayeredModuleLayerProtectionRules() { // Deliberately empty } @ArchTest public static final ArchRule layerAccessProtections = layeredArchitecture().consideringAllDependencies() .layer("Controller").definedBy("..controllers..").layer("Persistence").definedBy("..repositories") .layer("Connector").definedBy("..connectors..").layer("Service").definedBy("..services..") .withOptionalLayers(true).whereLayer("Controller").mayNotBeAccessedByAnyLayer(); @ArchTest public static final ArchRule sliceNoCycles = slices().matching("..com.paypal.*.(*)..").should().beFreeOfCycles(); }
5,437
0
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport
Create_ds/mirakl-hyperwallet-connector/hmc-testsupport/src/main/java/com/paypal/testsupport/archrules/SliceLayeredModulePackageStructureRules.java
package com.paypal.testsupport.archrules; import com.paypal.infrastructure.support.converter.Converter; import com.tngtech.archunit.junit.ArchTest; import com.tngtech.archunit.lang.ArchRule; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.RestController; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; public final class SliceLayeredModulePackageStructureRules { private SliceLayeredModulePackageStructureRules() { // Deliberately empty } @ArchTest public static final ArchRule servicesOnCorrectPackage = classes().that().areAnnotatedWith(Service.class).should() .resideInAnyPackage("..services..").allowEmptyShould(true); @ArchTest public static final ArchRule repositoriesOnCorrectPackage = classes().that().areAnnotatedWith(Repository.class) .should().resideInAnyPackage("..repositories..").allowEmptyShould(true); @ArchTest public static final ArchRule controllersOnCorrectPackage = classes().that().areAnnotatedWith(RestController.class) .should().resideInAnyPackage("..controllers..").allowEmptyShould(true); @ArchTest public static final ArchRule convertersOnCorrectPackage = classes().that().implement(Converter.class).should() .resideInAnyPackage("..converters..").allowEmptyShould(true); }
5,438
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/InfrastructureArchTest.java
package com.paypal.infrastructure; import com.paypal.testsupport.archrules.SliceLayeredModuleLayerProtectionRules; import com.paypal.testsupport.archrules.SliceLayeredModulePackageStructureRules; import com.tngtech.archunit.core.importer.ImportOption; import com.tngtech.archunit.junit.AnalyzeClasses; import com.tngtech.archunit.junit.ArchTest; import com.tngtech.archunit.junit.ArchTests; @AnalyzeClasses(packages = "com.paypal.infrastructure", importOptions = ImportOption.DoNotIncludeTests.class) public class InfrastructureArchTest { @ArchTest public static final ArchTests packageRules = ArchTests.in(SliceLayeredModulePackageStructureRules.class); @ArchTest public static final ArchTests layerRules = ArchTests.in(SliceLayeredModuleLayerProtectionRules.class); }
5,439
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/encryption
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/encryption/controllers/JwkSetControllerTest.java
package com.paypal.infrastructure.encryption.controllers; import com.fasterxml.jackson.databind.ObjectMapper; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletEncryptionConfiguration; import net.minidev.json.JSONObject; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.io.Resource; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class JwkSetControllerTest { private static final String FILENAME = "filename.txt"; @Spy @InjectMocks private JwkSetController testObj; @Mock private HyperwalletEncryptionConfiguration hyperwalletEncryptionConfigurationMock; @Mock private Resource errorSourceMock; @Mock private ObjectMapper objectMapperMock; @Mock private InputStream publicKeysFromFileMock, errorMessageMock; @BeforeEach void setUp() { testObj.errorResource = errorSourceMock; } @Test void getPublicKeys_should() throws IOException { doReturn(publicKeysFromFileMock).when(testObj).getPublicKeysFromFile(); testObj.getPublicKeys(); verify(objectMapperMock).readValue(publicKeysFromFileMock, JSONObject.class); } @Test void getPublicKeys_shouldSendMessageErrorWhenFileNotFound() throws IOException { when(hyperwalletEncryptionConfigurationMock.getHmcPublicKeyLocation()).thenReturn(FILENAME); final FileNotFoundException fileNotFoundException = new FileNotFoundException("Something bad happened"); doThrow(fileNotFoundException).when(testObj).getPublicKeysFromFile(); when(errorSourceMock.getInputStream()).thenReturn(errorMessageMock); testObj.getPublicKeys(); verify(objectMapperMock).readValue(errorMessageMock, JSONObject.class); } }
5,440
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/changestaging
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/changestaging/service/ChangeStagingServiceImplTest.java
package com.paypal.infrastructure.changestaging.service; import com.paypal.infrastructure.changestaging.model.Change; import com.paypal.infrastructure.changestaging.model.StagedChange; import com.paypal.infrastructure.changestaging.repositories.StagedChangesRepository; import com.paypal.infrastructure.changestaging.repositories.entities.StagedChangeEntity; import com.paypal.infrastructure.changestaging.service.converters.StagedChangesEntityConverter; import com.paypal.infrastructure.changestaging.service.converters.StagedChangesModelConverter; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class ChangeStagingServiceImplTest { @InjectMocks @Spy private ChangeStagingServiceImpl testObj; @Mock private StagedChangesModelConverter stagedChangesModelConverterMock; @Mock private StagedChangesEntityConverter stagedChangesEntityConverterMock; @Mock private StagedChangesRepository stagedChangeRepositoryMock; @Test void stageChange_shouldCreateStageChange_andStoreIt() { // given final Change change = mock(Change.class); final StagedChange stagedChange = mock(StagedChange.class); final StagedChangeEntity stagedChangeEntity = mock(StagedChangeEntity.class); when(stagedChangesModelConverterMock.from(change)).thenReturn(stagedChange); when(stagedChangesEntityConverterMock.from(stagedChange)).thenReturn(stagedChangeEntity); // when final StagedChange result = testObj.stageChange(change); // then assertThat(result).isEqualTo(stagedChange); verify(stagedChangeRepositoryMock).save(stagedChangeEntity); } @Test void stageChanges_shouldInvokeStageChange_forEveryChange() { // given final Change change1 = mock(Change.class); final Change change2 = mock(Change.class); final StagedChange stagedChange1 = mock(StagedChange.class); final StagedChange stagedChange2 = mock(StagedChange.class); doReturn(stagedChange1).when(testObj).stageChange(change1); doReturn(stagedChange2).when(testObj).stageChange(change2); // when final List<StagedChange> result = testObj.stageChanges(List.of(change1, change2)); // then assertThat(result).containsExactlyInAnyOrder(stagedChange1, stagedChange2); } }
5,441
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/changestaging/service
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/changestaging/service/operations/StagedChangesOperationRegistryTest.java
package com.paypal.infrastructure.changestaging.service.operations; import com.paypal.infrastructure.changestaging.model.ChangeOperation; import com.paypal.infrastructure.changestaging.model.ChangeTarget; import com.paypal.infrastructure.changestaging.model.StagedChange; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import java.util.List; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @ExtendWith(MockitoExtension.class) class StagedChangesOperationRegistryTest { private StagedChangesOperationRegistry testObj; @Test void getStagedChangesExecutor_shouldReturnMatchingExecutor() { // given final StagedChangesExecutorInfo stagedChangesExecutorInfo1 = new StagedChangesExecutorInfo(Integer.class, ChangeOperation.UPDATE, ChangeTarget.MIRAKL); final StagedChangesExecutorInfo stagedChangesExecutorInfo2 = new StagedChangesExecutorInfo(Long.class, ChangeOperation.UPDATE, ChangeTarget.MIRAKL); final StagedChangesExecutor stagedChangesExecutor1 = new MyStagedChangesExecutor(stagedChangesExecutorInfo1); final StagedChangesExecutor stagedChangesExecutor2 = new MyStagedChangesExecutor(stagedChangesExecutorInfo2); testObj = new StagedChangesOperationRegistry(List.of(stagedChangesExecutor1, stagedChangesExecutor2)); // when final StagedChangesExecutor result = testObj.getStagedChangesExecutor( new StagedChangesExecutorInfo(Integer.class, ChangeOperation.UPDATE, ChangeTarget.MIRAKL)); // then assertThat(result.getExecutorInfo().getType()).isEqualTo(Integer.class); } @Test void getAllStagedChangesExecutorInfo_shouldReturnAllExecutors() { // given final StagedChangesExecutorInfo stagedChangesExecutorInfo1 = new StagedChangesExecutorInfo(Integer.class, ChangeOperation.UPDATE, ChangeTarget.MIRAKL); final StagedChangesExecutorInfo stagedChangesExecutorInfo2 = new StagedChangesExecutorInfo(Long.class, ChangeOperation.UPDATE, ChangeTarget.MIRAKL); final StagedChangesExecutor stagedChangesExecutor1 = new MyStagedChangesExecutor(stagedChangesExecutorInfo1); final StagedChangesExecutor stagedChangesExecutor2 = new MyStagedChangesExecutor(stagedChangesExecutorInfo2); testObj = new StagedChangesOperationRegistry(List.of(stagedChangesExecutor1, stagedChangesExecutor2)); // when final Set<StagedChangesExecutorInfo> result = testObj.getAllStagedChangesExecutorInfo(); // then assertThat(result).containsExactlyInAnyOrder(stagedChangesExecutorInfo1, stagedChangesExecutorInfo2); } @Test void getAllStagedChangesExecutorInfo_shouldReturnEmpty_whenThereAreNoExecutors() { // given testObj = new StagedChangesOperationRegistry(List.of()); // when final Set<StagedChangesExecutorInfo> result = testObj.getAllStagedChangesExecutorInfo(); // then assertThat(result).isEmpty(); } private static class MyStagedChangesExecutor implements StagedChangesExecutor { private final StagedChangesExecutorInfo stagedChangesExecutorInfo; private MyStagedChangesExecutor(final StagedChangesExecutorInfo stagedChangesExecutorInfo) { this.stagedChangesExecutorInfo = stagedChangesExecutorInfo; } @Override public void execute(final List<StagedChange> changes) { // do nothing for tests } @Override public StagedChangesExecutorInfo getExecutorInfo() { return stagedChangesExecutorInfo; } } }
5,442
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mail
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mail/services/MailNotificationUtilImplTest.java
package com.paypal.infrastructure.mail.services; import com.callibrity.logging.test.LogTracker; import com.callibrity.logging.test.LogTrackerStub; import com.paypal.infrastructure.mail.configuration.MailConfiguration; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class MailNotificationUtilImplTest { @RegisterExtension final LogTrackerStub logTrackerStub = LogTrackerStub.create().recordForLevel(LogTracker.LogLevel.ERROR) .recordForType(MailNotificationUtilImpl.class); private static final String SUBJECT = "Subject"; private static final String BODY = "Body"; private static final String FROM_EMAIL = "from@mail.com"; private static final String RECIPIENTS_EMAILS = "recipient1@mail.com"; @InjectMocks private MailNotificationUtilImpl testObj; @Captor private ArgumentCaptor<SimpleMailMessage> simpleMailMessageCaptor; @Mock private MailConfiguration sellersMailConfigurationMock; @Mock private JavaMailSender javaMailSenderMock; @Test void sendPlainTextEmailWithMessagePrefix_shouldSendAnEmailWithInformationProvided() { when(sellersMailConfigurationMock.getFromNotificationEmail()).thenReturn(FROM_EMAIL); when(sellersMailConfigurationMock.getNotificationRecipients()).thenReturn(RECIPIENTS_EMAILS); testObj.sendPlainTextEmail(SUBJECT, BODY); verify(javaMailSenderMock).send(simpleMailMessageCaptor.capture()); final SimpleMailMessage emailContent = simpleMailMessageCaptor.getValue(); assertThat(emailContent.getSubject()).isEqualTo(SUBJECT); assertThat(emailContent.getText()).isEqualTo(BODY); assertThat(emailContent.getFrom()).isEqualTo(FROM_EMAIL); assertThat(emailContent.getTo()).containsExactlyInAnyOrder(RECIPIENTS_EMAILS); } @Test void sendPlainTextEmailWithMessagePrefix_shouldNotRethrowAnExceptionWhenSendingEmailFails() { logTrackerStub.recordForLevel(LogTracker.LogLevel.ERROR); doThrow(new RuntimeException("Something went wrong")).when(javaMailSenderMock) .send(any(SimpleMailMessage.class)); testObj.sendPlainTextEmail(SUBJECT, BODY); assertThat(logTrackerStub.contains("Email could not be sent.")).isTrue(); } }
5,443
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/itemlinks
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/itemlinks/converters/ItemLinksModelEntityConverterTest.java
package com.paypal.infrastructure.itemlinks.converters; import com.paypal.infrastructure.itemlinks.entities.ItemLinkEntity; import com.paypal.infrastructure.itemlinks.model.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mapstruct.factory.Mappers; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(MockitoExtension.class) class ItemLinksModelEntityConverterTest { @Spy private final ItemLinksModelEntityConverter testObj = Mappers.getMapper(ItemLinksModelEntityConverter.class); @Test void hyperwalletLocatorFromLinkTarget_shouldCreateHyperwalletItemLocator() { //@formatter:off final ItemLinkEntity itemLinkEntity = ItemLinkEntity.builder() .sourceSystem(ItemLinkExternalSystem.MIRAKL.toString()) .sourceType(MiraklItemTypes.SHOP.toString()) .sourceId("M1") .targetSystem(ItemLinkExternalSystem.HYPERWALLET.toString()) .targetType(HyperwalletItemTypes.BANK_ACCOUNT.toString()) .targetId("H1") .build(); //@formatter:on final HyperwalletItemLinkLocator result = testObj.hyperwalletLocatorFromLinkTarget(itemLinkEntity); assertThat(result.getId()).isEqualTo("H1"); assertThat(result.getType()).isEqualTo(HyperwalletItemTypes.BANK_ACCOUNT); } @Test void from_shouldCreateEntityFromLocators() { final HyperwalletItemLinkLocator hyperwalletItemLocator = new HyperwalletItemLinkLocator("H1", HyperwalletItemTypes.PAYMENT); final MiraklItemLinkLocator miraklItemLocator = new MiraklItemLinkLocator("M1", MiraklItemTypes.SHOP); final ItemLinkEntity itemLinkEntity = testObj.from(miraklItemLocator, hyperwalletItemLocator); assertThat(itemLinkEntity.getSourceId()).isEqualTo("M1"); assertThat(itemLinkEntity.getSourceType()).isEqualTo(MiraklItemTypes.SHOP.toString()); assertThat(itemLinkEntity.getSourceSystem()).isEqualTo(ItemLinkExternalSystem.MIRAKL.toString()); assertThat(itemLinkEntity.getTargetId()).isEqualTo("H1"); assertThat(itemLinkEntity.getTargetType()).isEqualTo(HyperwalletItemTypes.PAYMENT.toString()); assertThat(itemLinkEntity.getTargetSystem()).isEqualTo(ItemLinkExternalSystem.HYPERWALLET.toString()); } }
5,444
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/itemlinks
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/itemlinks/services/ItemLinksServiceImplTest.java
package com.paypal.infrastructure.itemlinks.services; import com.paypal.infrastructure.itemlinks.converters.ItemLinksModelEntityConverter; import com.paypal.infrastructure.itemlinks.entities.ItemLinkEntity; import com.paypal.infrastructure.itemlinks.model.*; import com.paypal.infrastructure.itemlinks.repositories.ItemLinkRepository; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class ItemLinksServiceImplTest { @InjectMocks private ItemLinksServiceImpl testObj; @Mock private ItemLinkRepository itemLinkRepositoryMock; @Mock private ItemLinksModelEntityConverter itemLinksModelEntityConverterMock; @Mock private HyperwalletItemLinkLocator hyperwalletItemLinkLocator1Mock, hyperwalletItemLinkLocator2Mock; @Mock private MiraklItemLinkLocator miraklItemLinkLocator1Mock, miraklItemLinkLocator2Mock; @Mock private ItemLinkEntity itemLinkEntity1Mock, itemLinkEntity2Mock; @Test void createLinks() { when(itemLinksModelEntityConverterMock.from(miraklItemLinkLocator1Mock, hyperwalletItemLinkLocator1Mock)) .thenReturn(itemLinkEntity1Mock); when(itemLinksModelEntityConverterMock.from(miraklItemLinkLocator1Mock, hyperwalletItemLinkLocator2Mock)) .thenReturn(itemLinkEntity2Mock); testObj.createLinks(miraklItemLinkLocator1Mock, List.of(hyperwalletItemLinkLocator1Mock, hyperwalletItemLinkLocator2Mock)); verify(itemLinkRepositoryMock).saveAll(Set.of(itemLinkEntity1Mock, itemLinkEntity2Mock)); } @Test void findLinks() { when(miraklItemLinkLocator1Mock.getId()).thenReturn("H1"); when(miraklItemLinkLocator1Mock.getType()).thenReturn(MiraklItemTypes.SHOP); when(miraklItemLinkLocator1Mock.getSystem()).thenReturn(ItemLinkExternalSystem.MIRAKL); when(miraklItemLinkLocator2Mock.getId()).thenReturn("H2"); when(miraklItemLinkLocator2Mock.getType()).thenReturn(MiraklItemTypes.SHOP); when(miraklItemLinkLocator2Mock.getSystem()).thenReturn(ItemLinkExternalSystem.MIRAKL); final Set<String> targetItemTypes = Set.of(HyperwalletItemTypes.BANK_ACCOUNT.toString(), HyperwalletItemTypes.PROGRAM.toString()); // formatter:off when(itemLinkRepositoryMock.findBySourceSystemAndSourceIdAndSourceTypeAndTargetSystemAndTargetTypeIn( eq("MIRAKL"), eq("H1"), eq("SHOP"), eq("HYPERWALLET"), argThat(x -> x.containsAll(targetItemTypes)))) .thenReturn(List.of(itemLinkEntity1Mock, itemLinkEntity2Mock)); when(itemLinkRepositoryMock.findBySourceSystemAndSourceIdAndSourceTypeAndTargetSystemAndTargetTypeIn( eq("MIRAKL"), eq("H2"), eq("SHOP"), eq("HYPERWALLET"), argThat(x -> x.containsAll(targetItemTypes)))) .thenReturn(List.of()); // formatter:on when(itemLinksModelEntityConverterMock.hyperwalletLocatorFromLinkTarget(itemLinkEntity1Mock)) .thenReturn(hyperwalletItemLinkLocator1Mock); when(itemLinksModelEntityConverterMock.hyperwalletLocatorFromLinkTarget(itemLinkEntity2Mock)) .thenReturn(hyperwalletItemLinkLocator2Mock); final Map<MiraklItemLinkLocator, Collection<HyperwalletItemLinkLocator>> result = testObj.findLinks( Set.of(miraklItemLinkLocator1Mock, miraklItemLinkLocator2Mock), Set.of(HyperwalletItemTypes.BANK_ACCOUNT, HyperwalletItemTypes.PROGRAM)); assertThat(result).containsKeys(miraklItemLinkLocator1Mock, miraklItemLinkLocator1Mock); assertThat(result.get(miraklItemLinkLocator1Mock)).containsExactlyInAnyOrder(hyperwalletItemLinkLocator1Mock, hyperwalletItemLinkLocator2Mock); assertThat(result.get(miraklItemLinkLocator2Mock)).isEmpty(); } }
5,445
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support/converter/MyStrategySingleExecutorTest.java
package com.paypal.infrastructure.support.converter; import com.paypal.infrastructure.support.strategy.SingleAbstractStrategyExecutor; import com.paypal.infrastructure.support.strategy.Strategy; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class MyStrategySingleExecutorTest { @Spy @InjectMocks private MyStrategySingleExecutor testObj; @Mock private Object sourceMock; @Mock private Strategy<Object, Object> strategyMock; @Test void execute_whenStrategyIsApplicable_shouldCallToStrategyConvertMethod() { when(strategyMock.isApplicable(sourceMock)).thenReturn(Boolean.TRUE); doReturn(Set.of(strategyMock)).when(testObj).getStrategies(); testObj.execute(sourceMock); verify(strategyMock).execute(sourceMock); } @Test void execute_whenStrategyIsNotApplicable_shouldNotCallToStrategyConvertMethod() { when(strategyMock.isApplicable(sourceMock)).thenReturn(Boolean.FALSE); doReturn(Set.of(strategyMock)).when(testObj).getStrategies(); testObj.execute(sourceMock); verify(strategyMock, never()).execute(sourceMock); } @Test void execute_whenNullSetIsReceived_shouldReturnNull() { doReturn(null).when(testObj).getStrategies(); final String result = testObj.execute(sourceMock); assertThat(result).isNull(); } @Test void execute_whenEmptySetOfStrategies_shouldReturnNull() { doReturn(Collections.emptySet()).when(testObj).getStrategies(); final String result = testObj.execute(sourceMock); assertThat(result).isNull(); } private static class MyStrategySingleExecutor extends SingleAbstractStrategyExecutor<Object, String> { @Override protected Set<Strategy<Object, String>> getStrategies() { return null; } } }
5,446
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support/date/TimeMachineTest.java
package com.paypal.infrastructure.support.date; import com.paypal.infrastructure.support.date.TimeMachine; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import java.time.LocalDateTime; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(MockitoExtension.class) class TimeMachineTest { @Test void now_shouldReturnLocalDateTimeBasedOnFixedTime() { final LocalDateTime fixedDate = LocalDateTime.of(2000, 11, 5, 12, 30, 22); TimeMachine.useFixedClockAt(fixedDate); final LocalDateTime result = TimeMachine.now(); assertThat(result).isEqualTo(fixedDate); } }
5,447
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support/exceptions/HMCErrorResponseTest.java
package com.paypal.infrastructure.support.exceptions; import com.paypal.infrastructure.support.exceptions.HMCErrorResponse; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class HMCErrorResponseTest { private static final String ERROR_MESSAGE = "Error message"; private static final String MESSAGE_ATTRIBUTE = "errorMessage"; @Test void constructor_ShouldPopulateFromAndToDate_WhenCalled() { final HMCErrorResponse result = new HMCErrorResponse(ERROR_MESSAGE); assertThat(result).hasFieldOrPropertyWithValue(MESSAGE_ATTRIBUTE, ERROR_MESSAGE); } @Test void getFrom_ShouldReturnFromValue_WhenCalled() { final HMCErrorResponse result = new HMCErrorResponse(ERROR_MESSAGE); assertThat(result.getErrorMessage()).isEqualTo(ERROR_MESSAGE); } }
5,448
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support/exceptions/HMCHyperwalletAPIExceptionTest.java
package com.paypal.infrastructure.support.exceptions; import com.hyperwallet.clientsdk.HyperwalletException; import com.paypal.infrastructure.support.exceptions.HMCHyperwalletAPIException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static com.paypal.infrastructure.support.exceptions.HMCHyperwalletAPIException.DEFAULT_MSG; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(MockitoExtension.class) class HMCHyperwalletAPIExceptionTest { private static final String HMC_HYPERWALLET_EXCEPTION_MESSAGE = "HMC Mirakl exception message"; private static final String HYPERWALLET_EXCEPTION_FIELD = "hyperwalletException"; private static final String DETAIL_MESSAGE_FIELD = "detailMessage"; @Mock private HyperwalletException hyperwalletExceptionMock; @Test void hMCHyperwalletAPIException_ShouldPopulateMessageAndException() { final HMCHyperwalletAPIException hmcHyperwalletAPIException = new HMCHyperwalletAPIException( HMC_HYPERWALLET_EXCEPTION_MESSAGE, hyperwalletExceptionMock); assertThat(hmcHyperwalletAPIException) .hasFieldOrPropertyWithValue(HYPERWALLET_EXCEPTION_FIELD, hyperwalletExceptionMock) .hasFieldOrPropertyWithValue(DETAIL_MESSAGE_FIELD, HMC_HYPERWALLET_EXCEPTION_MESSAGE); } @Test void hMCHyperwalletAPIException_ShouldPopulateDefaultMessageAndException() { final HMCHyperwalletAPIException hmcHyperwalletAPIException = new HMCHyperwalletAPIException( hyperwalletExceptionMock); assertThat(hmcHyperwalletAPIException) .hasFieldOrPropertyWithValue(HYPERWALLET_EXCEPTION_FIELD, hyperwalletExceptionMock) .hasFieldOrPropertyWithValue(DETAIL_MESSAGE_FIELD, DEFAULT_MSG); } @Test void hMCHyperwalletAPIException_ShouldReturnException() { final HMCHyperwalletAPIException hmcHyperwalletAPIException = new HMCHyperwalletAPIException( hyperwalletExceptionMock); assertThat(hmcHyperwalletAPIException.getHyperwalletException()).isEqualTo(hyperwalletExceptionMock); } }
5,449
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support/exceptions/DateIntervalExceptionTest.java
package com.paypal.infrastructure.support.exceptions; import com.paypal.infrastructure.support.exceptions.DateIntervalException; import org.junit.jupiter.api.Test; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import static org.assertj.core.api.Assertions.assertThat; class DateIntervalExceptionTest { private static final String FROM_ATTRIBUTE = "from"; private static final String TO_ATTRIBUTE = "to"; private static final Date FROM_DATE = new GregorianCalendar(2014, Calendar.FEBRUARY, 11).getTime(); private static final Date TO_DATE = new GregorianCalendar(2015, Calendar.FEBRUARY, 11).getTime(); private static final String DATE_INTERVAL_FORMATTED_MESSAGE = "[From] date [2015-02-11T00:00:00] can not be later than [To] date [2014-02-11T00:00:00]"; @Test void constructor_ShouldPopulateFromAndToDate_WhenCalled() { final DateIntervalException result = new DateIntervalException(FROM_DATE, TO_DATE); assertThat(result).hasFieldOrPropertyWithValue(FROM_ATTRIBUTE, FROM_DATE) .hasFieldOrPropertyWithValue(TO_ATTRIBUTE, TO_DATE); } @Test void getMessage_ShouldReturnADateIntervalErrorMessage() { final DateIntervalException result = new DateIntervalException(TO_DATE, FROM_DATE); assertThat(result.getMessage()).isEqualTo(DATE_INTERVAL_FORMATTED_MESSAGE); } }
5,450
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support/exceptions/HMCMiraklAPIExceptionTest.java
package com.paypal.infrastructure.support.exceptions; import com.mirakl.client.core.exception.MiraklException; import com.paypal.infrastructure.support.exceptions.HMCMiraklAPIException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static com.paypal.infrastructure.support.exceptions.HMCMiraklAPIException.DEFAULT_MSG; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(MockitoExtension.class) class HMCMiraklAPIExceptionTest { private static final String HMC_MIRAKL_EXCEPTION_MESSAGE = "HMC Mirakl exception message"; private static final String MIRAKL_EXCEPTION_FIELD = "miraklException"; private static final String DETAIL_MESSAGE_FIELD = "detailMessage"; @Mock private MiraklException miraklExceptionMock; @Test void hMCMiraklAPIException_ShouldPopulateMessageAndException() { final HMCMiraklAPIException hmcMiraklAPIException = new HMCMiraklAPIException(HMC_MIRAKL_EXCEPTION_MESSAGE, miraklExceptionMock); assertThat(hmcMiraklAPIException).hasFieldOrPropertyWithValue(MIRAKL_EXCEPTION_FIELD, miraklExceptionMock) .hasFieldOrPropertyWithValue(DETAIL_MESSAGE_FIELD, HMC_MIRAKL_EXCEPTION_MESSAGE); } @Test void hMCMiraklAPIException_ShouldPopulateDefaultMessageAndException() { final HMCMiraklAPIException hmcMiraklAPIException = new HMCMiraklAPIException(miraklExceptionMock); assertThat(hmcMiraklAPIException).hasFieldOrPropertyWithValue(MIRAKL_EXCEPTION_FIELD, miraklExceptionMock) .hasFieldOrPropertyWithValue(DETAIL_MESSAGE_FIELD, DEFAULT_MSG); } @Test void hMCMiraklAPIException_ShouldReturnException() { final HMCMiraklAPIException hmcMiraklAPIException = new HMCMiraklAPIException(miraklExceptionMock); assertThat(hmcMiraklAPIException.getMiraklException()).isEqualTo(miraklExceptionMock); } }
5,451
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support/exceptions/HMCExceptionHandlerTest.java
package com.paypal.infrastructure.support.exceptions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpStatus; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class HMCExceptionHandlerTest { private static final String EXCEPTION_MESSAGE = "Exception message"; public static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0]; @InjectMocks private HMCExceptionHandler testObj; @Mock private MissingServletRequestParameterException missingServletRequestParameterExceptionMock; @Mock private MethodArgumentTypeMismatchException methodArgumentTypeMismatchExceptionMock; @Mock private HMCException hmcExceptionMock; @Test void handleHMCException_ShouldReturnABadRequestAndTheExceptionErrorMessage() { when(hmcExceptionMock.getMessage()).thenReturn(EXCEPTION_MESSAGE); // The following expectation shouldn't be necessary, since Throwable.getSuppressed // should return an empty array if no exceptions were suppressed, but tests are // failing because Throwable.getSuppressed is returning null. when(hmcExceptionMock.getSuppressed()).thenReturn(EMPTY_THROWABLE_ARRAY); final HMCErrorResponse result = testObj.handleHMCException(hmcExceptionMock); assertThat(result.getErrorMessage()).isEqualTo(EXCEPTION_MESSAGE); } @Test void handleMethodArgumentTypeMismatchException_ShouldReturnABadRequestAndABadRequestErrorMessage() { when(methodArgumentTypeMismatchExceptionMock.getSuppressed()).thenReturn(EMPTY_THROWABLE_ARRAY); final HMCErrorResponse result = testObj .handleMethodArgumentTypeMismatchException(methodArgumentTypeMismatchExceptionMock); assertThat(result.getErrorMessage()).isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()); } @Test void handleMissingParametersException_ShouldReturnABadRequestAndABadRequestErrorMessage() { when(missingServletRequestParameterExceptionMock.getSuppressed()).thenReturn(EMPTY_THROWABLE_ARRAY); final HMCErrorResponse result = testObj .handleMissingRequestParametersException(missingServletRequestParameterExceptionMock); assertThat(result.getErrorMessage()).isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()); } }
5,452
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support/countries/CountriesUtilTest.java
package com.paypal.infrastructure.support.countries; import com.paypal.infrastructure.support.countries.CountriesUtil; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.Locale; import java.util.Optional; import java.util.stream.Stream; class CountriesUtilTest { /** * When isocode is null Then is returned an empty. */ @Test void whenIsocodeIsNull_ThenIsReturnedAnEmptyOptional() { final String isocode = null; final Optional<Locale> result = CountriesUtil.getLocaleByIsocode(isocode); Assertions.assertTrue(result.isEmpty()); } /** * When isocode not exists Then is returned an empty. */ @Test void whenIsocodeNotExists_ThenIsReturnedAnEmptyOptional() { final String isocode = "not_exist"; final Optional<Locale> result = CountriesUtil.getLocaleByIsocode(isocode); Assertions.assertTrue(result.isEmpty()); } /** * When uppercase isocode with two characters exists Then is returned the correct * locale */ @Test void whenIsocodeExists_ThenIsReturnedHisLocale() { final String isocode = "GB"; final Locale expected = new Locale("", isocode); final Optional<Locale> result = CountriesUtil.getLocaleByIsocode(isocode); Assertions.assertEquals(expected, result.get()); } @ParameterizedTest @MethodSource void getLocaleByIsocode_shouldIgnoreCase(final String isocode, final Locale expectedLocale) { final Optional<Locale> result = CountriesUtil.getLocaleByIsocode(isocode); Assertions.assertEquals(expectedLocale, result.get()); } private static Stream<Arguments> getLocaleByIsocode_shouldIgnoreCase() { //@formatter:off final Locale expectedLocale = new Locale("", "GB"); return Stream.of( Arguments.of("Gbr", expectedLocale), Arguments.of("gbr", expectedLocale), Arguments.of("GBR", expectedLocale) ); //@formatter:on } }
5,453
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support/logging/HyperwalletLoggingErrorsUtilTest.java
package com.paypal.infrastructure.support.logging; import cc.protea.util.http.Response; import com.hyperwallet.clientsdk.HyperwalletException; import com.hyperwallet.clientsdk.model.HyperwalletError; import com.hyperwallet.clientsdk.model.HyperwalletErrorList; import com.paypal.infrastructure.support.logging.HyperwalletLoggingErrorsUtil; import org.junit.jupiter.api.Test; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; class HyperwalletLoggingErrorsUtilTest { @Test void stringify_shouldPrintAllExceptionFields_forHyperwalletExceptionTypeA() { final HyperwalletException hyperwalletException = buildHyperwalletExceptionTypeA(); final String result = HyperwalletLoggingErrorsUtil.stringify(hyperwalletException); //@formatter:off assertThat(result).isEqualTo(""" { "errorCode" : "400", "errorMessage" : "HYPERWALLET_MESSAGE", "exceptionMessage" : "HYPERWALLET_MESSAGE", "responseStatusCode" : "200", "responseMessage" : "RESPONSE_MESSAGE", "responseBody" : "{field1:\\"value1\\"}" }"""); //@formatter:om } @Test void stringify_shouldPrintAllExceptionFields_forHyperwalletExceptionTypeB() { final HyperwalletException hyperwalletException = buildHyperwalletExceptionTypeB(); final String result = HyperwalletLoggingErrorsUtil.stringify(hyperwalletException); //@formatter:off assertThat(result).isEqualTo(""" { "errorCode" : "CODE-0", "errorMessage" : "MESSAGE-0", "exceptionMessage" : "MESSAGE-0", "responseStatusCode" : "200", "responseMessage" : "RESPONSE_MESSAGE", "responseBody" : "RESPONSE_BODY", "errorDetailList" : [ { "code" : "CODE-0", "fieldName" : "FIELD-0", "message" : "MESSAGE-0", "relatedResources" : [ "RELATED_RESOURCE-0-1", "RELATED_RESOURCE-101" ] }, { "code" : "CODE-1", "fieldName" : "FIELD-1", "message" : "MESSAGE-1", "relatedResources" : [ "RELATED_RESOURCE-1-1", "RELATED_RESOURCE-111" ] } ] }"""); //@formatter:om } @Test void stringify_shouldPrintAllExceptionFields_forHyperwalletExceptionTypeC() { final HyperwalletException hyperwalletException = buildHyperwalletExceptionTypeC(); final String result = HyperwalletLoggingErrorsUtil.stringify(hyperwalletException); //@formatter:off assertThat(result).isEqualTo(""" { "exceptionMessage" : "java.lang.RuntimeException: EXCEPTION_MESSAGE" }"""); //@formatter:on } private HyperwalletException buildHyperwalletExceptionTypeA() { final Response response = new Response(); response.setResponseCode(200); response.setResponseMessage("RESPONSE_MESSAGE"); response.setBody("{field1:\"value1\"}"); return new HyperwalletException(response, 400, "HYPERWALLET_MESSAGE"); } private HyperwalletException buildHyperwalletExceptionTypeB() { final Response response = new Response(); response.setResponseCode(200); response.setResponseMessage("RESPONSE_MESSAGE"); response.setBody("RESPONSE_BODY"); return new HyperwalletException(response, buildHyperwalletErrorList(2)); } private HyperwalletException buildHyperwalletExceptionTypeC() { final RuntimeException e = new RuntimeException("EXCEPTION_MESSAGE"); return new HyperwalletException(e); } private HyperwalletErrorList buildHyperwalletErrorList(final int num) { final HyperwalletErrorList hyperwalletErrorList = new HyperwalletErrorList(); //@formatter:off hyperwalletErrorList.setErrors( IntStream.range(0, num) .mapToObj(this::buildHyperwalletError) .collect(Collectors.toList())); //@formatter:on return hyperwalletErrorList; } private HyperwalletError buildHyperwalletError(final int i) { //@formatter:off return new HyperwalletError("CODE-" + i, "FIELD-" + i, "MESSAGE-" + i, List.of("RELATED_RESOURCE-" + i + - 1, "RELATED_RESOURCE-1" + i + 1)); //@formatter:on } }
5,454
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support/logging/MiraklLoggingErrorsUtilTest.java
package com.paypal.infrastructure.support.logging; import com.mirakl.client.core.exception.MiraklException; import com.paypal.infrastructure.support.logging.MiraklLoggingErrorsUtil; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class MiraklLoggingErrorsUtilTest { private static final String EXCEPTION_MESSAGE = "ExceptionMessage"; @Mock private MiraklException miraklExceptionMock; @Test void stringify_shouldAddExceptionMessageAsJSON() { when(miraklExceptionMock.getMessage()).thenReturn(EXCEPTION_MESSAGE); final String result = MiraklLoggingErrorsUtil.stringify(miraklExceptionMock); assertThat(result).isEqualTo("{exceptionMessage=" + EXCEPTION_MESSAGE + ",}"); } }
5,455
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/support/strategy/MultipleAbstractStrategyExecutorTest.java
package com.paypal.infrastructure.support.strategy; import com.paypal.infrastructure.support.strategy.MultipleAbstractStrategyExecutor; import com.paypal.infrastructure.support.strategy.Strategy; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import java.util.List; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class MultipleAbstractStrategyExecutorTest { @Spy @InjectMocks private MyMultipleAbstractStrategyExecutor testObj; @Mock private Object sourceMock; @Mock private Strategy<Object, Object> strategyOneMock, strategyTwoMock; @Test void execute_whenStrategyIsApplicable_shouldCallToStrategyConvertMethod() { when(strategyOneMock.isApplicable(sourceMock)).thenReturn(Boolean.TRUE); doReturn(Set.of(strategyOneMock)).when(testObj).getStrategies(); testObj.execute(sourceMock); verify(strategyOneMock).execute(sourceMock); } @Test void execute_whenNullSetIsReceived_shouldReturnEmptyList() { doReturn(null).when(testObj).getStrategies(); final List<String> result = testObj.execute(sourceMock); assertThat(result).isEmpty(); } @Test void execute_whenEmptySetOfStrategies_shouldReturnEmptyList() { doReturn(Collections.emptySet()).when(testObj).getStrategies(); final List<String> result = testObj.execute(sourceMock); assertThat(result).isEmpty(); } @Test void execute_whenSomeStrategiesAreApplicable_shouldExecuteTwoStrategies() { when(strategyOneMock.isApplicable(sourceMock)).thenReturn(true); when(strategyTwoMock.isApplicable(sourceMock)).thenReturn(true); doReturn(Set.of(strategyOneMock, strategyTwoMock)).when(testObj).getStrategies(); testObj.execute(sourceMock); verify(strategyOneMock).execute(sourceMock); verify(strategyTwoMock).execute(sourceMock); } @Test void execute_whenNoStrategiesAreApplicable_shouldNotExecuteStrategies() { when(strategyOneMock.isApplicable(sourceMock)).thenReturn(false); when(strategyTwoMock.isApplicable(sourceMock)).thenReturn(false); doReturn(Set.of(strategyOneMock, strategyTwoMock)).when(testObj).getStrategies(); testObj.execute(sourceMock); verify(strategyOneMock, never()).execute(sourceMock); verify(strategyTwoMock, never()).execute(sourceMock); } private static class MyMultipleAbstractStrategyExecutor extends MultipleAbstractStrategyExecutor<Object, String> { @Override protected Set<Strategy<Object, String>> getStrategies() { return null; } } }
5,456
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/hyperwallet
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/hyperwallet/configuration/HyperwalletProgramsConfigurationTest.java
package com.paypal.infrastructure.hyperwallet.configuration; import com.paypal.infrastructure.support.exceptions.InvalidConfigurationException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.test.util.ReflectionTestUtils; import java.util.List; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; //@formatter:off class HyperwalletProgramsConfigurationTest { private HyperwalletProgramsConfiguration testObj; @BeforeEach void setUp() { testObj = new HyperwalletProgramsConfiguration(); } @Test void getProgramConfiguration_shouldReturnConfiguration_whenSingleProgramIsConfigured() { setConfigurationVariables(List.of("DEFAULT"), List.of(), List.of("USER_PROGRAM_TOKEN_1"), List.of("PAYMENT_PROGRAM_TOKEN_1"), List.of("BANK_ACCOUNT_TOKEN_1")); final HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration result = testObj.getProgramConfiguration("DEFAULT"); assertThat(result.getUsersProgramToken()).isEqualTo("USER_PROGRAM_TOKEN_1"); assertThat(result.getPaymentProgramToken()).isEqualTo("PAYMENT_PROGRAM_TOKEN_1"); assertThat(result.getBankAccountToken()).isEqualTo("BANK_ACCOUNT_TOKEN_1"); } @Test void getProgramConfiguration_shouldReturnConfiguration_whenMultipleProgramIsConfigured() { configureMultipleProgramSetup(); final HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration result1 = testObj.getProgramConfiguration("UK"); assertThat(result1.getUsersProgramToken()).isEqualTo("USER_PROGRAM_TOKEN_1"); assertThat(result1.getPaymentProgramToken()).isEqualTo("PAYMENT_PROGRAM_TOKEN_1"); assertThat(result1.getBankAccountToken()).isEqualTo("BANK_ACCOUNT_TOKEN_1"); final HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration result2 = testObj.getProgramConfiguration("EUROPE"); assertThat(result2.getUsersProgramToken()).isEqualTo("USER_PROGRAM_TOKEN_2"); assertThat(result2.getPaymentProgramToken()).isEqualTo("PAYMENT_PROGRAM_TOKEN_2"); assertThat(result2.getBankAccountToken()).isEqualTo("BANK_ACCOUNT_TOKEN_2"); } @Test void getProgramConfiguration_shouldReturnConfiguration_whenMultipleProgramIsConfigured_andOneIsIgnored() { setConfigurationVariables(List.of("UK", "IGNORED", "EUROPE"), List.of("IGNORED"), List.of("USER_PROGRAM_TOKEN_1", "", "USER_PROGRAM_TOKEN_2"), List.of("PAYMENT_PROGRAM_TOKEN_1", "", "PAYMENT_PROGRAM_TOKEN_2"), List.of("BANK_ACCOUNT_TOKEN_1", "", "BANK_ACCOUNT_TOKEN_2")); final HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration result1 = testObj.getProgramConfiguration("UK"); assertThat(result1.getUsersProgramToken()).isEqualTo("USER_PROGRAM_TOKEN_1"); assertThat(result1.getPaymentProgramToken()).isEqualTo("PAYMENT_PROGRAM_TOKEN_1"); assertThat(result1.getBankAccountToken()).isEqualTo("BANK_ACCOUNT_TOKEN_1"); assertThat(result1.isIgnored()).isFalse(); final HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration result2 = testObj.getProgramConfiguration("EUROPE"); assertThat(result2.getUsersProgramToken()).isEqualTo("USER_PROGRAM_TOKEN_2"); assertThat(result2.getPaymentProgramToken()).isEqualTo("PAYMENT_PROGRAM_TOKEN_2"); assertThat(result2.getBankAccountToken()).isEqualTo("BANK_ACCOUNT_TOKEN_2"); assertThat(result2.isIgnored()).isFalse(); final HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration result3 = testObj.getProgramConfiguration("IGNORED"); assertThat(result3.isIgnored()).isTrue(); final List<String> result4 = testObj.getIgnoredHyperwalletPrograms(); assertThat(result4).containsExactly("IGNORED"); } @Test void getProgramConfigurations_shouldReturnAllConfigurations() { configureMultipleProgramSetup(); final List<HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration> result = testObj.getAllProgramConfigurations(); assertThat(result).hasSize(2); assertThat(result.stream().map(it -> it.getProgramName()).collect(Collectors.toList())).contains("UK", "EUROPE"); } @Test void getRootProgram_shouldReturnRootProgram_whenSet() { ReflectionTestUtils.setField(testObj, "hyperwalletRootProgramToken", "ROOT"); configureMultipleProgramSetup(); final String result = testObj.getRootProgramToken(); assertThat(result).isEqualTo("ROOT"); } @Test void getRootProgram_shouldReturnDefaultProgram_whenNotSet() { ReflectionTestUtils.setField(testObj, "hyperwalletRootProgramToken", ""); configureMultipleProgramSetup(); final String result = testObj.getRootProgramToken(); assertThat(result).isEqualTo("USER_PROGRAM_TOKEN_1"); } @Test void setIgnoredHyperwalletPrograms_shouldUpdateIgnoredPrograms_andRebuildMap() { configureMultipleProgramSetup(); testObj.setIgnoredHyperwalletPrograms(List.of("EUROPE")); assertThat(testObj.getProgramConfiguration("UK").isIgnored()).isFalse(); assertThat(testObj.getProgramConfiguration("EUROPE").isIgnored()).isTrue(); } @Test void buildProgramTokensMap_throwsInvalidConfigurationException_whenNotAllTokensAreProvided() { setConfigurationVariablesWithoutInitializeConfiguration(List.of("UK", "EUROPE"), List.of(), List.of("USER_PROGRAM_TOKEN_2"), List.of("PAYMENT_PROGRAM_TOKEN_1", "PAYMENT_PROGRAM_TOKEN_2"), List.of("BANK_ACCOUNT_TOKEN_1", "BANK_ACCOUNT_TOKEN_2")); assertThatExceptionOfType(InvalidConfigurationException.class).isThrownBy( () -> ReflectionTestUtils.invokeMethod(testObj, "initializeConfiguration")); } void setConfigurationVariables(final List<String> hyperwalletPrograms, final List<String> ignoredHyperwalletPrograms, final List<String> hyperwalletUserProgramTokens, final List<String> hyperwalletPaymentProgramTokens, final List<String> hyperwalletBankAccountTokens) { setConfigurationVariablesWithoutInitializeConfiguration(hyperwalletPrograms, ignoredHyperwalletPrograms, hyperwalletUserProgramTokens, hyperwalletPaymentProgramTokens, hyperwalletBankAccountTokens); ReflectionTestUtils.invokeMethod(testObj, "initializeConfiguration"); } private void setConfigurationVariablesWithoutInitializeConfiguration(final List<String> hyperwalletPrograms, final List<String> ignoredHyperwalletPrograms, final List<String> hyperwalletUserProgramTokens, final List<String> hyperwalletPaymentProgramTokens, final List<String> hyperwalletBankAccountTokens) { ReflectionTestUtils.setField(testObj, "hyperwalletProgramsNames", hyperwalletPrograms); ReflectionTestUtils.setField(testObj, "ignoredHyperwalletPrograms", ignoredHyperwalletPrograms); ReflectionTestUtils.setField(testObj, "hyperwalletUserProgramTokens", hyperwalletUserProgramTokens); ReflectionTestUtils.setField(testObj, "hyperwalletPaymentProgramTokens", hyperwalletPaymentProgramTokens); ReflectionTestUtils.setField(testObj, "hyperwalletBankAccountTokens", hyperwalletBankAccountTokens); } void configureMultipleProgramSetup() { setConfigurationVariables(List.of("UK", "EUROPE"), List.of(), List.of("USER_PROGRAM_TOKEN_1", "USER_PROGRAM_TOKEN_2"), List.of("PAYMENT_PROGRAM_TOKEN_1", "PAYMENT_PROGRAM_TOKEN_2"), List.of("BANK_ACCOUNT_TOKEN_1", "BANK_ACCOUNT_TOKEN_2")); } }
5,457
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/hyperwallet
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/hyperwallet/services/HyperwalletPaginationSupportTest.java
package com.paypal.infrastructure.hyperwallet.services; import com.fasterxml.jackson.core.type.TypeReference; import com.hyperwallet.clientsdk.Hyperwallet; import com.hyperwallet.clientsdk.model.HyperwalletLink; import com.hyperwallet.clientsdk.model.HyperwalletList; import com.hyperwallet.clientsdk.util.HyperwalletApiClient; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Supplier; import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class HyperwalletPaginationSupportTest { public static final int NUM_ITEMS = 10; public static final int PAGE_SIZE = 3; @InjectMocks @Spy private MyHyperwalletPaginationSupport testObj; @Mock private HyperwalletApiClient hyperwalletApiClientMock; @Mock private Supplier<HyperwalletList<Object>> paginatedFunctionMock; @Test void get_shouldReturnAllDataInEveryPage_whenThereAreMultiplePages() { // given when(paginatedFunctionMock.get()).thenReturn(hyperwalletList(NUM_ITEMS, PAGE_SIZE, 1)); doReturn(hyperwalletApiClientMock).when(testObj).getApiClient(); doReturn(hyperwalletList(NUM_ITEMS, PAGE_SIZE, 2)).when(hyperwalletApiClientMock).get( argThat(x -> x.contains("page=2")), ArgumentMatchers.<TypeReference<HyperwalletList<Object>>>any()); doReturn(hyperwalletList(NUM_ITEMS, PAGE_SIZE, 3)).when(hyperwalletApiClientMock).get( argThat(x -> x.contains("page=3")), ArgumentMatchers.<TypeReference<HyperwalletList<Object>>>any()); doReturn(hyperwalletList(NUM_ITEMS, PAGE_SIZE, 4)).when(hyperwalletApiClientMock).get( argThat(x -> x.contains("page=4")), ArgumentMatchers.<TypeReference<HyperwalletList<Object>>>any()); // when final List<Object> result = testObj.get(paginatedFunctionMock); // then assertThat(result).hasSize(NUM_ITEMS); } @Test void get_shouldReturnAllData_whenThereAreOneFullPage() { // given when(paginatedFunctionMock.get()).thenReturn(hyperwalletList(PAGE_SIZE, PAGE_SIZE, 1)); // when final List<Object> result = testObj.get(paginatedFunctionMock); // then assertThat(result).hasSize(PAGE_SIZE); } @Test void get_shouldReturnEmptyList_whenThereIsNoData() { // given when(paginatedFunctionMock.get()).thenReturn(hyperwalletList(0, PAGE_SIZE, 1)); // when final List<Object> result = testObj.get(paginatedFunctionMock); // then assertThat(result).isEmpty(); } HyperwalletList<Object> hyperwalletList(final int numItems, final int pageSize, final int numPage) { final int itemsInCurrentPage = numItems - pageSize * numPage >= 0 ? pageSize : numItems % pageSize; final boolean hasNextPage = numItems - pageSize * numPage > 0; final boolean hasPreviousPage = numPage == 0; final HyperwalletList<Object> hyperwalletList = new HyperwalletList<>(); hyperwalletList.setLimit(PAGE_SIZE); hyperwalletList.setData(IntStream.range(0, itemsInCurrentPage).mapToObj(i -> mock(Object.class)).toList()); hyperwalletList.setHasNextPage(hasNextPage); hyperwalletList.setHasPreviousPage(hasPreviousPage); final List<HyperwalletLink> links = new ArrayList<>(); if (hasNextPage) { final HyperwalletLink nextLink = new HyperwalletLink(); nextLink.setHref("http://localhost:8080/test?page=" + (numPage + 1)); nextLink.setParams(Map.of("rel", "next")); links.add(nextLink); } if (hasPreviousPage) { final HyperwalletLink previousLink = new HyperwalletLink(); previousLink.setHref("http://localhost:8080/test?page=" + (numPage - 1)); previousLink.setParams(Map.of("rel", "previous")); links.add(previousLink); } hyperwalletList.setLinks(links); return hyperwalletList; } private static class MyHyperwalletPaginationSupport extends HyperwalletPaginationSupport { public MyHyperwalletPaginationSupport(final Hyperwallet hyperwallet) { super(hyperwallet); } @Override protected HyperwalletApiClient getApiClient() { return super.getApiClient(); } } }
5,458
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/hyperwallet
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/hyperwallet/services/AbstractHyperwalletSDKServiceTest.java
package com.paypal.infrastructure.hyperwallet.services; import com.hyperwallet.clientsdk.Hyperwallet; import com.hyperwallet.clientsdk.util.HyperwalletEncryption; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletConnectionConfiguration; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletProgramsConfiguration; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.InjectMocks; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class AbstractHyperwalletSDKServiceTest { @InjectMocks private MyHyperwalletSDKService testObj; private static final String SERVER = "server"; private static final String PASSWORD = "password"; private static final String USER_NAME = "userName"; private static final String PROGRAM_TOKEN = "programToken"; private static final String HYPERWALLET_PROGRAM = "hyperwalletProgram"; @Mock private HyperwalletConnectionConfiguration hyperwalletConnectionConfigurationMock; @Mock private HyperwalletProgramsConfiguration hyperwalletProgramsConfigurationMock; @Mock private HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration hyperwalletProgramConfigurationMock; @Test void getHyperwalletInstance_shouldReturnAnHyperwalletInstance() { when(hyperwalletProgramsConfigurationMock.getProgramConfiguration(HYPERWALLET_PROGRAM)) .thenReturn(hyperwalletProgramConfigurationMock); when(hyperwalletProgramConfigurationMock.getUsersProgramToken()).thenReturn(PROGRAM_TOKEN); when(hyperwalletConnectionConfigurationMock.getUsername()).thenReturn(USER_NAME); when(hyperwalletConnectionConfigurationMock.getPassword()).thenReturn(PASSWORD); when(hyperwalletConnectionConfigurationMock.getServer()).thenReturn(SERVER); final Hyperwallet result = testObj.getHyperwalletInstanceByHyperwalletProgram(HYPERWALLET_PROGRAM); assertThat(result).hasFieldOrPropertyWithValue("programToken", PROGRAM_TOKEN) .hasFieldOrPropertyWithValue("apiClient.username", USER_NAME) .hasFieldOrPropertyWithValue("url", SERVER + "/rest/v4"); } @Test void getHyperwalletInstance_shouldReturnAnHyperwalletInstanceWithNOTEncryptedOption() { when(hyperwalletConnectionConfigurationMock.getUsername()).thenReturn(USER_NAME); when(hyperwalletConnectionConfigurationMock.getPassword()).thenReturn(PASSWORD); when(hyperwalletConnectionConfigurationMock.getServer()).thenReturn(SERVER); final Hyperwallet result = testObj.getHyperwalletInstanceByProgramToken(PROGRAM_TOKEN); assertThat(result).hasFieldOrPropertyWithValue("apiClient.hyperwalletEncryption", null); } @Test void getHyperwalletInstanceWithProgramToken_shouldReturnAnHyperwalletInstance() { when(hyperwalletConnectionConfigurationMock.getUsername()).thenReturn(USER_NAME); when(hyperwalletConnectionConfigurationMock.getPassword()).thenReturn(PASSWORD); when(hyperwalletConnectionConfigurationMock.getServer()).thenReturn(SERVER); final Hyperwallet result = testObj.getHyperwalletInstanceByProgramToken(PROGRAM_TOKEN); assertThat(result).hasFieldOrPropertyWithValue("programToken", PROGRAM_TOKEN) .hasFieldOrPropertyWithValue("apiClient.username", USER_NAME) .hasFieldOrPropertyWithValue("url", SERVER + "/rest/v4"); } @Test void getHyperwalletInstance_shouldReturnAnHyperwalletInstanceWithoutSettingToken() { when(hyperwalletConnectionConfigurationMock.getUsername()).thenReturn(USER_NAME); when(hyperwalletConnectionConfigurationMock.getPassword()).thenReturn(PASSWORD); when(hyperwalletConnectionConfigurationMock.getServer()).thenReturn(SERVER); final Hyperwallet result = testObj.getHyperwalletInstance(); assertThat(result).hasFieldOrPropertyWithValue("programToken", null) .hasFieldOrPropertyWithValue("apiClient.username", USER_NAME) .hasFieldOrPropertyWithValue("url", SERVER + "/rest/v4"); } static class MyHyperwalletSDKService extends AbstractHyperwalletSDKService { protected MyHyperwalletSDKService(final HyperwalletProgramsConfiguration programsConfiguration, final HyperwalletConnectionConfiguration connectionConfiguration, final HyperwalletEncryption encryption) { super(programsConfiguration, connectionConfiguration, encryption); } @Override protected String getProgramToken( final HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration programConfiguration) { return programConfiguration.getUsersProgramToken(); } } }
5,459
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/hyperwallet
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/hyperwallet/services/UserHyperwalletSDKServiceImplTest.java
package com.paypal.infrastructure.hyperwallet.services; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletProgramsConfiguration; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class UserHyperwalletSDKServiceImplTest { public static final String PROGRAM_TOKEN = "TOKEN"; @InjectMocks private UserHyperwalletSDKServiceImpl testObj; @Mock private HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration hyperwalletProgramConfigurationMock; @Test void getProgramToken_shouldReturnUserProgramToken() { when(hyperwalletProgramConfigurationMock.getUsersProgramToken()).thenReturn(PROGRAM_TOKEN); final String result = testObj.getProgramToken(hyperwalletProgramConfigurationMock); assertThat(result).isEqualTo(PROGRAM_TOKEN); } }
5,460
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/hyperwallet
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/hyperwallet/services/AbstractEncryptedHyperwalletSDKServiceTest.java
package com.paypal.infrastructure.hyperwallet.services; import com.hyperwallet.clientsdk.Hyperwallet; import com.hyperwallet.clientsdk.util.HyperwalletEncryption; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletConnectionConfiguration; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletProgramsConfiguration; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class AbstractEncryptedHyperwalletSDKServiceTest { @InjectMocks private MyHyperwalletSDKService testObj; private static final String SERVER = "server"; private static final String PASSWORD = "password"; private static final String USER_NAME = "userName"; private static final String PROGRAM_TOKEN = "programToken"; @Mock private HyperwalletEncryption hyperwalletEncryptionMock; @Mock private HyperwalletConnectionConfiguration hyperwalletConnectionConfigurationMock; @Test void getHyperwalletInstance_shouldReturnAnHyperwalletInstanceWithEncryptedOption() { when(hyperwalletConnectionConfigurationMock.getUsername()).thenReturn(USER_NAME); when(hyperwalletConnectionConfigurationMock.getPassword()).thenReturn(PASSWORD); when(hyperwalletConnectionConfigurationMock.getServer()).thenReturn(SERVER); final Hyperwallet result = testObj.getHyperwalletInstanceByProgramToken(PROGRAM_TOKEN); assertThat(result).hasFieldOrPropertyWithValue("apiClient.hyperwalletEncryption", hyperwalletEncryptionMock); } static class MyHyperwalletSDKService extends AbstractHyperwalletSDKService { protected MyHyperwalletSDKService(final HyperwalletProgramsConfiguration programsConfiguration, final HyperwalletConnectionConfiguration connectionConfiguration, final HyperwalletEncryption encryption) { super(programsConfiguration, connectionConfiguration, encryption); } @Override protected String getProgramToken( final HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration programConfiguration) { return programConfiguration.getUsersProgramToken(); } } }
5,461
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/hyperwallet
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/hyperwallet/services/PaymentHyperwalletSDKServiceImplTest.java
package com.paypal.infrastructure.hyperwallet.services; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletProgramsConfiguration; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class PaymentHyperwalletSDKServiceImplTest { public static final String PROGRAM_TOKEN = "TOKEN"; @InjectMocks private PaymentHyperwalletSDKServiceImpl testObj; @Mock private HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration hyperwalletProgramConfigurationMock; @Test void getProgramToken_shouldReturnPaymentProgramToken() { when(hyperwalletProgramConfigurationMock.getPaymentProgramToken()).thenReturn(PROGRAM_TOKEN); final String result = testObj.getProgramToken(hyperwalletProgramConfigurationMock); assertThat(result).isEqualTo(PROGRAM_TOKEN); } }
5,462
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl/settings/MiraklClientSettingsExecutorTest.java
package com.paypal.infrastructure.mirakl.settings; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; class MiraklClientSettingsExecutorTest { private MiraklClientSettings miraklClientSettings; private Runnable executorTestRunnable; @Test void runWithSettings_shouldSetTheSettingsToRunnableAndFinallyClearThem_afterBeingExecutedWithStagedChanges() { // given miraklClientSettings = new MiraklClientSettings(true); executorTestRunnable = () -> { final MiraklClientSettings miraklClientSettingsIntoRunnable = MiraklClientSettingsHolder .getMiraklClientSettings(); assertThat(miraklClientSettingsIntoRunnable).isEqualTo(miraklClientSettings); }; // when MiraklClientSettingsExecutor.runWithSettings(miraklClientSettings, executorTestRunnable); // then assertThat(MiraklClientSettingsHolder.getMiraklClientSettings()) .isEqualTo(MiraklClientSettingsHolder.DEFAULT_SETTINGS); } @Test void runWithSettings_shouldClearTheSettings_IfAnExceptionIsTriggered() { // given miraklClientSettings = new MiraklClientSettings(true); executorTestRunnable = () -> { throw new IllegalArgumentException("This is an Exception."); }; // when assertThatThrownBy( () -> MiraklClientSettingsExecutor.runWithSettings(miraklClientSettings, executorTestRunnable)) .isInstanceOf(IllegalArgumentException.class); // then assertThat(MiraklClientSettingsHolder.getMiraklClientSettings()) .isEqualTo(MiraklClientSettingsHolder.DEFAULT_SETTINGS); } }
5,463
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl/settings/MiraklClientSettingsHolderTest.java
package com.paypal.infrastructure.mirakl.settings; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class MiraklClientSettingsHolderTest { private MiraklClientSettings miraklClientSettings; @BeforeEach void setUp() { miraklClientSettings = new MiraklClientSettings(true); } @AfterEach void tearDown() { MiraklClientSettingsHolder.clear(); } @Test void setMiraklClientSettings_shouldUpdateTheSettings_whenExecuted() { MiraklClientSettingsHolder.setMiraklClientSettings(miraklClientSettings); assertThat(MiraklClientSettingsHolder.getMiraklClientSettings()).isEqualTo(miraklClientSettings); } @Test void getMiraklClientSettings_shouldReturnTheSettings_whenExecuted() { assertThat(MiraklClientSettingsHolder.getMiraklClientSettings()) .isEqualTo(MiraklClientSettingsHolder.DEFAULT_SETTINGS); } @Test void clear_shouldClearSettings_whenExecuted() { MiraklClientSettingsHolder.setMiraklClientSettings(miraklClientSettings); MiraklClientSettingsHolder.clear(); assertThat(MiraklClientSettingsHolder.getMiraklClientSettings()) .isEqualTo(MiraklClientSettingsHolder.DEFAULT_SETTINGS); } }
5,464
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl/support/MiraklShopUtilsTest.java
package com.paypal.infrastructure.mirakl.support; import com.mirakl.client.mmp.domain.shop.MiraklShop; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.InjectMocks; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; class MiraklShopUtilsTest { private static final String PROGRAM = "program"; private static final String PROGRAM_2 = "program-2"; private static final String BANKACCOUNT_TOKEN = "bankAccountToken"; private static final String BANKACCOUNT_TOKEN_2 = "bankAccountToken-2"; @Test void shouldGetAndSet_programAndBankAccountToken() { // given final MiraklShop miraklShop = new MiraklShop(); // when MiraklShopUtils.setProgram(miraklShop, PROGRAM); MiraklShopUtils.setBankAccountToken(miraklShop, BANKACCOUNT_TOKEN); final Optional<String> program = MiraklShopUtils.getProgram(miraklShop); final Optional<String> bankAccountToken = MiraklShopUtils.getBankAccountToken(miraklShop); // then assertThat(program).contains(PROGRAM); assertThat(bankAccountToken).contains(BANKACCOUNT_TOKEN); } @Test void shouldOverride_programAndBankAccountToken() { // given final MiraklShop miraklShop = new MiraklShop(); // when MiraklShopUtils.setProgram(miraklShop, PROGRAM); MiraklShopUtils.setBankAccountToken(miraklShop, BANKACCOUNT_TOKEN); MiraklShopUtils.setProgram(miraklShop, PROGRAM_2); MiraklShopUtils.setBankAccountToken(miraklShop, BANKACCOUNT_TOKEN_2); final Optional<String> program = MiraklShopUtils.getProgram(miraklShop); final Optional<String> bankAccountToken = MiraklShopUtils.getBankAccountToken(miraklShop); // then assertThat(program).contains(PROGRAM_2); assertThat(bankAccountToken).contains(BANKACCOUNT_TOKEN_2); } @Test void shouldDealWithNulls_programAndBankAccountToken() { // given final MiraklShop miraklShop = new MiraklShop(); // when MiraklShopUtils.setProgram(miraklShop, null); MiraklShopUtils.setBankAccountToken(miraklShop, null); MiraklShopUtils.setProgram(miraklShop, PROGRAM_2); MiraklShopUtils.setBankAccountToken(miraklShop, BANKACCOUNT_TOKEN_2); final Optional<String> program = MiraklShopUtils.getProgram(miraklShop); final Optional<String> bankAccountToken = MiraklShopUtils.getBankAccountToken(miraklShop); // then assertThat(program).contains(PROGRAM_2); assertThat(bankAccountToken).contains(BANKACCOUNT_TOKEN_2); } }
5,465
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl/controllers/ChangeIgnoredProgramsControllerTest.java
package com.paypal.infrastructure.mirakl.controllers; import com.paypal.infrastructure.mirakl.controllers.dto.IgnoredProgramsDTO; import com.paypal.infrastructure.mirakl.services.IgnoreProgramsService; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.InjectMocks; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class ChangeIgnoredProgramsControllerTest { @InjectMocks private ChangeIgnoredProgramsController testObj; @Mock private IgnoreProgramsService ignoreProgramsServiceMock; @Mock private IgnoredProgramsDTO ignoredProgramsDTO; @Test void ignore_shouldReplacedIgnoredProgramList_andReturnOk() { when(ignoredProgramsDTO.getIgnoredPrograms()).thenReturn(List.of("A", "B")); final ResponseEntity<String> result = testObj.ignore(ignoredProgramsDTO); verify(ignoreProgramsServiceMock).ignorePrograms(List.of("A", "B")); assertEquals(HttpStatus.OK, result.getStatusCode()); } @Test void get_shouldReturnIgnoredPrograms() { when(ignoreProgramsServiceMock.getIgnoredPrograms()).thenReturn(List.of("A", "B")); final ResponseEntity<Object> result = testObj.get(); assertEquals(HttpStatus.OK, result.getStatusCode()); assertEquals(List.of("A", "B"), result.getBody()); } }
5,466
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl/client/StageChangesMiraklClientTest.java
package com.paypal.infrastructure.mirakl.client; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdateShop; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdateShops; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdatedShops; import com.mirakl.client.mmp.operator.request.shop.MiraklUpdateShopsRequest; import com.paypal.infrastructure.changestaging.model.Change; import com.paypal.infrastructure.changestaging.service.ChangeStagingService; import com.paypal.infrastructure.mirakl.client.converters.MiraklStageChangeConverter; import com.paypal.infrastructure.mirakl.client.filter.IgnoredShopsFilter; import com.paypal.infrastructure.mirakl.configuration.MiraklApiClientConfig; import com.paypal.infrastructure.mirakl.settings.MiraklClientSettings; import com.paypal.infrastructure.mirakl.settings.MiraklClientSettingsExecutor; import com.paypal.infrastructure.mirakl.settings.MiraklClientSettingsHolder; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.InjectMocks; import org.springframework.test.util.ReflectionTestUtils; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class StageChangesMiraklClientTest { private StageChangesMiraklClient testObj; @Mock private ChangeStagingService changeStagingServiceMock; @Mock private MiraklStageChangeConverter miraklStageChangeConverterMock; @BeforeEach void setUp() { final MiraklApiClientConfig config = new MiraklApiClientConfig(); config.setOperatorApiKey("OPERATOR-KEY"); config.setEnvironment("environment"); testObj = Mockito.spy(new StageChangesMiraklClient(config, mock(IgnoredShopsFilter.class), changeStagingServiceMock, miraklStageChangeConverterMock)); } @AfterEach void tearDown() { MiraklClientSettingsHolder.clear(); } @Test void updateShops_shouldStageChanges_whenStagingIsEnabled() { // given final MiraklUpdateShopsRequest miraklUpdateShopsRequest = mock(MiraklUpdateShopsRequest.class); final List<MiraklUpdateShop> miraklUpdateShops = List.of(mock(MiraklUpdateShop.class)); final List<Change> changes = List.of(mock(Change.class)); when(miraklUpdateShopsRequest.getShops()).thenReturn(miraklUpdateShops); when(miraklStageChangeConverterMock.from(miraklUpdateShops)).thenReturn(changes); MiraklClientSettingsHolder.setMiraklClientSettings(new MiraklClientSettings(true)); // when final MiraklUpdatedShops result = testObj.updateShops(miraklUpdateShopsRequest); // then assertThat(result.getShopReturns()).isEmpty(); verify(changeStagingServiceMock).stageChanges(changes); verify(testObj, never()).callSuperGetMiraklUpdatedShops(miraklUpdateShopsRequest); } @Test void updateShops_shouldDelegateOnMiraklSDK_whenStagingIsDisabled() { // given final MiraklUpdateShopsRequest miraklUpdateShopsRequest = mock(MiraklUpdateShopsRequest.class); MiraklClientSettingsHolder.setMiraklClientSettings(new MiraklClientSettings(false)); final MiraklUpdatedShops miraklUpdatedShops = mock(MiraklUpdatedShops.class); doReturn(miraklUpdatedShops).when(testObj).callSuperGetMiraklUpdatedShops(miraklUpdateShopsRequest); // when final MiraklUpdatedShops result = testObj.updateShops(miraklUpdateShopsRequest); // then assertThat(result).isEqualTo(miraklUpdatedShops); verify(changeStagingServiceMock, never()).stageChanges(any()); verify(testObj).callSuperGetMiraklUpdatedShops(miraklUpdateShopsRequest); } }
5,467
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl/client/DirectMiraklClientTest.java
package com.paypal.infrastructure.mirakl.client; import com.mirakl.client.mmp.domain.additionalfield.MiraklFrontOperatorAdditionalField; import com.mirakl.client.mmp.domain.common.FileWrapper; import com.mirakl.client.mmp.domain.invoice.MiraklInvoices; import com.mirakl.client.mmp.domain.payment.MiraklTransactionLogs; import com.mirakl.client.mmp.domain.shop.MiraklShops; import com.mirakl.client.mmp.domain.shop.document.MiraklShopDocument; import com.mirakl.client.mmp.domain.version.MiraklVersion; import com.mirakl.client.mmp.operator.core.MiraklMarketplacePlatformOperatorApiClient; import com.mirakl.client.mmp.operator.domain.documents.MiraklDocumentsConfigurations; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdatedShops; import com.mirakl.client.mmp.operator.request.additionalfield.MiraklGetAdditionalFieldRequest; import com.mirakl.client.mmp.operator.request.documents.MiraklGetDocumentsConfigurationRequest; import com.mirakl.client.mmp.operator.request.payment.invoice.MiraklGetInvoicesRequest; import com.mirakl.client.mmp.operator.request.shop.MiraklUpdateShopsRequest; import com.mirakl.client.mmp.request.payment.MiraklGetTransactionLogsRequest; import com.mirakl.client.mmp.request.shop.MiraklGetShopsRequest; import com.mirakl.client.mmp.request.shop.document.MiraklDeleteShopDocumentRequest; import com.mirakl.client.mmp.request.shop.document.MiraklDownloadShopsDocumentsRequest; import com.mirakl.client.mmp.request.shop.document.MiraklGetShopDocumentsRequest; import com.paypal.infrastructure.mirakl.client.filter.IgnoredShopsFilter; import com.paypal.infrastructure.mirakl.configuration.MiraklApiClientConfig; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class DirectMiraklClientTest { private DirectMiraklClient testObj; @Mock private MiraklMarketplacePlatformOperatorApiClient miraklMarketplacePlatformOperatorApiClientMock; @Mock private IgnoredShopsFilter ignoredShopsFilterMock; @BeforeEach void setUp() { final MiraklApiClientConfig config = new MiraklApiClientConfig(); config.setOperatorApiKey("OPERATOR-KEY"); config.setEnvironment("environment"); testObj = Mockito.spy(new DirectMiraklClient(config, ignoredShopsFilterMock)); ReflectionTestUtils.setField(testObj, "miraklMarketplacePlatformOperatorApiClient", miraklMarketplacePlatformOperatorApiClientMock); } @Test void getVersion_shouldDelegateOnMiraklSdkClient() { // given final MiraklVersion miraklVersion = mock(MiraklVersion.class); when(miraklMarketplacePlatformOperatorApiClientMock.getVersion()).thenReturn(miraklVersion); // when final MiraklVersion result = testObj.getVersion(); // then assertThat(result).isEqualTo(miraklVersion); verify(miraklMarketplacePlatformOperatorApiClientMock).getVersion(); } @Test void getShops_shouldCallSdkClient_andFilterShops() { // given final MiraklShops unfilteredMiraklShops = mock(MiraklShops.class); final MiraklShops filteredMiraklShops = mock(MiraklShops.class); when(ignoredShopsFilterMock.filterIgnoredShops(unfilteredMiraklShops)).thenReturn(filteredMiraklShops); final MiraklGetShopsRequest miraklGetShopsRequest = mock(MiraklGetShopsRequest.class); when(miraklMarketplacePlatformOperatorApiClientMock.getShops(miraklGetShopsRequest)) .thenReturn(unfilteredMiraklShops); // when final MiraklShops result = testObj.getShops(miraklGetShopsRequest); // then assertThat(result).isEqualTo(filteredMiraklShops); verify(miraklMarketplacePlatformOperatorApiClientMock).getShops(miraklGetShopsRequest); } @Test void updateShops_shouldDelegateOnMiraklSdkClient() { // given final MiraklUpdateShopsRequest miraklUpdateShopsRequest = mock(MiraklUpdateShopsRequest.class); final MiraklUpdatedShops miraklUpdatedShops = mock(MiraklUpdatedShops.class); when(miraklMarketplacePlatformOperatorApiClientMock.updateShops(miraklUpdateShopsRequest)) .thenReturn(miraklUpdatedShops); // when final MiraklUpdatedShops result = testObj.updateShops(miraklUpdateShopsRequest); // then assertThat(result).isEqualTo(miraklUpdatedShops); verify(miraklMarketplacePlatformOperatorApiClientMock).updateShops(miraklUpdateShopsRequest); } @Test void getAdditionalFields_shouldDelegateOnMiraklSdkClient() { // given final MiraklGetAdditionalFieldRequest miraklGetAdditionalFieldRequest = mock( MiraklGetAdditionalFieldRequest.class); final List<MiraklFrontOperatorAdditionalField> additionalFields = List .of(mock(MiraklFrontOperatorAdditionalField.class)); when(miraklMarketplacePlatformOperatorApiClientMock.getAdditionalFields(miraklGetAdditionalFieldRequest)) .thenReturn(additionalFields); // when final List<MiraklFrontOperatorAdditionalField> result = testObj .getAdditionalFields(miraklGetAdditionalFieldRequest); // then assertThat(result).isEqualTo(additionalFields); verify(miraklMarketplacePlatformOperatorApiClientMock).getAdditionalFields(miraklGetAdditionalFieldRequest); } @Test void getInvoices_shouldDelegateOnMiraklSdkClient() { // given final MiraklGetInvoicesRequest miraklGetInvoicesRequest = mock(MiraklGetInvoicesRequest.class); final MiraklInvoices miraklInvoices = mock(MiraklInvoices.class); when(miraklMarketplacePlatformOperatorApiClientMock.getInvoices(miraklGetInvoicesRequest)) .thenReturn(miraklInvoices); // when final MiraklInvoices result = testObj.getInvoices(miraklGetInvoicesRequest); // then assertThat(result).isEqualTo(miraklInvoices); verify(miraklMarketplacePlatformOperatorApiClientMock).getInvoices(miraklGetInvoicesRequest); } @SuppressWarnings("java:S1874") @Test void getTransactionLogs_shouldDelegateOnMiraklSdkClient() { // given final MiraklGetTransactionLogsRequest miraklGetTransactionLogsRequest = mock( MiraklGetTransactionLogsRequest.class); final MiraklTransactionLogs miraklTransactionLogs = mock(MiraklTransactionLogs.class); when(miraklMarketplacePlatformOperatorApiClientMock.getTransactionLogs(miraklGetTransactionLogsRequest)) .thenReturn(miraklTransactionLogs); // when final MiraklTransactionLogs result = testObj.getTransactionLogs(miraklGetTransactionLogsRequest); // then assertThat(result).isEqualTo(miraklTransactionLogs); verify(miraklMarketplacePlatformOperatorApiClientMock).getTransactionLogs(miraklGetTransactionLogsRequest); } @Test void getDocumentsConfiguration_shouldDelegateOnMiraklSdkClient() { // given final MiraklGetDocumentsConfigurationRequest miraklGetDocumentsConfigurationRequest = mock( MiraklGetDocumentsConfigurationRequest.class); final MiraklDocumentsConfigurations miraklDocumentsConfiguration = mock(MiraklDocumentsConfigurations.class); when(miraklMarketplacePlatformOperatorApiClientMock .getDocumentsConfiguration(miraklGetDocumentsConfigurationRequest)) .thenReturn(miraklDocumentsConfiguration); // when final MiraklDocumentsConfigurations result = testObj .getDocumentsConfiguration(miraklGetDocumentsConfigurationRequest); // then assertThat(result).isEqualTo(miraklDocumentsConfiguration); verify(miraklMarketplacePlatformOperatorApiClientMock) .getDocumentsConfiguration(miraklGetDocumentsConfigurationRequest); } @Test void getShopDocuments_shouldDelegateOnMiraklSdkClient() { // given final MiraklGetShopDocumentsRequest miraklGetShopDocumentsRequest = mock(MiraklGetShopDocumentsRequest.class); final List<MiraklShopDocument> miraklShopDocuments = List.of(mock(MiraklShopDocument.class)); when(miraklMarketplacePlatformOperatorApiClientMock.getShopDocuments(miraklGetShopDocumentsRequest)) .thenReturn(miraklShopDocuments); // when final List<MiraklShopDocument> result = testObj.getShopDocuments(miraklGetShopDocumentsRequest); // then assertThat(result).isEqualTo(miraklShopDocuments); verify(miraklMarketplacePlatformOperatorApiClientMock).getShopDocuments(miraklGetShopDocumentsRequest); } @Test void downloadShopDocumentes_shouldDelegateOnMiraklSdkClient() { // given final MiraklDownloadShopsDocumentsRequest miraklDownloadShopsDocumentsRequest = mock( MiraklDownloadShopsDocumentsRequest.class); final FileWrapper fileWrapper = mock(FileWrapper.class); when(miraklMarketplacePlatformOperatorApiClientMock.downloadShopsDocuments(miraklDownloadShopsDocumentsRequest)) .thenReturn(fileWrapper); // when final FileWrapper result = testObj.downloadShopsDocuments(miraklDownloadShopsDocumentsRequest); // then assertThat(result).isEqualTo(fileWrapper); verify(miraklMarketplacePlatformOperatorApiClientMock) .downloadShopsDocuments(miraklDownloadShopsDocumentsRequest); } @Test void deleteShopDocument_shouldDelegateOnMiraklSdkClient() { // given final MiraklDeleteShopDocumentRequest miraklDeleteShopDocumentRequest = mock( MiraklDeleteShopDocumentRequest.class); // when testObj.deleteShopDocument(miraklDeleteShopDocumentRequest); // then verify(miraklMarketplacePlatformOperatorApiClientMock).deleteShopDocument(miraklDeleteShopDocumentRequest); } }
5,468
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl/client
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl/client/changestaging/MiraklUpdateShopStagedChangesExecutorTest.java
package com.paypal.infrastructure.mirakl.client.changestaging; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdateShop; import com.mirakl.client.mmp.operator.request.shop.MiraklUpdateShopsRequest; import com.paypal.infrastructure.changestaging.model.ChangeOperation; import com.paypal.infrastructure.changestaging.model.ChangeTarget; import com.paypal.infrastructure.changestaging.model.StagedChange; import com.paypal.infrastructure.changestaging.service.operations.StagedChangesExecutorInfo; import com.paypal.infrastructure.mirakl.client.MiraklClient; import com.paypal.testsupport.TestDateUtil; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.function.Consumer; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) class MiraklUpdateShopStagedChangesExecutorTest { @InjectMocks private MiraklUpdateShopStagedChangesExecutor testObj; @Mock private MiraklClient miraklClientMock; @Captor private ArgumentCaptor<MiraklUpdateShopsRequest> argumentCaptor; @Test void execute_shouldUpdateTheShops_whenExecutedWithAListOfChanges_compactingChangesFromShop() { // given //@formatter:off final List<StagedChange> stagedChanges = new ArrayList<>(List.of( stagedChange(1, 1, x -> {}), stagedChange(2, 2, x -> {}), stagedChange(3, 1, x -> {}), stagedChange(2, 3, x -> {}) )); //@formatter:on // when testObj.execute(stagedChanges); // then verify(miraklClientMock).updateShops(argumentCaptor.capture()); final MiraklUpdateShopsRequest miraklUpdateShopsRequestCaptured = argumentCaptor.getValue(); final List<MiraklUpdateShop> compactedShops = miraklUpdateShopsRequestCaptured.getShops(); assertThat(compactedShops).hasSize(3); assertThat(compactedShops.get(0).getShopId()).isEqualTo(1L); assertThat(compactedShops.get(1).getShopId()).isEqualTo(2L); assertThat(compactedShops.get(2).getShopId()).isEqualTo(3L); } @Test void execute_shouldCompactAndAggregateFieldsFromDifferentChangesOfTheSameShop() { // given //@formatter:off final List<StagedChange> stagedChanges = new ArrayList<>(List.of( stagedChange(1, 1, x -> x.setDescription("Description")), stagedChange(1, 2, x -> x.setName("Name")) )); //@formatter:on // when testObj.execute(stagedChanges); // then verify(miraklClientMock).updateShops(argumentCaptor.capture()); final MiraklUpdateShopsRequest miraklUpdateShopsRequestCaptured = argumentCaptor.getValue(); final List<MiraklUpdateShop> compactedShops = miraklUpdateShopsRequestCaptured.getShops(); assertThat(compactedShops).hasSize(1); assertThat(compactedShops.get(0).getShopId()).isEqualTo(1L); assertThat(compactedShops.get(0).getDescription()).isEqualTo("Description"); assertThat(compactedShops.get(0).getName()).isEqualTo("Name"); } @Test void execute_shouldCompactAndHandlePatchesOfBooleanValues() { // given //@formatter:off final List<StagedChange> stagedChanges = new ArrayList<>(List.of( stagedChange(1, 1, x -> x.setProfessional(false)), stagedChange(2, 1, x -> x.setProfessional(true)), stagedChange(3, 1, x -> {}) )); //@formatter:on // when testObj.execute(stagedChanges); // then verify(miraklClientMock).updateShops(argumentCaptor.capture()); final MiraklUpdateShopsRequest miraklUpdateShopsRequestCaptured = argumentCaptor.getValue(); final List<MiraklUpdateShop> compactedShops = miraklUpdateShopsRequestCaptured.getShops(); assertThat(compactedShops.get(0).isProfessional()).isFalse(); assertThat(compactedShops.get(1).isProfessional()).isTrue(); assertThat(ReflectionTestUtils.getField(compactedShops.get(2), "professional")).isNull(); } @Test void execute_shouldCompactAndKeepTheValueOfLaterDateWhenBothStoresHaveAPropertyFilled_whenExecuted() { // given //@formatter:off final List<StagedChange> stagedChanges = new ArrayList<>(List.of( stagedChange(1, 2, x -> x.setDescription("Old description")), stagedChange(1, 1, x -> x.setDescription("New description")) )); //@formatter:on // when testObj.execute(stagedChanges); // then verify(miraklClientMock).updateShops(argumentCaptor.capture()); final MiraklUpdateShopsRequest miraklUpdateShopsRequestCaptured = argumentCaptor.getValue(); final List<MiraklUpdateShop> compactedShops = miraklUpdateShopsRequestCaptured.getShops(); final MiraklUpdateShop firstMiraklUpdateShop = compactedShops.get(0); assertThat(firstMiraklUpdateShop.getDescription()).isEqualTo("New description"); } @Test void getExecutorInfo_shouldCreateAndReturnStagedChangesExecutorInfo_whenExecuted() { // when final StagedChangesExecutorInfo stagedChangesExecutorInfo = testObj.getExecutorInfo(); // then assertThat(stagedChangesExecutorInfo).isNotNull(); assertThat(stagedChangesExecutorInfo.getOperation()).isEqualTo(ChangeOperation.UPDATE); assertThat(stagedChangesExecutorInfo.getTarget()).isEqualTo(ChangeTarget.MIRAKL); assertThat(stagedChangesExecutorInfo.getType()).isEqualTo(MiraklUpdateShop.class); } private StagedChange stagedChange(final long shopId, final long daysOffset, final Consumer<MiraklUpdateShop> updatePayload) { final StagedChange stagedChange1 = new StagedChange(); stagedChange1.setType(MiraklUpdateShop.class); stagedChange1.setId("%s-%s".formatted(shopId, UUID.randomUUID().toString())); stagedChange1.setTarget(ChangeTarget.MIRAKL); stagedChange1.setOperation(ChangeOperation.UPDATE); stagedChange1.setCreationDate(TestDateUtil.currentDateMinusDays(daysOffset)); final MiraklUpdateShop payload = new MiraklUpdateShop(); payload.setShopId(shopId); stagedChange1.setPayload(payload); updatePayload.accept(payload); return stagedChange1; } }
5,469
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl/client
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl/client/converters/MiraklStageChangeConverterTest.java
package com.paypal.infrastructure.mirakl.client.converters; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdateShop; import com.paypal.infrastructure.changestaging.model.Change; import com.paypal.infrastructure.changestaging.model.ChangeOperation; import com.paypal.infrastructure.changestaging.model.ChangeTarget; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mapstruct.factory.Mappers; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import java.util.List; import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(MockitoExtension.class) class MiraklStageChangeConverterTest { @Spy private final MiraklStageChangeConverter testObj = Mappers.getMapper(MiraklStageChangeConverter.class); @Test void from_shouldCreateChangeFromMiraklUpdateShop() { // given final MiraklUpdateShop sourceUpdateShop = generateTestMiraklUpdateShop(1L); // when final Change targetChange = testObj.from(sourceUpdateShop); // then assertIndividualChange(sourceUpdateShop, targetChange); } @Test void multipleFrom_shouldCreateAllChangesFromMiraklUpdateShops() { // given final List<MiraklUpdateShop> sourceUpdateShopList = List.of(generateTestMiraklUpdateShop(1L), generateTestMiraklUpdateShop(2L), generateTestMiraklUpdateShop(3L)); // when final List<Change> targetChanges = testObj.from(sourceUpdateShopList); // then IntStream.range(0, sourceUpdateShopList.size()) .forEach(index -> assertIndividualChange(sourceUpdateShopList.get(index), targetChanges.get(index))); } private static void assertIndividualChange(final MiraklUpdateShop sourceUpdateShop, final Change targetChange) { assertThat(targetChange.getType()).isEqualTo(MiraklUpdateShop.class); assertThat(targetChange.getPayload()).isEqualTo(sourceUpdateShop); assertThat(targetChange.getOperation()).isEqualTo(ChangeOperation.UPDATE); assertThat(targetChange.getTarget()).isEqualTo(ChangeTarget.MIRAKL); } @NotNull private static MiraklUpdateShop generateTestMiraklUpdateShop(final long shopId) { final MiraklUpdateShop sourceUpdateShop = new MiraklUpdateShop(); sourceUpdateShop.setShopId(shopId); sourceUpdateShop.setName("testShop"); return sourceUpdateShop; } }
5,470
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl/client
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl/client/filter/IgnoredShopsFilterTest.java
package com.paypal.infrastructure.mirakl.client.filter; import com.mirakl.client.mmp.domain.common.MiraklAdditionalFieldValue; import com.mirakl.client.mmp.domain.shop.MiraklShop; import com.mirakl.client.mmp.domain.shop.MiraklShops; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletProgramsConfiguration; import com.paypal.infrastructure.mirakl.configuration.MiraklApiClientConfig; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.InjectMocks; import java.util.List; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.*; import static org.mockito.Mockito.lenient; @ExtendWith(MockitoExtension.class) class IgnoredShopsFilterTest { @InjectMocks private IgnoredShopsFilter testObj; @Mock private HyperwalletProgramsConfiguration hyperwalletProgramsConfigurationMock; @Mock private MiraklShops miraklShopsMock; @Mock private MiraklShop miraklShop1Mock, miraklShop2Mock, miraklShop3Mock; @BeforeEach void setUp() { final MiraklApiClientConfig config = new MiraklApiClientConfig(); config.setOperatorApiKey("OPERATOR-KEY"); config.setEnvironment("environment"); } @Test void getShops_shouldFilterShopsBelongingToIgnoredPrograms() { when(miraklShopsMock.getShops()).thenReturn(List.of(miraklShop1Mock, miraklShop2Mock, miraklShop3Mock)); mockShop(miraklShop1Mock, 1); mockShop(miraklShop2Mock, 2); mockShop(miraklShop3Mock, 3); mockIgnoreProgram(1, false); mockIgnoreProgram(2, true); mockIgnoreProgram(3, false); final MiraklShops result = testObj.filterIgnoredShops(miraklShopsMock); verify(result, times(1)).setShops(argThat(x -> x.size() == 2)); verify(result, times(1)).setShops(argThat(x -> x.containsAll(List.of(miraklShop1Mock, miraklShop3Mock)))); } private void mockShop(final MiraklShop miraklShopMock, final int id) { final MiraklAdditionalFieldValue.MiraklValueListAdditionalFieldValue miraklAdditionalFieldValueMock = Mockito .mock(MiraklAdditionalFieldValue.MiraklValueListAdditionalFieldValue.class); lenient().when(miraklShopMock.getId()).thenReturn(String.valueOf(id)); when(miraklShopMock.getAdditionalFieldValues()).thenReturn(List.of(miraklAdditionalFieldValueMock)); when(miraklAdditionalFieldValueMock.getCode()).thenReturn("hw-program"); when(miraklAdditionalFieldValueMock.getValue()).thenReturn("PROGRAM-" + id); } private void mockIgnoreProgram(final int id, final boolean ignored) { final HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration programConfiguration = Mockito .mock(HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration.class); lenient().when(hyperwalletProgramsConfigurationMock.getProgramConfiguration("PROGRAM-" + id)) .thenReturn(programConfiguration); lenient().when(programConfiguration.isIgnored()).thenReturn(ignored); } }
5,471
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/test/java/com/paypal/infrastructure/mirakl/services/IgnoreProgramsServiceImplTest.java
package com.paypal.infrastructure.mirakl.services; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletProgramsConfiguration; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class IgnoreProgramsServiceImplTest { @InjectMocks private IgnoreProgramsServiceImpl testObj; @Mock private HyperwalletProgramsConfiguration hyperwalletProgramsConfiguration; @Test void ignorePrograms_shouldCallHyperwalletApiConfigMockWithPassedPrograms() { final List<String> programsToIgnore = List.of("PROGRAM_1", "PROGRAM_2"); testObj.ignorePrograms(programsToIgnore); verify(hyperwalletProgramsConfiguration).setIgnoredHyperwalletPrograms(programsToIgnore); } @Test void ignorePrograms_shouldNotFailWhenListIsEmpty() { final List<String> programsToIgnore = List.of(); testObj.ignorePrograms(programsToIgnore); verify(hyperwalletProgramsConfiguration).setIgnoredHyperwalletPrograms(programsToIgnore); } @Test void ignorePrograms_shouldPassAnEmtpyListWhenListIsNull() { final List<String> programsToIgnore = null; testObj.ignorePrograms(programsToIgnore); verify(hyperwalletProgramsConfiguration).setIgnoredHyperwalletPrograms(List.of()); } @Test void getIgnoredPrograms_shouldReturnTheListReturnedByUserHyperwalletConfig() { final List<String> programs = List.of("PROGRAM_1"); when(hyperwalletProgramsConfiguration.getIgnoredHyperwalletPrograms()).thenReturn(programs); final List<String> result = testObj.getIgnoredPrograms(); assertThat(result).isSameAs(programs); } @Test void isIgnored_shouldReturnTrue_whenIgnoredProgramsContainsProgram() { final List<String> programs = List.of("PROGRAM_1", "PROGRAM_2"); when(hyperwalletProgramsConfiguration.getIgnoredHyperwalletPrograms()).thenReturn(programs); final boolean result = testObj.isIgnored("PROGRAM_1"); assertThat(result).isTrue(); } @Test void isIgnored_shouldReturnFalse_whenIgnoredProgramsNotContainsProgram() { final List<String> programs = List.of("PROGRAM_2", "PROGRAM_3"); when(hyperwalletProgramsConfiguration.getIgnoredHyperwalletPrograms()).thenReturn(programs); final boolean result = testObj.isIgnored("PROGRAM_1"); assertThat(result).isFalse(); } @Test void isIgnored_shouldReturnFalse_whenIgnoredProgramsListIsEmpty() { final List<String> programs = List.of(); when(hyperwalletProgramsConfiguration.getIgnoredHyperwalletPrograms()).thenReturn(programs); final boolean result = testObj.isIgnored("PROGRAM_1"); assertThat(result).isFalse(); } @Test void isIgnored_shouldReturnFalse_whenIgnoredProgramsListIsNull() { when(hyperwalletProgramsConfiguration.getIgnoredHyperwalletPrograms()).thenReturn(null); final boolean result = testObj.isIgnored("PROGRAM_1"); assertThat(result).isFalse(); } }
5,472
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/integrationTest/java/com/paypal/infrastructure
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/integrationTest/java/com/paypal/infrastructure/changestaging/ChangeStagingManagementTest.java
package com.paypal.infrastructure.changestaging; import com.paypal.infrastructure.changestaging.model.ChangeOperation; import com.paypal.infrastructure.changestaging.model.ChangeTarget; import com.paypal.infrastructure.changestaging.repositories.StagedChangesRepository; import com.paypal.infrastructure.changestaging.repositories.entities.StagedChangeEntity; import com.paypal.infrastructure.changestaging.service.StagedChangesPoller; import com.paypal.testsupport.AbstractIntegrationTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.test.web.servlet.MockMvc; import java.util.Date; import java.util.List; import java.util.stream.IntStream; import static org.mockito.Mockito.verify; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @AutoConfigureMockMvc(addFilters = false) class ChangeStagingManagementTest extends AbstractIntegrationTest { @Autowired private MockMvc mockMvc; @Autowired private StagedChangesRepository stagedChangesRepository; @SpyBean private StagedChangesPoller stagedChangesPoller; @Test void shouldGetStagedChanges() throws Exception { stagedChangesRepository.saveAll(entities(10)); this.mockMvc.perform(get("/management/staged-changes/")).andDo(print()).andExpect(status().isOk()) .andExpect(jsonPath("$.page.totalElements").value(10)); } @Test void shouldProcessStagedChanges() throws Exception { stagedChangesRepository.saveAll(entities(10)); this.mockMvc.perform(post("/management/staged-changes/process")).andDo(print()).andExpect(status().isOk()); verify(stagedChangesPoller).performStagedChange(); } private List<StagedChangeEntity> entities(final int num) { return IntStream.rangeClosed(1, num).mapToObj(this::entity).toList(); } private StagedChangeEntity entity(final int idx) { final StagedChangeEntity stagedChangeEntity = new StagedChangeEntity(); stagedChangeEntity.setId(String.valueOf(idx)); stagedChangeEntity.setOperation(ChangeOperation.UPDATE); stagedChangeEntity.setType("type-" + idx); stagedChangeEntity.setTarget(ChangeTarget.MIRAKL); stagedChangeEntity.setPayload("payload-" + idx); stagedChangeEntity.setCreationDate(new Date()); return stagedChangeEntity; } }
5,473
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/integrationTest/java/com/paypal/infrastructure
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/integrationTest/java/com/paypal/infrastructure/itemlinks/ItemLinksITTest.java
package com.paypal.infrastructure.itemlinks; import com.paypal.infrastructure.itemlinks.model.HyperwalletItemLinkLocator; import com.paypal.infrastructure.itemlinks.model.HyperwalletItemTypes; import com.paypal.infrastructure.itemlinks.model.MiraklItemLinkLocator; import com.paypal.infrastructure.itemlinks.model.MiraklItemTypes; import com.paypal.infrastructure.itemlinks.services.ItemLinksService; import com.paypal.testsupport.AbstractIntegrationTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import java.util.Collection; import java.util.Map; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; @Transactional class ItemLinksITTest extends AbstractIntegrationTest { @Autowired private ItemLinksService itemLinksService; private final ItemLinksMother itemLinksMother = new ItemLinksMother(); @Test void shouldCreateAndRecoverLinks() { final MiraklItemLinkLocator miraklItemLinkLocator1 = itemLinksMother.aMiraklItemLinkLocator(1, MiraklItemTypes.SHOP); final MiraklItemLinkLocator miraklItemLinkLocator2 = itemLinksMother.aMiraklItemLinkLocator(2, MiraklItemTypes.SHOP); final MiraklItemLinkLocator miraklItemLinkLocator3 = itemLinksMother.aMiraklItemLinkLocator(3, MiraklItemTypes.SHOP); final HyperwalletItemLinkLocator hyperwalletItemLinkLocator1 = itemLinksMother.aHyperwalletItemLinkLocator(1, HyperwalletItemTypes.PROGRAM); final HyperwalletItemLinkLocator hyperwalletItemLinkLocator2 = itemLinksMother.aHyperwalletItemLinkLocator(1, HyperwalletItemTypes.BANK_ACCOUNT); final HyperwalletItemLinkLocator hyperwalletItemLinkLocator3 = itemLinksMother.aHyperwalletItemLinkLocator(2, HyperwalletItemTypes.PROGRAM); itemLinksService.createLinks(miraklItemLinkLocator1, Set.of(hyperwalletItemLinkLocator1, hyperwalletItemLinkLocator2)); itemLinksService.createLinks(miraklItemLinkLocator2, Set.of(hyperwalletItemLinkLocator3)); itemLinksService.createLinks(miraklItemLinkLocator3, Set.of()); final Map<MiraklItemLinkLocator, Collection<HyperwalletItemLinkLocator>> miraklItemLinkLocatorLinks = itemLinksService .findLinks(Set.of(miraklItemLinkLocator1, miraklItemLinkLocator2, miraklItemLinkLocator3), Set.of(HyperwalletItemTypes.BANK_ACCOUNT, HyperwalletItemTypes.PROGRAM)); assertThat(miraklItemLinkLocatorLinks.entrySet()).hasSize(3); assertThat(miraklItemLinkLocatorLinks.get(miraklItemLinkLocator1)) .containsExactlyInAnyOrder(hyperwalletItemLinkLocator1, hyperwalletItemLinkLocator2); assertThat(miraklItemLinkLocatorLinks.get(miraklItemLinkLocator2)) .containsExactlyInAnyOrder(hyperwalletItemLinkLocator3); assertThat(miraklItemLinkLocatorLinks.get(miraklItemLinkLocator3)).isEmpty(); } @Test void shouldFilterLinksAccordingToTypes() { final MiraklItemLinkLocator miraklItemLinkLocator1 = itemLinksMother.aMiraklItemLinkLocator(1, MiraklItemTypes.SHOP); final MiraklItemLinkLocator miraklItemLinkLocator2 = itemLinksMother.aMiraklItemLinkLocator(2, MiraklItemTypes.SHOP); final HyperwalletItemLinkLocator hyperwalletItemLinkLocator1 = itemLinksMother.aHyperwalletItemLinkLocator(1, HyperwalletItemTypes.PROGRAM); final HyperwalletItemLinkLocator hyperwalletItemLinkLocator2 = itemLinksMother.aHyperwalletItemLinkLocator(1, HyperwalletItemTypes.BUSINESS_STAKEHOLDER); final HyperwalletItemLinkLocator hyperwalletItemLinkLocator3 = itemLinksMother.aHyperwalletItemLinkLocator(2, HyperwalletItemTypes.PROGRAM); itemLinksService.createLinks(miraklItemLinkLocator1, Set.of(hyperwalletItemLinkLocator1, hyperwalletItemLinkLocator2)); itemLinksService.createLinks(miraklItemLinkLocator2, Set.of(hyperwalletItemLinkLocator3)); final Map<MiraklItemLinkLocator, Collection<HyperwalletItemLinkLocator>> miraklItemLinkLocatorLinks = itemLinksService .findLinks(Set.of(miraklItemLinkLocator1, miraklItemLinkLocator2), Set.of(HyperwalletItemTypes.BANK_ACCOUNT, HyperwalletItemTypes.PROGRAM)); assertThat(miraklItemLinkLocatorLinks.entrySet()).hasSize(2); assertThat(miraklItemLinkLocatorLinks.get(miraklItemLinkLocator1)) .containsExactlyInAnyOrder(hyperwalletItemLinkLocator1); assertThat(miraklItemLinkLocatorLinks.get(miraklItemLinkLocator2)) .containsExactlyInAnyOrder(hyperwalletItemLinkLocator3); } class ItemLinksMother { MiraklItemLinkLocator aMiraklItemLinkLocator(final int id, final MiraklItemTypes type) { return new MiraklItemLinkLocator("M-%s-%d".formatted(type.toString(), id), type); } HyperwalletItemLinkLocator aHyperwalletItemLinkLocator(final int id, final HyperwalletItemTypes type) { return new HyperwalletItemLinkLocator("H-%s-%d".formatted(type.toString(), id), type); } } }
5,474
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/encryption
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/encryption/controllers/JwkSetController.java
package com.paypal.infrastructure.encryption.controllers; import com.fasterxml.jackson.databind.ObjectMapper; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletEncryptionConfiguration; import lombok.extern.slf4j.Slf4j; import net.minidev.json.JSONObject; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.core.io.Resource; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import static com.paypal.infrastructure.hyperwallet.constants.HyperWalletConstants.JWKSET_ERROR_FILENAME; /** * Optional controller that allows to expose your public keys for encryption */ @Slf4j @ConditionalOnProperty("hmc.hyperwallet.encryption.encryptionEnabled") @RestController @RequestMapping("/jwkset") public class JwkSetController { private final HyperwalletEncryptionConfiguration hyperwalletEncryptionConfiguration; private final ObjectMapper mapper; @Value("classpath:" + JWKSET_ERROR_FILENAME) protected Resource errorResource; public JwkSetController(final HyperwalletEncryptionConfiguration hyperwalletEncryptionConfiguration, final ObjectMapper objectMapper) { this.hyperwalletEncryptionConfiguration = hyperwalletEncryptionConfiguration; this.mapper = objectMapper; } @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody JSONObject getPublicKeys() throws IOException { try { final InputStream publicKeysStream = getPublicKeysFromFile(); return this.mapper.readValue(publicKeysStream, JSONObject.class); } catch (final FileNotFoundException ex) { log.error( "File that contains public keys for encryption [{}] has an incorrect name or it's not defined: {}", this.hyperwalletEncryptionConfiguration.getHmcPublicKeyLocation(), ex.getMessage()); } return this.mapper.readValue(this.errorResource.getInputStream(), JSONObject.class); } protected InputStream getPublicKeysFromFile() throws FileNotFoundException { return new FileInputStream(this.hyperwalletEncryptionConfiguration.getHmcPublicKeyLocation()); } }
5,475
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/repositories/StagedChangesRepository.java
package com.paypal.infrastructure.changestaging.repositories; import com.paypal.infrastructure.changestaging.model.ChangeOperation; import com.paypal.infrastructure.changestaging.model.ChangeTarget; import com.paypal.infrastructure.changestaging.repositories.entities.StagedChangeEntity; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface StagedChangesRepository extends JpaRepository<StagedChangeEntity, String> { List<StagedChangeEntity> findByTypeAndOperationAndTargetOrderByCreationDateAsc(String type, ChangeOperation operation, ChangeTarget target, Pageable pageable); void deleteByIdIn(List<String> ids); }
5,476
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/repositories
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/repositories/entities/StagedChangeEntity.java
package com.paypal.infrastructure.changestaging.repositories.entities; import com.paypal.infrastructure.changestaging.model.ChangeOperation; import com.paypal.infrastructure.changestaging.model.ChangeTarget; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.validation.constraints.NotNull; import lombok.Data; import java.util.Date; @Data @Entity public class StagedChangeEntity { @Id private String id; @NotNull private String type; @NotNull private ChangeOperation operation; @NotNull private ChangeTarget target; @NotNull @Column(length = 32768) private String payload; @NotNull private Date creationDate; }
5,477
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/model/Change.java
package com.paypal.infrastructure.changestaging.model; import lombok.Data; @Data public class Change { private Class<?> type; private ChangeOperation operation; private ChangeTarget target; private Object payload; }
5,478
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/model/ChangeOperation.java
package com.paypal.infrastructure.changestaging.model; public enum ChangeOperation { UPDATE }
5,479
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/model/StagedChange.java
package com.paypal.infrastructure.changestaging.model; import lombok.Data; import java.util.Date; @Data public class StagedChange { private String id; private Class<?> type; private ChangeOperation operation; private ChangeTarget target; private Object payload; private Date creationDate; }
5,480
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/model/ChangeTarget.java
package com.paypal.infrastructure.changestaging.model; public enum ChangeTarget { MIRAKL }
5,481
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/service/ChangeStagingServiceImpl.java
package com.paypal.infrastructure.changestaging.service; import com.paypal.infrastructure.changestaging.model.Change; import com.paypal.infrastructure.changestaging.model.StagedChange; import com.paypal.infrastructure.changestaging.repositories.StagedChangesRepository; import com.paypal.infrastructure.changestaging.service.converters.StagedChangesEntityConverter; import com.paypal.infrastructure.changestaging.service.converters.StagedChangesModelConverter; import org.springframework.stereotype.Component; import java.util.List; @Component public class ChangeStagingServiceImpl implements ChangeStagingService { private final StagedChangesModelConverter stagedChangesModelConverter; private final StagedChangesEntityConverter stagedChangesEntityConverter; private final StagedChangesRepository stagedChangeRepository; public ChangeStagingServiceImpl(final StagedChangesModelConverter stagedChangesModelConverter, final StagedChangesEntityConverter stagedChangesEntityConverter, final StagedChangesRepository stagedChangeRepository) { this.stagedChangesModelConverter = stagedChangesModelConverter; this.stagedChangesEntityConverter = stagedChangesEntityConverter; this.stagedChangeRepository = stagedChangeRepository; } @Override public StagedChange stageChange(final Change change) { final StagedChange stagedChange = stagedChangesModelConverter.from(change); stagedChangeRepository.save(stagedChangesEntityConverter.from(stagedChange)); return stagedChange; } @Override public List<StagedChange> stageChanges(final List<Change> changes) { return changes.stream().map(this::stageChange).toList(); } }
5,482
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/service/StagedChangesPoller.java
package com.paypal.infrastructure.changestaging.service; import com.paypal.infrastructure.changestaging.service.operations.StagedChangesExecutorInfo; import com.paypal.infrastructure.changestaging.service.operations.StagedChangesOperationRegistry; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; @Component @Slf4j public class StagedChangesPoller { private final StagedChangesProcessor stagedChangesProcessor; private final ExecutionCounter executionCounter; public StagedChangesPoller(final StagedChangesOperationRegistry stagedChangesOperationRegistry, final StagedChangesProcessor stagedChangesProcessor) { this.executionCounter = new ExecutionCounter(stagedChangesOperationRegistry.getAllStagedChangesExecutorInfo()); this.stagedChangesProcessor = stagedChangesProcessor; } @Scheduled(fixedRateString = "${hmc.changestaging.polling-rate}", initialDelayString = "${hmc.changestaging.initial-delay}") public void performStagedChange() { final StagedChangesExecutorInfo stagedChangesExecutorInfo = executionCounter.next(); stagedChangesProcessor.performStagedChangesFor(stagedChangesExecutorInfo); } private static class ExecutionCounter { private final Map<StagedChangesExecutorInfo, Long> executions; public ExecutionCounter(final Set<StagedChangesExecutorInfo> candidates) { this.executions = candidates.stream().collect(Collectors.toMap(Function.identity(), e -> 0L)); } public StagedChangesExecutorInfo next() { final StagedChangesExecutorInfo next = executions.entrySet().stream().min(Map.Entry.comparingByValue()) .map(Map.Entry::getKey).orElseThrow(() -> new IllegalStateException("No candidates found")); executions.put(next, executions.get(next) + 1); return next; } } }
5,483
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/service/ChangeStagingService.java
package com.paypal.infrastructure.changestaging.service; import com.paypal.infrastructure.changestaging.model.Change; import com.paypal.infrastructure.changestaging.model.StagedChange; import java.util.List; public interface ChangeStagingService { StagedChange stageChange(Change change); List<StagedChange> stageChanges(List<Change> changes); }
5,484
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/service/StagedChangesProcessor.java
package com.paypal.infrastructure.changestaging.service; import com.paypal.infrastructure.changestaging.repositories.StagedChangesRepository; import com.paypal.infrastructure.changestaging.repositories.entities.StagedChangeEntity; import com.paypal.infrastructure.changestaging.service.converters.StagedChangesEntityConverter; import com.paypal.infrastructure.changestaging.service.operations.StagedChangesExecutor; import com.paypal.infrastructure.changestaging.service.operations.StagedChangesExecutorInfo; import com.paypal.infrastructure.changestaging.service.operations.StagedChangesOperationRegistry; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Slf4j @Component @Transactional public class StagedChangesProcessor { @Value("${hmc.changestaging.batch-size}") private int operationBatchSize; private final StagedChangesRepository stagedChangesRepository; private final StagedChangesEntityConverter stagedChangesEntityConverter; private final StagedChangesOperationRegistry stagedChangesOperationRegistry; public StagedChangesProcessor(final StagedChangesRepository stagedChangesRepository, final StagedChangesEntityConverter stagedChangesEntityConverter, final StagedChangesOperationRegistry stagedChangesOperationRegistry) { this.stagedChangesRepository = stagedChangesRepository; this.stagedChangesEntityConverter = stagedChangesEntityConverter; this.stagedChangesOperationRegistry = stagedChangesOperationRegistry; } public void performStagedChangesFor(final StagedChangesExecutorInfo stagedChangesExecutorInfo) { final List<StagedChangeEntity> stagedChanges = retrieveStagedChanges(stagedChangesExecutorInfo); if (!stagedChanges.isEmpty()) { log.info("Executing {} staged changes of type {} for target {}", stagedChanges.size(), stagedChangesExecutorInfo.getType().getName(), stagedChangesExecutorInfo.getTarget()); processStagedChanges(stagedChangesExecutorInfo, stagedChanges); } } private List<StagedChangeEntity> retrieveStagedChanges(final StagedChangesExecutorInfo stagedChangesExecutorInfo) { //@formatter:off return stagedChangesRepository.findByTypeAndOperationAndTargetOrderByCreationDateAsc( stagedChangesExecutorInfo.getType().getName(), stagedChangesExecutorInfo.getOperation(), stagedChangesExecutorInfo.getTarget(), Pageable.ofSize(operationBatchSize)); //@formatter:on } private void processStagedChanges(final StagedChangesExecutorInfo stagedChangesExecutorInfo, final List<StagedChangeEntity> stagedChanges) { final StagedChangesExecutor stagedChangesExecutor = stagedChangesOperationRegistry .getStagedChangesExecutor(stagedChangesExecutorInfo); try { stagedChangesExecutor.execute(stagedChangesEntityConverter.from(stagedChanges)); } finally { final List<String> stagedChangeIds = stagedChanges.stream().map(StagedChangeEntity::getId).toList(); stagedChangesRepository.deleteByIdIn(stagedChangeIds); } } }
5,485
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/service
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/service/converters/StagedChangesModelConverter.java
package com.paypal.infrastructure.changestaging.service.converters; import com.paypal.infrastructure.changestaging.model.Change; import com.paypal.infrastructure.changestaging.model.StagedChange; import org.mapstruct.Mapper; import org.mapstruct.Mapping; @Mapper(componentModel = "spring") public interface StagedChangesModelConverter { @Mapping(target = "id", expression = "java(java.util.UUID.randomUUID().toString())") @Mapping(target = "creationDate", expression = "java(new java.util.Date())") StagedChange from(Change source); }
5,486
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/service
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/service/converters/StagedChangesEntityConverter.java
package com.paypal.infrastructure.changestaging.service.converters; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.mirakl.client.core.internal.mapper.PatchSerializer; import com.mirakl.client.core.internal.util.Patch; import com.paypal.infrastructure.changestaging.model.StagedChange; import com.paypal.infrastructure.changestaging.repositories.entities.StagedChangeEntity; import lombok.SneakyThrows; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.Named; import java.util.List; @Mapper(componentModel = "spring") public interface StagedChangesEntityConverter { @Mapping(target = "payload", source = "source") StagedChangeEntity from(StagedChange source); @Mapping(target = "payload", qualifiedByName = "payloadDeserialization", source = "source") StagedChange from(StagedChangeEntity source); List<StagedChange> from(List<StagedChangeEntity> source); @SneakyThrows default String payloadFrom(final StagedChange source) { return getObjectMapper().writeValueAsString(source.getPayload()); } @SneakyThrows @Named("payloadDeserialization") default Object payloadFrom(final StagedChangeEntity source) { return getObjectMapper().readValue(source.getPayload(), Class.forName(source.getType())); } default String from(final Class<?> value) { return value.getName(); } @SneakyThrows default Class<?> map(final String value) { return Class.forName(value); } @SuppressWarnings("java:S3740") default ObjectMapper getObjectMapper() { final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); final SimpleModule module = new SimpleModule(); module.addSerializer(Patch.class, new PatchSerializer()); objectMapper.registerModule(module); return objectMapper; } }
5,487
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/service
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/service/operations/StagedChangesExecutorInfo.java
package com.paypal.infrastructure.changestaging.service.operations; import com.paypal.infrastructure.changestaging.model.ChangeOperation; import com.paypal.infrastructure.changestaging.model.ChangeTarget; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class StagedChangesExecutorInfo { private Class<?> type; private ChangeOperation operation; private ChangeTarget target; }
5,488
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/service
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/service/operations/StagedChangesExecutor.java
package com.paypal.infrastructure.changestaging.service.operations; import com.paypal.infrastructure.changestaging.model.StagedChange; import java.util.List; public interface StagedChangesExecutor { void execute(List<StagedChange> changes); StagedChangesExecutorInfo getExecutorInfo(); }
5,489
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/service
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/service/operations/StagedChangesOperationRegistry.java
package com.paypal.infrastructure.changestaging.service.operations; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; @Component public class StagedChangesOperationRegistry { private final Map<StagedChangesExecutorInfo, StagedChangesExecutor> stringStagedChangesOperationsMap; public StagedChangesOperationRegistry(final List<StagedChangesExecutor> stagedChangesExecutors) { this.stringStagedChangesOperationsMap = stagedChangesExecutors.stream() .collect(Collectors.toMap(StagedChangesExecutor::getExecutorInfo, Function.identity())); } public StagedChangesExecutor getStagedChangesExecutor(final StagedChangesExecutorInfo stagedChangesExecutorInfo) { return stringStagedChangesOperationsMap.get(stagedChangesExecutorInfo); } public Set<StagedChangesExecutorInfo> getAllStagedChangesExecutorInfo() { return stringStagedChangesOperationsMap.keySet(); } }
5,490
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/controllers/ChangeStagingManagementController.java
package com.paypal.infrastructure.changestaging.controllers; import com.paypal.infrastructure.changestaging.controllers.converters.StagedChangesDtoConverter; import com.paypal.infrastructure.changestaging.controllers.dtos.StagedChangeDto; import com.paypal.infrastructure.changestaging.repositories.StagedChangesRepository; import com.paypal.infrastructure.changestaging.repositories.entities.StagedChangeEntity; import com.paypal.infrastructure.changestaging.service.StagedChangesPoller; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.PagedModel; import org.springframework.web.bind.annotation.*; import static org.springframework.http.HttpStatus.OK; @RestController @RequestMapping("/management/staged-changes") public class ChangeStagingManagementController { private final StagedChangesRepository stagedChangesRepository; private final StagedChangesDtoConverter stagedChangesDtoConverter; private final StagedChangesPoller stagedChangesPoller; private final PagedResourcesAssembler<StagedChangeDto> pagedResourcesAssembler; public ChangeStagingManagementController(final StagedChangesRepository stagedChangesRepository, final StagedChangesDtoConverter stagedChangesDtoConverter, final StagedChangesPoller stagedChangesPoller, final PagedResourcesAssembler<StagedChangeDto> pagedResourcesAssembler) { this.stagedChangesRepository = stagedChangesRepository; this.stagedChangesDtoConverter = stagedChangesDtoConverter; this.stagedChangesPoller = stagedChangesPoller; this.pagedResourcesAssembler = pagedResourcesAssembler; } @GetMapping("/") public PagedModel<EntityModel<StagedChangeDto>> findAll(final Pageable pageable) { final Page<StagedChangeEntity> stagedChanges = stagedChangesRepository.findAll(pageable); return pagedResourcesAssembler.toModel(stagedChangesDtoConverter.from(stagedChanges)); } @PostMapping("/process") @ResponseStatus(OK) public void process() { stagedChangesPoller.performStagedChange(); } }
5,491
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/controllers
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/controllers/converters/StagedChangesDtoConverter.java
package com.paypal.infrastructure.changestaging.controllers.converters; import com.paypal.infrastructure.changestaging.controllers.dtos.StagedChangeDto; import com.paypal.infrastructure.changestaging.repositories.entities.StagedChangeEntity; import org.mapstruct.Mapper; import org.springframework.data.domain.Page; @Mapper(componentModel = "spring") public interface StagedChangesDtoConverter { StagedChangeDto from(StagedChangeEntity source); default String from(final Class<?> value) { return value.getName(); } default Page<StagedChangeDto> from(final Page<StagedChangeEntity> source) { return source.map(this::from); } }
5,492
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/controllers
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/changestaging/controllers/dtos/StagedChangeDto.java
package com.paypal.infrastructure.changestaging.controllers.dtos; import lombok.Data; import java.util.Date; @Data public class StagedChangeDto { private String id; private String type; private String operation; private String target; private Object payload; private Date creationDate; }
5,493
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mail
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mail/configuration/MailConfiguration.java
package com.paypal.infrastructure.mail.configuration; import lombok.Getter; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; /** * Mail configuration class */ @Getter @Configuration public class MailConfiguration { @Value("${hmc.mail-alerts.settings.recipients}") private String notificationRecipients; @Value("${hmc.mail-alerts.settings.from}") private String fromNotificationEmail; }
5,494
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mail
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mail/services/MailNotificationUtilDisabled.java
package com.paypal.infrastructure.mail.services; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Service; /** * Default implementation of {@link MailNotificationUtil} */ @ConditionalOnProperty(prefix = "hmc.toggle-features.", name = "mail-alerts", havingValue = "false") @Slf4j @Service public class MailNotificationUtilDisabled implements MailNotificationUtil { /** * {@inheritDoc} */ @Override public void sendPlainTextEmail(final String subject, final String body) { log.info("Send email subject: " + subject + " body: " + body); } }
5,495
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mail
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mail/services/MailNotificationUtilImpl.java
package com.paypal.infrastructure.mail.services; import com.paypal.infrastructure.mail.configuration.MailConfiguration; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; /** * Default implementation of {@link MailNotificationUtil} */ @ConditionalOnProperty(prefix = "hmc.toggle-features.", name = "mail-alerts", havingValue = "true") @Slf4j @Service public class MailNotificationUtilImpl implements MailNotificationUtil { @Resource private JavaMailSender emailSender; @Resource private MailConfiguration mailConfiguration; /** * {@inheritDoc} */ @Override public void sendPlainTextEmail(final String subject, final String body) { final SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(mailConfiguration.getFromNotificationEmail()); message.setTo(mailConfiguration.getNotificationRecipients()); message.setSubject(subject); message.setText(body); try { emailSender.send(message); } catch (final RuntimeException e) { log.error("Email could not be sent. Reason: ", e); } } }
5,496
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mail
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mail/services/MailNotificationUtil.java
package com.paypal.infrastructure.mail.services; /** * Service that offers email sending functionality */ public interface MailNotificationUtil { /** * Sends an email with the attributes received without a message prefix * @param subject Email's subject * @param body Email's body message */ void sendPlainTextEmail(String subject, String body); }
5,497
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/itemlinks/ItemLinksConfiguration.java
package com.paypal.infrastructure.itemlinks; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan public class ItemLinksConfiguration { }
5,498
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/itemlinks
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/itemlinks/converters/ItemLinksModelEntityConverter.java
package com.paypal.infrastructure.itemlinks.converters; import com.paypal.infrastructure.itemlinks.entities.ItemLinkEntity; import com.paypal.infrastructure.itemlinks.model.HyperwalletItemLinkLocator; import com.paypal.infrastructure.itemlinks.model.MiraklItemLinkLocator; import org.mapstruct.Mapper; import org.mapstruct.Mapping; @Mapper(componentModel = "spring") public interface ItemLinksModelEntityConverter { @Mapping(target = "sourceId", source = "source.id") @Mapping(target = "sourceType", source = "source.type") @Mapping(target = "sourceSystem", source = "source.system") @Mapping(target = "targetId", source = "target.id") @Mapping(target = "targetType", source = "target.type") @Mapping(target = "targetSystem", source = "target.system") ItemLinkEntity from(MiraklItemLinkLocator source, HyperwalletItemLinkLocator target); @Mapping(target = "id", source = "targetId") @Mapping(target = "type", source = "targetType") HyperwalletItemLinkLocator hyperwalletLocatorFromLinkTarget(ItemLinkEntity itemLinkEntity); }
5,499