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-infrastructure/src/main/java/com/paypal/infrastructure/itemlinks
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/itemlinks/repositories/ItemLinkRepository.java
package com.paypal.infrastructure.itemlinks.repositories; import com.paypal.infrastructure.itemlinks.entities.ItemLinkEntity; import com.paypal.infrastructure.itemlinks.entities.ItemLinkEntityId; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Collection; import java.util.List; @Repository public interface ItemLinkRepository extends JpaRepository<ItemLinkEntity, ItemLinkEntityId> { List<ItemLinkEntity> findBySourceSystemAndSourceIdAndSourceTypeAndTargetSystemAndTargetTypeIn(String sourceSystem, String sourceId, String sourceType, String targetSystem, Collection<String> targetTypes); }
5,500
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/model/MiraklItemTypes.java
package com.paypal.infrastructure.itemlinks.model; /** * List of all possible values of Mirakl items. */ public enum MiraklItemTypes { SHOP, INVOICE }
5,501
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/model/MiraklItemLinkLocator.java
package com.paypal.infrastructure.itemlinks.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; /** * Represents a reference to a Mirakl item. */ @Data @Builder @AllArgsConstructor public class MiraklItemLinkLocator implements ItemLinkLocator<MiraklItemTypes> { private String id; private MiraklItemTypes type; @Override public ItemLinkExternalSystem getSystem() { return ItemLinkExternalSystem.MIRAKL; } }
5,502
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/model/HyperwalletItemLinkLocator.java
package com.paypal.infrastructure.itemlinks.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; /** * Represents a reference to a Hyperwallet item. */ @Data @Builder @AllArgsConstructor public class HyperwalletItemLinkLocator implements ItemLinkLocator<HyperwalletItemTypes> { private String id; private HyperwalletItemTypes type; @Override public ItemLinkExternalSystem getSystem() { return ItemLinkExternalSystem.HYPERWALLET; } }
5,503
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/model/HyperwalletItemTypes.java
package com.paypal.infrastructure.itemlinks.model; /** * List of all possible values of Hyperwallet items. */ public enum HyperwalletItemTypes { PROGRAM, BANK_ACCOUNT, USER, BUSINESS_STAKEHOLDER, PAYMENT }
5,504
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/model/ItemLinkExternalSystem.java
package com.paypal.infrastructure.itemlinks.model; /** * All possible external systems available for tracking relationships between item * references. */ public enum ItemLinkExternalSystem { MIRAKL, HYPERWALLET }
5,505
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/model/ItemLinkLocator.java
package com.paypal.infrastructure.itemlinks.model; /** * Represents a reference for an item in an external system. The item is identified by its * Id and its Type. * * @param <T> Enum with all possible values for item types. */ public interface ItemLinkLocator<T> { /** * Returns the id of the item. * @return an Id. */ String getId(); /** * Returns the type of the item. * @return an enum value with the type. */ T getType(); /** * Returns the system where the item is stored. * @return an enum value with the system. */ ItemLinkExternalSystem getSystem(); }
5,506
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/services/ItemLinksServiceImpl.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.HyperwalletItemLinkLocator; import com.paypal.infrastructure.itemlinks.model.HyperwalletItemTypes; import com.paypal.infrastructure.itemlinks.model.ItemLinkExternalSystem; import com.paypal.infrastructure.itemlinks.model.MiraklItemLinkLocator; import com.paypal.infrastructure.itemlinks.repositories.ItemLinkRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; @Service @Transactional public class ItemLinksServiceImpl implements ItemLinksService { private final ItemLinkRepository itemLinkRepository; private final ItemLinksModelEntityConverter itemLinksModelEntityConverter; public ItemLinksServiceImpl(final ItemLinkRepository itemLinkRepository, final ItemLinksModelEntityConverter itemLinksModelEntityConverter) { this.itemLinkRepository = itemLinkRepository; this.itemLinksModelEntityConverter = itemLinksModelEntityConverter; } @Override public void createLinks(final MiraklItemLinkLocator miraklItemLocator, final Collection<HyperwalletItemLinkLocator> hyperwalletItemLocators) { // formatter:off final Collection<ItemLinkEntity> itemLinkEntities = hyperwalletItemLocators.stream() .map(hwItemLocator -> itemLinksModelEntityConverter.from(miraklItemLocator, hwItemLocator)) .collect(Collectors.toSet()); // formatter:on itemLinkRepository.saveAll(itemLinkEntities); } @Override public Map<MiraklItemLinkLocator, Collection<HyperwalletItemLinkLocator>> findLinks( final Collection<MiraklItemLinkLocator> sourceItem, final Set<HyperwalletItemTypes> targetTypes) { // formatter:off return sourceItem.stream() .collect(Collectors.toMap(Function.identity(), source -> findLinks(source, targetTypes))); // formatter_on } @Override public Collection<HyperwalletItemLinkLocator> findLinks(final MiraklItemLinkLocator sourceItem, final Set<HyperwalletItemTypes> hyperwalletItemTypes) { // formatter:off final List<ItemLinkEntity> itemLinkEntityList = itemLinkRepository .findBySourceSystemAndSourceIdAndSourceTypeAndTargetSystemAndTargetTypeIn( sourceItem.getSystem().toString(), sourceItem.getId(), sourceItem.getType().toString(), ItemLinkExternalSystem.HYPERWALLET.toString(), hyperwalletItemTypes.stream().map(HyperwalletItemTypes::toString).collect(Collectors.toSet())); // formatter:on return itemLinkEntityList.stream().map(itemLinksModelEntityConverter::hyperwalletLocatorFromLinkTarget) .collect(Collectors.toSet()); } }
5,507
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/services/ItemLinksService.java
package com.paypal.infrastructure.itemlinks.services; import com.paypal.infrastructure.itemlinks.model.HyperwalletItemLinkLocator; import com.paypal.infrastructure.itemlinks.model.HyperwalletItemTypes; import com.paypal.infrastructure.itemlinks.model.MiraklItemLinkLocator; import org.springframework.stereotype.Service; import java.util.Collection; import java.util.Map; import java.util.Set; /** * This service is used to keep track of the relationships between Mirakl and Hyperwallet * entities. This information in persisted in the database so is kept between restarts. * */ @Service public interface ItemLinksService { /** * Stores the provided links. * @param miraklItemLocator A reference to a Mirakl item. * @param hyperwalletItemLocators A collection of references to Hyperwallet items. */ void createLinks(MiraklItemLinkLocator miraklItemLocator, Collection<HyperwalletItemLinkLocator> hyperwalletItemLocators); /** * Retrieves all the links of the requested types for the list of Mirakl references * passed * @param sourceItem A reference to a Mirakl item. * @param targetTypes The types of Hyperwallet items to find. * @return A map with a collection of Hyperwallet references for each of the requested * Mirakl references. */ Map<MiraklItemLinkLocator, Collection<HyperwalletItemLinkLocator>> findLinks( Collection<MiraklItemLinkLocator> sourceItem, Set<HyperwalletItemTypes> targetTypes); /** * Retrieves all the links of the requested types for the list of Mirakl references * passed * @param sourceItem A reference to a Mirakl item. * @param hyperwalletItemTypes The types of Hyperwallet items to find. * @return all items relationships found. */ Collection<HyperwalletItemLinkLocator> findLinks(MiraklItemLinkLocator sourceItem, Set<HyperwalletItemTypes> hyperwalletItemTypes); }
5,508
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/entities/ItemLinkEntityId.java
package com.paypal.infrastructure.itemlinks.entities; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Data @NoArgsConstructor @AllArgsConstructor public class ItemLinkEntityId implements Serializable { private String sourceId; private String sourceType; private String sourceSystem; private String targetType; private String targetSystem; }
5,509
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/entities/ItemLinkEntity.java
package com.paypal.infrastructure.itemlinks.entities; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import jakarta.persistence.*; import java.io.Serializable; @Data @Entity @Builder(toBuilder = true) @NoArgsConstructor @AllArgsConstructor @IdClass(ItemLinkEntityId.class) @Table(indexes = { @Index(columnList = "sourceId,sourceType,sourceSystem,targetSystem,targetType") }) public class ItemLinkEntity implements Serializable { @Id private String sourceId; @Id private String sourceType; @Id private String sourceSystem; private String targetId; @Id private String targetType; @Id private String targetSystem; }
5,510
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/converter/Converter.java
package com.paypal.infrastructure.support.converter; import org.springframework.lang.NonNull; /** * Interface to convert objects from source class {@link S} into target class {@link T} * * @param <S> Source class * @param <T> Target class */ public interface Converter<S, T> { /** * Method that retrieves a {@link S} and returns a {@link T} * @param source the source object {@link S} * @return the returned object {@link T} */ T convert(@NonNull final S source); }
5,511
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/date/TimeMachine.java
package com.paypal.infrastructure.support.date; import java.time.Clock; import java.time.LocalDateTime; import java.time.ZoneId; /** * Time machine class to help with date testing */ public final class TimeMachine { private static Clock clock = Clock.systemDefaultZone(); private static final ZoneId zoneId = ZoneId.systemDefault(); private TimeMachine() { // doNothing } /** * Returns the current {@link LocalDateTime} * @return a {@link LocalDateTime} */ public static LocalDateTime now() { return LocalDateTime.now(getClock()); } /** * Fixes the clock date to an specific {@link LocalDateTime} * @param date The {@link LocalDateTime} */ public static void useFixedClockAt(final LocalDateTime date) { clock = Clock.fixed(date.atZone(zoneId).toInstant(), zoneId); } /** * Sets the default zone to the system default one */ public static void useSystemDefaultZoneClock() { clock = Clock.systemDefaultZone(); } /** * Returns the {@link Clock} * @return The {@link Clock} */ private static Clock getClock() { return clock; } }
5,512
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/date/DateUtil.java
package com.paypal.infrastructure.support.date; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Objects; import java.util.TimeZone; /** * Utility class to handle dates */ @Slf4j public final class DateUtil { public static final TimeZone TIME_UTC = TimeZone.getTimeZone("UTC"); private DateUtil() { } /** * Converts a {@link Date} into a {@link LocalDateTime} * @param date the {@link Date} to convert * @return the date converted into {@link LocalDateTime} */ public static LocalDateTime convertToLocalDateTime(final Date date) { final ZoneId defaultZoneId = ZoneId.systemDefault(); final Instant instant = date.toInstant(); return instant.atZone(defaultZoneId).toLocalDateTime(); } /** * Converts a {@link LocalDateTime} into a {@link Date} * @param localDateTime the {@link LocalDateTime} to convert * @param zoneId * @return the date converted into {@link Date} */ public static Date convertToDate(final LocalDateTime localDateTime, final ZoneId zoneId) { return Date.from(localDateTime.atZone(zoneId).toInstant()); } /** * Converts a {@link LocalDate} into a {@link Date} * @param localDate the {@link LocalDate} to convert * @param zoneId * @return the date converted into {@link Date} */ public static Date convertToDate(final LocalDate localDate, final ZoneId zoneId) { return Date.from(localDate.atStartOfDay(zoneId).toInstant()); } /** * Converts a {@link String} into a {@link Date} * @param stringDate the {@link String} to convert * @param timeZone timezone used to parse the date * @return the date converted into {@link Date} */ public static Date convertToDate(final String stringDate, final String dateFormat, final TimeZone timeZone) { try { final DateFormat format = new SimpleDateFormat(dateFormat, Locale.ENGLISH); format.setTimeZone(timeZone); return format.parse(stringDate); } catch (final ParseException ex) { log.error("Invalid date format [{}] for date [{}]", dateFormat, stringDate); log.error(ex.getMessage(), ex); return null; } } /** * Converts a {@link LocalDate} into a {@link String} * @param localDateTime the {@link LocalDate} to convert * @param dateFormatPattern date format required * @return the date converted into {@link String} */ public static String convertToString(final LocalDateTime localDateTime, final String dateFormatPattern) { if (StringUtils.isNotEmpty(dateFormatPattern) && Objects.nonNull(localDateTime)) { final DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(dateFormatPattern, Locale.ENGLISH); return localDateTime.format(dateFormat); } return StringUtils.EMPTY; } }
5,513
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/exceptions/HMCHyperwalletAPIException.java
package com.paypal.infrastructure.support.exceptions; import com.hyperwallet.clientsdk.HyperwalletException; /** * Base exception for all Hyperwallet Connector exceptions. */ public class HMCHyperwalletAPIException extends HMCException { protected static final String DEFAULT_MSG = "An error has occurred while invoking Hyperwallet API"; private final HyperwalletException hyperwalletException; public HMCHyperwalletAPIException(final String message, final HyperwalletException e) { super(message, e); hyperwalletException = e; } public HMCHyperwalletAPIException(final HyperwalletException e) { super(DEFAULT_MSG, e); hyperwalletException = e; } public HyperwalletException getHyperwalletException() { return hyperwalletException; } }
5,514
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/exceptions/InvalidConfigurationException.java
package com.paypal.infrastructure.support.exceptions; public class InvalidConfigurationException extends HMCException { public InvalidConfigurationException(final String message) { super(message); } public InvalidConfigurationException(final String message, final Throwable cause) { super(message, cause); } }
5,515
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/exceptions/HMCErrorResponse.java
package com.paypal.infrastructure.support.exceptions; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * Wraps HMC API error messages. */ @Getter @RequiredArgsConstructor public class HMCErrorResponse { /** * The error message used in the API response. */ private final String errorMessage; }
5,516
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/exceptions/DateIntervalException.java
package com.paypal.infrastructure.support.exceptions; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * Exception for handling date interval errors, it is when from date is after to date. */ public class DateIntervalException extends HMCException { public static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss"; private static final String DATE_INTERVAL_ERROR_MESSAGE = "[From] date [%s] can not be later than [To] date [%s]"; /** * from {@link Date}. */ private final Date from; /** * to {@link Date}. */ private final Date to; public DateIntervalException(final Date from, final Date to) { this.from = from; this.to = to; } /** * Overrides the error message for using an specific error message format. * @return an error message with the following format: [From] date {@code from} can * not be later than [To] date {@code to}. */ @Override public String getMessage() { final DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); return DATE_INTERVAL_ERROR_MESSAGE.formatted(dateFormat.format(this.from), dateFormat.format(this.to)); } }
5,517
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/exceptions/HMCMiraklAPIException.java
package com.paypal.infrastructure.support.exceptions; import com.mirakl.client.core.exception.MiraklException; /** * Base exception for all Mirakl Connector exceptions. */ public class HMCMiraklAPIException extends HMCException { protected static final String DEFAULT_MSG = "An error has occurred while invoking Mirakl API"; private final MiraklException miraklException; public HMCMiraklAPIException(final String message, final MiraklException e) { super(message, e); miraklException = e; } public HMCMiraklAPIException(final MiraklException e) { super(DEFAULT_MSG, e); miraklException = e; } public MiraklException getMiraklException() { return miraklException; } }
5,518
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/exceptions/HMCExceptionHandler.java
package com.paypal.infrastructure.support.exceptions; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; /** * Controller advice for handling HMC exceptions. */ @Slf4j @RestControllerAdvice public class HMCExceptionHandler { /** * Handles {@link HMCException} exceptions. * @param exception a {@link HMCException} exception. * @return a {@link ResponseEntity} of {@link HMCErrorResponse} with http bad request * status and an exception error message. */ @ExceptionHandler(HMCException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public HMCErrorResponse handleHMCException(final HMCException exception) { log.warn(exception.getMessage(), exception); return new HMCErrorResponse(exception.getMessage()); } /** * Handles {@link MethodArgumentTypeMismatchException} exceptions. * @param exception a {@link MethodArgumentTypeMismatchException} exception. * @return a {@link ResponseEntity} of {@link HMCErrorResponse} with http bad request * status and an exception error message. */ @ExceptionHandler(MethodArgumentTypeMismatchException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public HMCErrorResponse handleMethodArgumentTypeMismatchException( final MethodArgumentTypeMismatchException exception) { log.warn(exception.getMessage(), exception); return new HMCErrorResponse(HttpStatus.BAD_REQUEST.getReasonPhrase()); } /** * Handles {@link MissingServletRequestParameterException} exceptions. * @param exception a {@link MissingServletRequestParameterException} exception. * @return a {@link ResponseEntity} of {@link HMCErrorResponse} with http bad request * status and an exception error message. */ @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public HMCErrorResponse handleMissingRequestParametersException( final MissingServletRequestParameterException exception) { log.warn(exception.getMessage(), exception); return new HMCErrorResponse(HttpStatus.BAD_REQUEST.getReasonPhrase()); } }
5,519
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/exceptions/HMCException.java
package com.paypal.infrastructure.support.exceptions; /** * Base exception for all internal errors in Hyperwallet-Mirakl Connector. */ public class HMCException extends RuntimeException { public HMCException() { } public HMCException(final String message) { super(message); } public HMCException(final String message, final Throwable cause) { super(message, cause); } public HMCException(final Throwable cause) { super(cause); } public HMCException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
5,520
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/countries/CountriesUtil.java
package com.paypal.infrastructure.support.countries; import org.apache.commons.lang3.StringUtils; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Optional; /** * Utility class for helping with countries manipulation */ public final class CountriesUtil { private static final Map<String, Locale> localeMap; static { final String[] countries = Locale.getISOCountries(); localeMap = new HashMap<>(countries.length * 2); for (final String country : countries) { final Locale locale = new Locale("", country); localeMap.put(locale.getISO3Country().toUpperCase(), locale); localeMap.put(country.toUpperCase(), locale); } } private CountriesUtil() { throw new IllegalStateException("Utility class"); } /** * Returns the {@link Locale} representation of a three letter isocode country * @param isocode the isocode representation * @return the {@link Locale} */ public static Optional<Locale> getLocaleByIsocode(final String isocode) { if (StringUtils.isBlank(isocode)) { return Optional.empty(); } return Optional.ofNullable(localeMap.get(isocode.toUpperCase())); } }
5,521
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/logging/LoggingConstantsUtil.java
package com.paypal.infrastructure.support.logging; /** * Class to store logging global constants */ public final class LoggingConstantsUtil { private LoggingConstantsUtil() { } public static final String LIST_LOGGING_SEPARATOR = ","; }
5,522
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/logging/HyperwalletLoggingErrorsUtil.java
package com.paypal.infrastructure.support.logging; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.hyperwallet.clientsdk.HyperwalletException; import lombok.extern.slf4j.Slf4j; /** * Util class for logging errors of {@link HyperwalletException} */ @Slf4j public final class HyperwalletLoggingErrorsUtil { private HyperwalletLoggingErrorsUtil() { } /** * Stringifies the exception {@link HyperwalletException} * @param exception the {@link HyperwalletException} * @return the stringified version of {@link HyperwalletException} */ public static String stringify(final HyperwalletException exception) { final HyperwalletErrorLogEntry logEntry = HyperwalletErrorLogEntryConverter.INSTANCE.from(exception); final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); try { return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(logEntry); } catch (final JsonProcessingException e) { log.warn("An error has been occurred while generating detailed error information from Hyperwallet error", e); return exception.getMessage(); } } }
5,523
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/logging/HyperwalletErrorLogEntry.java
package com.paypal.infrastructure.support.logging; import lombok.Data; import java.util.List; @Data public class HyperwalletErrorLogEntry { private String errorCode; private String errorMessage; private String exceptionMessage; private String responseStatusCode; private String responseMessage; private String responseBody; List<ErrorDetail> errorDetailList; @Data public static class ErrorDetail { private String code; private String fieldName; private String message; private List<String> relatedResources; } }
5,524
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/logging/MiraklLoggingErrorsUtil.java
package com.paypal.infrastructure.support.logging; import com.mirakl.client.core.exception.MiraklException; /** * Util class for logging errors of {@link MiraklException} */ public final class MiraklLoggingErrorsUtil { private static final String MESSAGE_FORMAT = "{exceptionMessage=%s,}"; private MiraklLoggingErrorsUtil() { } /** * Stringifies the exception {@link MiraklException} * @param exception the {@link MiraklException} * @return the stringified version of {@link MiraklException} */ public static String stringify(final MiraklException exception) { return MESSAGE_FORMAT.formatted(exception.getMessage()); } }
5,525
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/logging/HyperwalletErrorLogEntryConverter.java
package com.paypal.infrastructure.support.logging; import com.hyperwallet.clientsdk.HyperwalletException; import com.hyperwallet.clientsdk.model.HyperwalletError; import com.hyperwallet.clientsdk.model.HyperwalletErrorList; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.factory.Mappers; import java.util.List; @Mapper public interface HyperwalletErrorLogEntryConverter { HyperwalletErrorLogEntryConverter INSTANCE = Mappers.getMapper(HyperwalletErrorLogEntryConverter.class); HyperwalletErrorLogEntry.ErrorDetail from(HyperwalletError hyperwalletError); List<HyperwalletErrorLogEntry.ErrorDetail> from(List<HyperwalletError> hyperwalletError); default List<HyperwalletError> from(final HyperwalletErrorList hyperwalletError) { return hyperwalletError.getErrors(); } @Mapping(target = "responseStatusCode", source = "response.responseCode") @Mapping(target = "responseMessage", source = "response.responseMessage") @Mapping(target = "responseBody", source = "response.body") @Mapping(target = "exceptionMessage", source = "message") @Mapping(target = "errorDetailList", source = "hyperwalletErrors") HyperwalletErrorLogEntry from(HyperwalletException exception); }
5,526
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/services/TokenSynchronizationService.java
package com.paypal.infrastructure.support.services; /** * Service for ensure the tokens in hypewallet and mirakl ar in sync * * @param <T> */ public interface TokenSynchronizationService<T> { /** * Synchronize the tokens in hypewallet and mirakl for a specific item * @param model that contains the item to synchronize * @return the updated model item with the token in case there was a synchronization */ T synchronizeToken(T model); }
5,527
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/strategy/Strategy.java
package com.paypal.infrastructure.support.strategy; /** * Strategy interface */ public interface Strategy<S, T> { /** * Executes the business logic based on the content of {@code source} and returns a * {@link T} class based on a set of strategies * @param source the source object of type {@link S} * @return the converted object of type {@link T} */ T execute(S source); /** * Checks whether the strategy must be executed based on the {@code source} * @param source the source object * @return returns whether the strategy is applicable or not */ boolean isApplicable(S source); }
5,528
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/strategy/SingleAbstractStrategyExecutor.java
package com.paypal.infrastructure.support.strategy; import java.util.Objects; import java.util.Set; /** * Abstract strategy executor that ensures that only one strategy is run for an specific * source and target */ public abstract class SingleAbstractStrategyExecutor<S, T> implements StrategyExecutor<S, T> { @Override public T execute(final S source) { if (Objects.nonNull(getStrategies()) && !getStrategies().isEmpty()) { for (final Strategy<S, T> strategy : getStrategies()) { if (strategy.isApplicable(source)) { return strategy.execute(source); } } } return null; } protected abstract Set<Strategy<S, T>> getStrategies(); }
5,529
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/strategy/StrategyExecutor.java
package com.paypal.infrastructure.support.strategy; /** * Generic interface for executing strategies */ public interface StrategyExecutor<S, T> { /** * Executes business logic based on the {@code source} and returns the target * {@link T} class based on a set of strategies * @param source the source object of type {@link S} * @return the returned object of type {@link T} */ T execute(S source); }
5,530
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/support/strategy/MultipleAbstractStrategyExecutor.java
package com.paypal.infrastructure.support.strategy; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Set; /** * Abstract strategy executor that ensures that multiple strategies run for an specific * source and target */ public abstract class MultipleAbstractStrategyExecutor<S, T> implements StrategyExecutor<S, List<T>> { @Override public List<T> execute(final S source) { final ArrayList<T> appendedExecution = new ArrayList<>(); final Set<Strategy<S, T>> strategies = getStrategies(); if (Objects.nonNull(strategies)) { for (final Strategy<S, T> strategy : strategies) { if (strategy.isApplicable(source)) { appendedExecution.add(strategy.execute(source)); } } } return appendedExecution; } protected abstract Set<Strategy<S, T>> getStrategies(); }
5,531
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/hyperwallet/InfrastructureHyperwalletConfig.java
package com.paypal.infrastructure.hyperwallet; import com.hyperwallet.clientsdk.util.HyperwalletEncryption; import com.nimbusds.jose.EncryptionMethod; import com.nimbusds.jose.JWEAlgorithm; import com.nimbusds.jose.JWSAlgorithm; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletEncryptionConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan public class InfrastructureHyperwalletConfig { @ConditionalOnProperty("hmc.hyperwallet.encryption.encryptionEnabled") @Bean public HyperwalletEncryption hyperwalletEncryptionWrapper( final HyperwalletEncryptionConfiguration encryptionConfiguration) { //@formatter:off return new HyperwalletEncryption( JWEAlgorithm.parse(encryptionConfiguration.getEncryptionAlgorithm()), JWSAlgorithm.parse(encryptionConfiguration.getSignAlgorithm()), EncryptionMethod.parse(encryptionConfiguration.getEncryptionMethod()), encryptionConfiguration.getHmcKeySetLocation(), encryptionConfiguration.getHwKeySetLocation(), encryptionConfiguration.getExpirationMinutes()); //@formatter:on } }
5,532
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet/configuration/HyperwalletEncryptionConfiguration.java
package com.paypal.infrastructure.hyperwallet.configuration; import lombok.Getter; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Getter @Component public class HyperwalletEncryptionConfiguration { @Value("#{'${hmc.hyperwallet.encryption.encryptionEnabled}'}") protected boolean enabled; @Value("#{'${hmc.hyperwallet.encryption.encryptionAlgorithm}'}") protected String encryptionAlgorithm; @Value("#{'${hmc.hyperwallet.encryption.signAlgorithm}'}") protected String signAlgorithm; @Value("#{'${hmc.hyperwallet.encryption.encryptionMethod}'}") protected String encryptionMethod; @Value("#{'${hmc.hyperwallet.encryption.expirationMinutes}'}") protected Integer expirationMinutes; @Value("#{'${hmc.hyperwallet.encryption.hwKeySetLocation}'}") protected String hwKeySetLocation; @Value("#{'${hmc.hyperwallet.encryption.hmcKeySetLocation}'}") protected String hmcKeySetLocation; @Value("#{'${hmc.hyperwallet.encryption.hmcPublicKeyLocation}'}") protected String hmcPublicKeyLocation; }
5,533
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet/configuration/HyperwalletProgramsConfiguration.java
package com.paypal.infrastructure.hyperwallet.configuration; import com.paypal.infrastructure.support.exceptions.InvalidConfigurationException; import jakarta.annotation.PostConstruct; import lombok.AllArgsConstructor; import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; @Component public class HyperwalletProgramsConfiguration { @Value("#{'${hmc.hyperwallet.programs.names}'.split(',')}") private List<String> hyperwalletProgramsNames; @Value("#{'${hmc.hyperwallet.programs.ignored}'.split(',')}") private List<String> ignoredHyperwalletPrograms; @Value("#{'${hmc.hyperwallet.programs.userTokens}'.split(',')}") private List<String> hyperwalletUserProgramTokens; @Value("#{'${hmc.hyperwallet.programs.paymentTokens}'.split(',')}") private List<String> hyperwalletPaymentProgramTokens; @Value("#{'${hmc.hyperwallet.programs.bankAccountTokens}'.split(',')}") private List<String> hyperwalletBankAccountTokens; @Value("#{'${hmc.hyperwallet.programs.rootToken}'}") private String hyperwalletRootProgramToken; private Map<String, HyperwalletProgramConfiguration> programTokensMap = new HashMap<>(); public HyperwalletProgramConfiguration getProgramConfiguration(final String programName) { return programTokensMap.get(programName); } public List<HyperwalletProgramConfiguration> getAllProgramConfigurations() { return new ArrayList<>(programTokensMap.values()); } public String getRootProgramToken() { return !hyperwalletRootProgramToken.isBlank() ? hyperwalletRootProgramToken : hyperwalletUserProgramTokens.get(0); } public void setIgnoredHyperwalletPrograms(final List<String> ignoredPrograms) { ignoredHyperwalletPrograms = new ArrayList<>(ignoredPrograms); buildProgramTokensMap(); } public List<String> getIgnoredHyperwalletPrograms() { return ignoredHyperwalletPrograms; } public List<String> getHyperwalletProgramsNames() { return hyperwalletProgramsNames; } @PostConstruct private void initializeConfiguration() { cleanConfigurationVariables(); buildProgramTokensMap(); } private void buildProgramTokensMap() { //@formatter:off try { programTokensMap = IntStream.range(0, hyperwalletProgramsNames.size()) .mapToObj(i -> new HyperwalletProgramConfiguration(hyperwalletProgramsNames.get(i), ignoredHyperwalletPrograms.contains(hyperwalletProgramsNames.get(i)), hyperwalletUserProgramTokens.get(i), hyperwalletPaymentProgramTokens.get(i), hyperwalletBankAccountTokens.get(i))) .collect(Collectors.toMap(HyperwalletProgramConfiguration::getProgramName, Function.identity())); } catch (final Exception e) { throw new InvalidConfigurationException("Property files configuration error. Check hyperwallet program tokens configuration.", e); } //@formatter:on } private void cleanConfigurationVariables() { ignoredHyperwalletPrograms = removeEmptyStringValues(ignoredHyperwalletPrograms); hyperwalletProgramsNames = removeEmptyStringValues(hyperwalletProgramsNames); } private List<String> removeEmptyStringValues(final List<String> ignoredHyperwalletPrograms) { return ignoredHyperwalletPrograms.stream().filter(program -> !program.equals("")).collect(Collectors.toList()); } @Data @AllArgsConstructor public static class HyperwalletProgramConfiguration { private String programName; private boolean ignored; private String usersProgramToken; private String paymentProgramToken; private String bankAccountToken; } }
5,534
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet/configuration/HyperwalletConnectionConfiguration.java
package com.paypal.infrastructure.hyperwallet.configuration; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Data @Component @ConfigurationProperties("hmc.hyperwallet.connection") public class HyperwalletConnectionConfiguration { protected String server; protected String username; protected String password; }
5,535
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet/constants/HyperWalletConstants.java
package com.paypal.infrastructure.hyperwallet.constants; /** * Holds HyperWallet constants */ public final class HyperWalletConstants { private HyperWalletConstants() { } public static final String HYPERWALLET_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss"; public static final String PAYMENT_OPERATOR_SUFFIX = "-operatorFee"; public static final String JWKSET_ERROR_FILENAME = "public_keys_error.json"; // Mirakl's API allows returning a maximum of 100 results per "page" in any API call // with pagination support public static final int MIRAKL_MAX_RESULTS_PER_PAGE = 100; }
5,536
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet/services/PaymentHyperwalletSDKService.java
package com.paypal.infrastructure.hyperwallet.services; /** * Service that provides the correct Hyperwallet instance according to Hyperwallet * hierarchy and based on the parameter received. To be used for payment operations. */ public interface PaymentHyperwalletSDKService extends HyperwalletSDKService { }
5,537
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet/services/PaymentHyperwalletSDKServiceImpl.java
package com.paypal.infrastructure.hyperwallet.services; import com.hyperwallet.clientsdk.util.HyperwalletEncryption; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletConnectionConfiguration; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletProgramsConfiguration; import org.springframework.lang.Nullable; import org.springframework.stereotype.Service; /** * Implementation of {@link PaymentHyperwalletSDKService} */ @Service public class PaymentHyperwalletSDKServiceImpl extends AbstractHyperwalletSDKService implements PaymentHyperwalletSDKService { public PaymentHyperwalletSDKServiceImpl(final HyperwalletProgramsConfiguration programsConfiguration, final HyperwalletConnectionConfiguration connectionConfiguration, @Nullable final HyperwalletEncryption encryption) { super(programsConfiguration, connectionConfiguration, encryption); } @Override protected String getProgramToken( final HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration programConfiguration) { return programConfiguration.getPaymentProgramToken(); } }
5,538
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet/services/HyperwalletSDKService.java
package com.paypal.infrastructure.hyperwallet.services; import com.hyperwallet.clientsdk.Hyperwallet; import com.hyperwallet.clientsdk.model.HyperwalletProgram; /** * Service that provides the correct Hyperwallet instance according to Hyperwallet * hierarchy and based on the parameter received */ public interface HyperwalletSDKService { /** * Return Hyperwallet instance based on the hyperwallet program received as parameter * @param hyperwalletProgram hyperwallet program * @return {@link Hyperwallet} object */ Hyperwallet getHyperwalletInstanceByHyperwalletProgram(String hyperwalletProgram); /** * Return Hyperwallet instance based on programToken received as parameter * @param programToken program token * @return {@link Hyperwallet} object */ Hyperwallet getHyperwalletInstanceByProgramToken(String programToken); /** * Return Hyperwallet instance without any associated program token * @return {@link Hyperwallet} object */ Hyperwallet getHyperwalletInstance(); HyperwalletProgram getRootProgram(); /** * Returns a {@link String} program token based on its hyperwallet program associated * @param hyperwalletProgram hyperwallet program * @return {@link String} */ String getProgramTokenByHyperwalletProgram(String hyperwalletProgram); }
5,539
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet/services/UserHyperwalletSDKServiceImpl.java
package com.paypal.infrastructure.hyperwallet.services; import com.hyperwallet.clientsdk.util.HyperwalletEncryption; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletConnectionConfiguration; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletProgramsConfiguration; import org.springframework.lang.Nullable; import org.springframework.stereotype.Service; @Service public class UserHyperwalletSDKServiceImpl extends AbstractHyperwalletSDKService implements UserHyperwalletSDKService { public UserHyperwalletSDKServiceImpl(final HyperwalletProgramsConfiguration programsConfiguration, final HyperwalletConnectionConfiguration connectionConfiguration, @Nullable final HyperwalletEncryption encryption) { super(programsConfiguration, connectionConfiguration, encryption); } protected String getProgramToken( final HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration programConfiguration) { return programConfiguration.getUsersProgramToken(); } }
5,540
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet/services/UserHyperwalletSDKService.java
package com.paypal.infrastructure.hyperwallet.services; /** * Service that provides the correct Hyperwallet instance according to Hyperwallet * hierarchy and based on the parameter received. To be used for user operations. */ public interface UserHyperwalletSDKService extends HyperwalletSDKService { }
5,541
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet/services/AbstractHyperwalletSDKService.java
package com.paypal.infrastructure.hyperwallet.services; import com.hyperwallet.clientsdk.Hyperwallet; import com.hyperwallet.clientsdk.model.HyperwalletProgram; import com.hyperwallet.clientsdk.util.HyperwalletEncryption; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletConnectionConfiguration; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletProgramsConfiguration; import org.springframework.lang.Nullable; public abstract class AbstractHyperwalletSDKService { protected final HyperwalletProgramsConfiguration programsConfiguration; protected final HyperwalletConnectionConfiguration connectionConfiguration; protected final HyperwalletEncryption encryption; protected AbstractHyperwalletSDKService(final HyperwalletProgramsConfiguration programsConfiguration, final HyperwalletConnectionConfiguration connectionConfiguration, @Nullable final HyperwalletEncryption encryption) { this.programsConfiguration = programsConfiguration; this.connectionConfiguration = connectionConfiguration; this.encryption = encryption; } public Hyperwallet getHyperwalletInstanceByHyperwalletProgram(final String hyperwalletProgram) { //@formatter:off final HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration programConfiguration = programsConfiguration.getProgramConfiguration(hyperwalletProgram); //@formatter:on return getHyperwalletInstanceByProgramToken(getProgramToken(programConfiguration)); } public Hyperwallet getHyperwalletInstanceByProgramToken(final String programToken) { return new Hyperwallet(connectionConfiguration.getUsername(), connectionConfiguration.getPassword(), programToken, connectionConfiguration.getServer(), encryption); } public Hyperwallet getHyperwalletInstance() { return new Hyperwallet(connectionConfiguration.getUsername(), connectionConfiguration.getPassword(), null, connectionConfiguration.getServer(), encryption); } public HyperwalletProgram getRootProgram() { final String rootProgramToken = programsConfiguration.getRootProgramToken(); return getHyperwalletInstanceByProgramToken(rootProgramToken).getProgram(rootProgramToken); } public String getProgramTokenByHyperwalletProgram(final String hyperwalletProgram) { return getProgramToken(programsConfiguration.getProgramConfiguration(hyperwalletProgram)); } protected abstract String getProgramToken( HyperwalletProgramsConfiguration.HyperwalletProgramConfiguration programConfiguration); }
5,542
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/hyperwallet/services/HyperwalletPaginationSupport.java
package com.paypal.infrastructure.hyperwallet.services; import com.fasterxml.jackson.core.type.TypeReference; import com.hyperwallet.clientsdk.Hyperwallet; import com.hyperwallet.clientsdk.model.*; import com.hyperwallet.clientsdk.util.HyperwalletApiClient; import org.springframework.lang.NonNull; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; //@formatter:off public class HyperwalletPaginationSupport { private final Hyperwallet hyperwallet; public HyperwalletPaginationSupport(final Hyperwallet hyperwallet) { this.hyperwallet = hyperwallet; } @NonNull public <T> List<T> get(final Supplier<HyperwalletList<T>> paginatedFunction) { HyperwalletList<T> page = paginatedFunction.get(); final List<T> result = new ArrayList<>(page.getData()); while (page.hasNextPage()) { final HyperwalletLink nextLink = page.getLinks().stream() .filter(x -> x.getParams().get("rel").equals("next")) .findFirst() .orElseThrow(() -> new IllegalStateException("Could not find next page link")); page = followLink(nextLink, page); result.addAll(page.getData()); } return result; } private <T> HyperwalletList<T> followLink(final HyperwalletLink link, final HyperwalletList<T> previousPage) { return getApiClient().get(link.getHref(), new HyperwalletListTypeReference<>(previousPage)); } @SuppressWarnings({"java:S3011", "java:S2259"}) protected HyperwalletApiClient getApiClient() { try { final Field field = ReflectionUtils.findField(Hyperwallet.class, "apiClient"); assert field != null; field.setAccessible(true); return (HyperwalletApiClient) field.get(hyperwallet); } catch (final Exception e) { throw new IllegalStateException("Could not get apiClient field from Hyperwallet instance", e); } } private static final class HyperwalletListTypeReference<T> extends TypeReference<HyperwalletList<T>> { private final HyperwalletList<T> reference; public HyperwalletListTypeReference(final HyperwalletList<T> reference) { this.reference = reference; } @Override public Type getType() { return new HyperwalletListParametrizedType(reference); } } private static final class HyperwalletListParametrizedType implements ParameterizedType { private final Type[] actualTypeArguments; private final Type rawType; public HyperwalletListParametrizedType(final HyperwalletList<?> reference) { this.actualTypeArguments = new Type[]{reference.getData().get(0).getClass()}; this.rawType = reference.getClass(); } @Override public Type[] getActualTypeArguments() { return actualTypeArguments; } @Override public Type getRawType() { return rawType; } @Override public Type getOwnerType() { return null; } } }
5,543
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/settings/MiraklClientSettings.java
package com.paypal.infrastructure.mirakl.settings; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class MiraklClientSettings { private boolean stageChanges = false; }
5,544
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/settings/MiraklClientSettingsHolder.java
package com.paypal.infrastructure.mirakl.settings; public final class MiraklClientSettingsHolder { private MiraklClientSettingsHolder() { // private constructor } public static final MiraklClientSettings DEFAULT_SETTINGS = new MiraklClientSettings(); private static final ThreadLocal<MiraklClientSettings> miraklClientSettingsThreadLocal = ThreadLocal .withInitial(() -> DEFAULT_SETTINGS); public static void setMiraklClientSettings(final MiraklClientSettings settings) { miraklClientSettingsThreadLocal.set(settings); } public static MiraklClientSettings getMiraklClientSettings() { return miraklClientSettingsThreadLocal.get(); } public static void clear() { miraklClientSettingsThreadLocal.remove(); } }
5,545
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/settings/MiraklClientSettingsExecutor.java
package com.paypal.infrastructure.mirakl.settings; public final class MiraklClientSettingsExecutor { private MiraklClientSettingsExecutor() { // private constructor } public static void runWithSettings(final MiraklClientSettings settings, final Runnable runnable) { MiraklClientSettingsHolder.setMiraklClientSettings(settings); try { runnable.run(); } finally { MiraklClientSettingsHolder.clear(); } } }
5,546
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/configuration/MiraklApiClientConfig.java
package com.paypal.infrastructure.mirakl.configuration; import lombok.Data; import lombok.EqualsAndHashCode; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; @Data @EqualsAndHashCode @Configuration @ConfigurationProperties(prefix = "hmc.mirakl.connection") public class MiraklApiClientConfig { private String operatorApiKey; private String environment; }
5,547
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/support/MiraklShopUtils.java
package com.paypal.infrastructure.mirakl.support; import com.mirakl.client.mmp.domain.common.MiraklAdditionalFieldValue; import com.mirakl.client.mmp.domain.shop.MiraklShop; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.Optional; public final class MiraklShopUtils { public static final String HYPERWALLET_BANK_ACCOUNT_TOKEN = "hw-bankaccount-token"; public static final String HYPERWALLET_PROGRAM = "hw-program"; private MiraklShopUtils() { // private constructor } public static Optional<String> getProgram(final MiraklShop miraklShop) { return getMiraklSingleValueListCustomFieldValue(miraklShop, HYPERWALLET_PROGRAM); } public static void setProgram(final MiraklShop miraklShop, final String program) { setMiraklSingleValueListCustomFieldValue(miraklShop, HYPERWALLET_PROGRAM, program); } public static Optional<String> getBankAccountToken(final MiraklShop miraklShop) { return getMiraklStringCustomFieldValue(miraklShop, HYPERWALLET_BANK_ACCOUNT_TOKEN); } public static void setBankAccountToken(final MiraklShop miraklShop, final String bankAccountToken) { setMiraklStringCustomFieldValue(miraklShop, HYPERWALLET_BANK_ACCOUNT_TOKEN, bankAccountToken); } public static void setMiraklSingleValueListCustomFieldValue(final MiraklShop miraklShop, final String code, final String value) { final Optional<MiraklAdditionalFieldValue.MiraklValueListAdditionalFieldValue> existingFieldValue = getMiraklSingleValueListCustomField( miraklShop, code); existingFieldValue.ifPresentOrElse(f -> f.setValue(value), () -> addMiraklSingleValueListCustomFieldValue(miraklShop, code, value)); } public static void setMiraklStringCustomFieldValue(final MiraklShop miraklShop, final String code, final String value) { final Optional<MiraklAdditionalFieldValue.MiraklStringAdditionalFieldValue> existingFieldValue = getMiraklStringCustomField( miraklShop, code); existingFieldValue.ifPresentOrElse(f -> f.setValue(value), () -> addMiraklStringCustomFieldValue(miraklShop, code, value)); } private static void addMiraklSingleValueListCustomFieldValue(final MiraklShop miraklShop, final String code, final String value) { final MiraklAdditionalFieldValue.MiraklValueListAdditionalFieldValue newFieldValue = new MiraklAdditionalFieldValue.MiraklValueListAdditionalFieldValue(); newFieldValue.setCode(code); newFieldValue.setValue(value); addField(miraklShop, newFieldValue); } private static void addMiraklStringCustomFieldValue(final MiraklShop miraklShop, final String code, final String value) { final MiraklAdditionalFieldValue.MiraklStringAdditionalFieldValue newFieldValue = new MiraklAdditionalFieldValue.MiraklStringAdditionalFieldValue(); newFieldValue.setCode(code); newFieldValue.setValue(value); addField(miraklShop, newFieldValue); } private static void addField(final MiraklShop miraklShop, final MiraklAdditionalFieldValue newFieldValue) { final List<MiraklAdditionalFieldValue> additionalFieldValues = miraklShop.getAdditionalFieldValues(); final List<MiraklAdditionalFieldValue> newAdditionalFieldValues = new ArrayList<>( additionalFieldValues != null ? additionalFieldValues : List.of()); newAdditionalFieldValues.add(newFieldValue); miraklShop.setAdditionalFieldValues(newAdditionalFieldValues); } public static Optional<MiraklAdditionalFieldValue.MiraklStringAdditionalFieldValue> getMiraklStringCustomField( final @NotNull MiraklShop shop, final String customFieldCode) { return shop.getAdditionalFieldValues() != null ? getMiraklStringCustomField(shop.getAdditionalFieldValues(), customFieldCode) : Optional.empty(); } public static Optional<MiraklAdditionalFieldValue.MiraklValueListAdditionalFieldValue> getMiraklSingleValueListCustomField( final @NotNull MiraklShop shop, final String customFieldCode) { return shop.getAdditionalFieldValues() != null ? getMiraklSingleValueListCustomField(shop.getAdditionalFieldValues(), customFieldCode) : Optional.empty(); } public static Optional<String> getMiraklStringCustomFieldValue(final @NotNull MiraklShop shop, final String customFieldCode) { return shop.getAdditionalFieldValues() != null ? getMiraklStringCustomFieldValue(shop.getAdditionalFieldValues(), customFieldCode) : Optional.empty(); } public static Optional<String> getMiraklSingleValueListCustomFieldValue(final @NotNull MiraklShop shop, final String customFieldCode) { return shop.getAdditionalFieldValues() != null ? getMiraklSingleValueListCustomFieldValue(shop.getAdditionalFieldValues(), customFieldCode) : Optional.empty(); } private static Optional<String> getMiraklStringCustomFieldValue(final List<MiraklAdditionalFieldValue> fields, final String customFieldCode) { //@formatter:off return getMiraklStringCustomField(fields, customFieldCode) .map(MiraklAdditionalFieldValue.MiraklAbstractAdditionalFieldWithSingleValue::getValue); //@formatter:on } private static Optional<MiraklAdditionalFieldValue.MiraklStringAdditionalFieldValue> getMiraklStringCustomField( final List<MiraklAdditionalFieldValue> fields, final String customFieldCode) { //@formatter:off return fields.stream().filter(field -> field.getCode().equals(customFieldCode)) .filter(MiraklAdditionalFieldValue.MiraklStringAdditionalFieldValue.class::isInstance) .map(MiraklAdditionalFieldValue.MiraklStringAdditionalFieldValue.class::cast) .findAny(); //@formatter:on } private static Optional<String> getMiraklSingleValueListCustomFieldValue( final List<MiraklAdditionalFieldValue> fields, final String customFieldCode) { //@formatter:off return getMiraklSingleValueListCustomField(fields, customFieldCode) .map(MiraklAdditionalFieldValue.MiraklAbstractAdditionalFieldWithSingleValue::getValue); //@formatter:on } private static Optional<MiraklAdditionalFieldValue.MiraklValueListAdditionalFieldValue> getMiraklSingleValueListCustomField( final List<MiraklAdditionalFieldValue> fields, final String customFieldCode) { //@formatter:off return fields.stream() .filter(field -> field.getCode().equals(customFieldCode)) .filter(MiraklAdditionalFieldValue.MiraklValueListAdditionalFieldValue.class::isInstance) .map(MiraklAdditionalFieldValue.MiraklValueListAdditionalFieldValue.class::cast) .findAny(); //@formatter:on } }
5,548
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/controllers/ChangeIgnoredProgramsController.java
package com.paypal.infrastructure.mirakl.controllers; import com.paypal.infrastructure.mirakl.controllers.dto.IgnoredProgramsDTO; import com.paypal.infrastructure.mirakl.services.IgnoreProgramsService; import jakarta.annotation.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/configuration/programs") public class ChangeIgnoredProgramsController { @Resource private IgnoreProgramsService ignoreProgramsService; @PutMapping("/ignored") public ResponseEntity<String> ignore(@RequestBody final IgnoredProgramsDTO programs) { ignoreProgramsService.ignorePrograms(programs.getIgnoredPrograms()); return ResponseEntity.ok().build(); } @GetMapping("/ignored") public ResponseEntity<Object> get() { return new ResponseEntity<>(ignoreProgramsService.getIgnoredPrograms(), HttpStatus.OK); } }
5,549
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/controllers
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/controllers/dto/IgnoredProgramsDTO.java
package com.paypal.infrastructure.mirakl.controllers.dto; import lombok.Data; import java.util.List; @Data public class IgnoredProgramsDTO { List<String> ignoredPrograms; }
5,550
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/client/DirectMiraklClient.java
package com.paypal.infrastructure.mirakl.client; import com.mirakl.client.core.security.MiraklCredential; 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.invoice.MiraklConfirmAccountingDocumentPaymentRequest; 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.springframework.stereotype.Component; import java.util.List; @Component public class DirectMiraklClient implements MiraklClient { private MiraklMarketplacePlatformOperatorApiClient miraklMarketplacePlatformOperatorApiClient; private final IgnoredShopsFilter ignoredShopsFilter; private final MiraklApiClientConfig config; public DirectMiraklClient(final MiraklApiClientConfig config, final IgnoredShopsFilter ignoredShopsFilter) { this.config = config; this.ignoredShopsFilter = ignoredShopsFilter; reloadHttpConfiguration(); } @Override public MiraklVersion getVersion() { return miraklMarketplacePlatformOperatorApiClient.getVersion(); } @Override public MiraklShops getShops(final MiraklGetShopsRequest request) { final MiraklShops shops = getUnfilteredMiraklShops(request); return ignoredShopsFilter.filterIgnoredShops(shops); } @Override public MiraklUpdatedShops updateShops(final MiraklUpdateShopsRequest miraklUpdateShopsRequest) { return miraklMarketplacePlatformOperatorApiClient.updateShops(miraklUpdateShopsRequest); } @Override public List<MiraklFrontOperatorAdditionalField> getAdditionalFields( final MiraklGetAdditionalFieldRequest miraklGetAdditionalFieldRequest) { return miraklMarketplacePlatformOperatorApiClient.getAdditionalFields(miraklGetAdditionalFieldRequest); } @Override public MiraklInvoices getInvoices(final MiraklGetInvoicesRequest accountingDocumentRequest) { return miraklMarketplacePlatformOperatorApiClient.getInvoices(accountingDocumentRequest); } @SuppressWarnings("java:S1874") @Override public MiraklTransactionLogs getTransactionLogs( final MiraklGetTransactionLogsRequest miraklGetTransactionLogsRequest) { return miraklMarketplacePlatformOperatorApiClient.getTransactionLogs(miraklGetTransactionLogsRequest); } @Override public MiraklDocumentsConfigurations getDocumentsConfiguration( final MiraklGetDocumentsConfigurationRequest miraklGetDocumentsConfigurationRequest) { return miraklMarketplacePlatformOperatorApiClient .getDocumentsConfiguration(miraklGetDocumentsConfigurationRequest); } @Override public List<MiraklShopDocument> getShopDocuments( final MiraklGetShopDocumentsRequest getShopBusinessStakeholderDocumentsRequest) { return miraklMarketplacePlatformOperatorApiClient.getShopDocuments(getShopBusinessStakeholderDocumentsRequest); } @Override public FileWrapper downloadShopsDocuments( final MiraklDownloadShopsDocumentsRequest miraklDownloadShopsDocumentsRequest) { return miraklMarketplacePlatformOperatorApiClient.downloadShopsDocuments(miraklDownloadShopsDocumentsRequest); } @Override public void deleteShopDocument(final MiraklDeleteShopDocumentRequest miraklDeleteShopDocumentRequest) { miraklMarketplacePlatformOperatorApiClient.deleteShopDocument(miraklDeleteShopDocumentRequest); } @Override public void confirmAccountingDocumentPayment( final MiraklConfirmAccountingDocumentPaymentRequest paymentConfirmationRequest) { miraklMarketplacePlatformOperatorApiClient.confirmAccountingDocumentPayment(paymentConfirmationRequest); } @Override public void reloadHttpConfiguration() { this.miraklMarketplacePlatformOperatorApiClient = new MiraklMarketplacePlatformOperatorApiClient( config.getEnvironment(), new MiraklCredential(config.getOperatorApiKey())); } protected MiraklShops getUnfilteredMiraklShops(final MiraklGetShopsRequest request) { return miraklMarketplacePlatformOperatorApiClient.getShops(request); } }
5,551
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/client/MiraklClient.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.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.invoice.MiraklConfirmAccountingDocumentPaymentRequest; 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 java.util.List; public interface MiraklClient { MiraklVersion getVersion(); MiraklShops getShops(MiraklGetShopsRequest request); MiraklUpdatedShops updateShops(MiraklUpdateShopsRequest miraklUpdateShopsRequest); List<MiraklFrontOperatorAdditionalField> getAdditionalFields( MiraklGetAdditionalFieldRequest miraklGetAdditionalFieldRequest); MiraklInvoices getInvoices(MiraklGetInvoicesRequest accountingDocumentRequest); @SuppressWarnings("java:S1874") MiraklTransactionLogs getTransactionLogs(MiraklGetTransactionLogsRequest miraklGetTransactionLogsRequest); MiraklDocumentsConfigurations getDocumentsConfiguration( MiraklGetDocumentsConfigurationRequest miraklGetDocumentsConfigurationRequest); List<MiraklShopDocument> getShopDocuments(MiraklGetShopDocumentsRequest getShopBusinessStakeholderDocumentsRequest); FileWrapper downloadShopsDocuments(MiraklDownloadShopsDocumentsRequest miraklDownloadShopsDocumentsRequest); void deleteShopDocument(MiraklDeleteShopDocumentRequest miraklDeleteShopDocumentRequest); void confirmAccountingDocumentPayment(MiraklConfirmAccountingDocumentPaymentRequest paymentConfirmationRequest); void reloadHttpConfiguration(); }
5,552
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/client/StageChangesMiraklClient.java
package com.paypal.infrastructure.mirakl.client; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdatedShops; import com.mirakl.client.mmp.operator.request.shop.MiraklUpdateShopsRequest; 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.MiraklClientSettingsHolder; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; import java.util.List; @Primary @Component public class StageChangesMiraklClient extends DirectMiraklClient { private final ChangeStagingService changeStagingService; private final MiraklStageChangeConverter miraklStageChangeConverter; public StageChangesMiraklClient(final MiraklApiClientConfig config, final IgnoredShopsFilter ignoredShopsFilter, final ChangeStagingService changeStagingService, final MiraklStageChangeConverter miraklStageChangeConverter) { super(config, ignoredShopsFilter); this.changeStagingService = changeStagingService; this.miraklStageChangeConverter = miraklStageChangeConverter; } @Override public MiraklUpdatedShops updateShops(final MiraklUpdateShopsRequest miraklUpdateShopsRequest) { if (MiraklClientSettingsHolder.getMiraklClientSettings().isStageChanges()) { changeStagingService.stageChanges(miraklStageChangeConverter.from(miraklUpdateShopsRequest.getShops())); // This updates will be made asynchronously in other thread after batching // some changes, so we return an empty response. // If the return response is needed, staging can't be used. final MiraklUpdatedShops miraklUpdatedShops = new MiraklUpdatedShops(); miraklUpdatedShops.setShopReturns(List.of()); return miraklUpdatedShops; } else { return callSuperGetMiraklUpdatedShops(miraklUpdateShopsRequest); } } // For testing purposes protected MiraklUpdatedShops callSuperGetMiraklUpdatedShops( final MiraklUpdateShopsRequest miraklUpdateShopsRequest) { return super.updateShops(miraklUpdateShopsRequest); } }
5,553
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/client
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/client/changestaging/MiraklUpdateShopStagedChangesExecutor.java
package com.paypal.infrastructure.mirakl.client.changestaging; import com.mirakl.client.core.internal.util.Patch; 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.StagedChangesExecutor; import com.paypal.infrastructure.changestaging.service.operations.StagedChangesExecutorInfo; import com.paypal.infrastructure.mirakl.client.MiraklClient; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.commons.beanutils.PropertyUtils; import org.reflections.ReflectionUtils; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import static java.util.function.Predicate.not; import static org.reflections.ReflectionUtils.withName; //@formatter:off @Slf4j @Component public class MiraklUpdateShopStagedChangesExecutor implements StagedChangesExecutor { private final MiraklClient miraklClient; public MiraklUpdateShopStagedChangesExecutor(@Qualifier("directMiraklClient") final MiraklClient miraklClient) { this.miraklClient = miraklClient; } @Override public void execute(final List<StagedChange> changes) { changes.sort(Comparator.comparing(this::getShopId) .thenComparing(StagedChange::getCreationDate)); final List<MiraklUpdateShop> updateShops = changes.stream() .map(StagedChange::getPayload) .map(MiraklUpdateShop.class::cast) .toList(); final List<MiraklUpdateShop> compactedShops = compactShops(regroupShops(updateShops)); log.info("Updating {} shops with ids {}", compactedShops.size(), compactedShops.stream() .map(MiraklUpdateShop::getShopId) .toList()); miraklClient.updateShops(new MiraklUpdateShopsRequest(compactedShops)); } private Long getShopId(final StagedChange stagedChange) { return ((MiraklUpdateShop) stagedChange.getPayload()).getShopId(); } @Override public StagedChangesExecutorInfo getExecutorInfo() { final StagedChangesExecutorInfo stagedChangesExecutorInfo = new StagedChangesExecutorInfo(); stagedChangesExecutorInfo.setOperation(ChangeOperation.UPDATE); stagedChangesExecutorInfo.setTarget(ChangeTarget.MIRAKL); stagedChangesExecutorInfo.setType(MiraklUpdateShop.class); return stagedChangesExecutorInfo; } private List<MiraklUpdateShop> compactShops(final List<List<MiraklUpdateShop>> shops) { return shops.stream().map(this::compactShopChanges).toList(); } private MiraklUpdateShop compactShopChanges(final List<MiraklUpdateShop> shopChanges) { return shopChanges.stream().reduce(new MiraklUpdateShop(), this::compactShop); } private MiraklUpdateShop compactShop(final MiraklUpdateShop miraklUpdateShop1, final MiraklUpdateShop miraklUpdateShop2) { copyAllValues(miraklUpdateShop2, miraklUpdateShop1); copyAllPatches(miraklUpdateShop2, miraklUpdateShop1); return miraklUpdateShop1; } private List<List<MiraklUpdateShop>> regroupShops(final List<MiraklUpdateShop> shops) { return shops.stream().collect(Collectors .groupingBy(MiraklUpdateShop::getShopId)) .values() .stream().toList(); } private void copyAllValues(final MiraklUpdateShop source, final MiraklUpdateShop target) { Arrays.stream(PropertyUtils.getPropertyDescriptors(MiraklUpdateShop.class)) .filter(d -> !d.getName().contains("Patch")) .filter(not(this::hasPatchType)) .forEach(d -> copyAsValue(source, target, d.getName())); } private void copyAllPatches(final MiraklUpdateShop source, final MiraklUpdateShop target) { Arrays.stream(PropertyUtils.getPropertyDescriptors(MiraklUpdateShop.class)) .filter(this::hasPatchType) .forEach(d -> copyAsPatch(source, target, d.getName())); } @SuppressWarnings("unchecked") private boolean hasPatchType(final PropertyDescriptor property) { return !ReflectionUtils.getAllFields(MiraklUpdateShop.class, f -> f.getName().contains(property.getName()), f -> f.getType().isAssignableFrom(Patch.class)) .isEmpty(); } @SneakyThrows private void copyAsValue(final MiraklUpdateShop source, final MiraklUpdateShop target, final String fieldName) { final Object sourceValue = PropertyUtils.getProperty(source, fieldName); if (sourceValue != null) { PropertyUtils.setProperty(target, fieldName, sourceValue); } } @SuppressWarnings("java:S3011") @SneakyThrows private void copyAsPatch(final MiraklUpdateShop source, final MiraklUpdateShop target, final String fieldName) { final List<Field> patchObjectFields = new ArrayList<>(ReflectionUtils.getAllFields(MiraklUpdateShop.class, withName(fieldName))); patchObjectFields.sort(Comparator.comparing(Field::getDeclaringClass, MiraklUpdateShopStagedChangesExecutor::compareClassesByHierarchy)); final Field patchObjectField = patchObjectFields.get(0); patchObjectField.setAccessible(true); final Patch<?> patchObject = (Patch<?>) patchObjectField.get(source); if (patchObject != null && patchObject.isPresent()) { copyAsValue(source, target, fieldName); } patchObjectField.setAccessible(false); } private static int compareClassesByHierarchy(final Class<?> c1, final Class<?> c2) { if (c1.isAssignableFrom(c2)) { return 1; } else if (c2.isAssignableFrom(c1)) { return -1; } return 0; } }
5,554
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/client
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/client/converters/MiraklStageChangeConverter.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.mapstruct.Mapper; import java.util.List; @Mapper(componentModel = "spring") public interface MiraklStageChangeConverter { default Change from(final MiraklUpdateShop source) { final Change change = new Change(); change.setType(MiraklUpdateShop.class); change.setPayload(source); change.setOperation(ChangeOperation.UPDATE); change.setTarget(ChangeTarget.MIRAKL); return change; } List<Change> from(List<MiraklUpdateShop> source); }
5,555
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/client
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/client/filter/IgnoredShopsFilter.java
package com.paypal.infrastructure.mirakl.client.filter; 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.support.MiraklShopUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; @Slf4j @Component public class IgnoredShopsFilter { private final HyperwalletProgramsConfiguration hyperwalletProgramsConfiguration; public IgnoredShopsFilter(final HyperwalletProgramsConfiguration hyperwalletProgramsConfiguration) { this.hyperwalletProgramsConfiguration = hyperwalletProgramsConfiguration; } public MiraklShops filterIgnoredShops(final MiraklShops shops) { final List<MiraklShop> validShops = shops.getShops().stream().filter(Predicate.not(this::isIgnored)) .collect(Collectors.toList()); shops.setShops(validShops); shops.setTotalCount((long) validShops.size()); return shops; } private boolean isIgnored(final MiraklShop miraklShop) { final Optional<String> program = MiraklShopUtils.getProgram(miraklShop); if (program.isPresent()) { final String programValue = program.get(); final boolean isIgnored = hyperwalletProgramsConfiguration.getProgramConfiguration(programValue) .isIgnored(); if (isIgnored) { log.info("Shop with id [{}] contains program [{}] which is in the ignored list, skipping processing", miraklShop.getId(), programValue); } return isIgnored; } else { log.debug("Program not set for shop with id [{}]", miraklShop.getId()); return true; } } }
5,556
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/services/IgnoreProgramsServiceImpl.java
package com.paypal.infrastructure.mirakl.services; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletProgramsConfiguration; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.util.List; @Slf4j @Component public class IgnoreProgramsServiceImpl implements IgnoreProgramsService { @Resource private HyperwalletProgramsConfiguration userHyperwalletApiConfig; @Override public void ignorePrograms(final List<String> programs) { final List<String> ignoredPrograms = CollectionUtils.isEmpty(programs) ? List.of() : programs; userHyperwalletApiConfig.setIgnoredHyperwalletPrograms(ignoredPrograms); log.info("Setting ignored program to: {}", String.join(",", ignoredPrograms)); } @Override public List<String> getIgnoredPrograms() { return userHyperwalletApiConfig.getIgnoredHyperwalletPrograms(); } @Override public boolean isIgnored(final String program) { return !CollectionUtils.isEmpty(getIgnoredPrograms()) && getIgnoredPrograms().contains(program); } }
5,557
0
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl
Create_ds/mirakl-hyperwallet-connector/hmc-infrastructure/src/main/java/com/paypal/infrastructure/mirakl/services/IgnoreProgramsService.java
package com.paypal.infrastructure.mirakl.services; import java.util.List; public interface IgnoreProgramsService { void ignorePrograms(List<String> programs); List<String> getIgnoredPrograms(); boolean isIgnored(String program); }
5,558
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/ignoredprogramschecks/startup
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/ignoredprogramschecks/startup/converters/HmcIgnoredProgramsCheckConverterImplTest.java
package com.paypal.observability.ignoredprogramschecks.startup.converters; import com.paypal.observability.ignoredprogramschecks.model.HmcIgnoredProgramsCheck; import com.paypal.observability.startupchecks.model.StartupCheck; import com.paypal.observability.startupchecks.model.StartupCheckStatus; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; import java.util.List; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(MockitoExtension.class) class HmcIgnoredProgramsCheckConverterImplTest { @InjectMocks private HmcIgnoredProgramsCheckConverterImpl testObj; @Test void from_shouldConvertIgnoredProgramsCheckToStartUpCheckAndEnsureTheErrorMessageIsShownWhenIgnoredProgramsAreNotSubsetOfPrograms() { final HmcIgnoredProgramsCheck ignoredProgramsCheck = HmcIgnoredProgramsCheck.builder() .ignoredPrograms(List.of("PROGRAM1", "PROGRAM2")).programs(List.of("PROGRAM3", "PROGRAM4")) .isSubset(false).build(); final StartupCheck result = testObj.from(ignoredProgramsCheck); assertThat(result).hasFieldOrPropertyWithValue("status", StartupCheckStatus.READY_WITH_WARNINGS) .hasFieldOrPropertyWithValue("statusMessage", Optional.of("The [%s] list of ignored programs is not a subset of [%s] programs" .formatted("PROGRAM1,PROGRAM2", "PROGRAM3,PROGRAM4"))); } @Test void from_shouldConvertIgnoredProgramsCheckToStartUpCheckAndEnsureTheErrorMessageIsNotShownWhenIgnoredProgramsAreSubsetOfPrograms() { final HmcIgnoredProgramsCheck ignoredProgramsCheck = HmcIgnoredProgramsCheck.builder() .ignoredPrograms(List.of("PROGRAM1")).programs(List.of("PROGRAM1", "PROGRAM2")).isSubset(true).build(); final StartupCheck result = testObj.from(ignoredProgramsCheck); assertThat(result).hasFieldOrPropertyWithValue("status", StartupCheckStatus.READY) .hasFieldOrPropertyWithValue("statusMessage", Optional.empty()); } }
5,559
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/notificationslogging
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/notificationslogging/loggincontext/NotificationListenerLoggingContextAspectTest.java
package com.paypal.observability.notificationslogging.loggincontext; import com.hyperwallet.clientsdk.model.HyperwalletWebhookNotification; import com.paypal.notifications.events.model.HMCEvent; import org.aspectj.lang.ProceedingJoinPoint; 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 static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class NotificationListenerLoggingContextAspectTest { @Spy @InjectMocks private NotificationListenerLoggingContextAspect testObj; @Mock private ProceedingJoinPoint pjpMock; @Test void getNotificationObject_shouldReturnNotificationObjectWhenArgIsOfTypeHyperwalletNotification() { final HyperwalletWebhookNotification notification = new HyperwalletWebhookNotification(); final HMCEvent hmcEvent = new MyEvent(new Object(), notification); when(pjpMock.getArgs()).thenReturn(new Object[] { hmcEvent }); final HyperwalletWebhookNotification result = testObj.getNotificationObject(pjpMock); assertThat(result).isEqualTo(notification); } @Test void getNotificationObject_shouldReturnNullWhenArgumentIsNotOfTypeHyperwalletNotification() { final String notification = ""; when(pjpMock.getArgs()).thenReturn(new Object[] { notification }); final HyperwalletWebhookNotification result = testObj.getNotificationObject(pjpMock); assertThat(result).isNull(); } @Test void getNotificationObject_shouldReturnNullWhenArgumentIsNull() { when(pjpMock.getArgs()).thenReturn(new Object[] { null }); final HyperwalletWebhookNotification result = testObj.getNotificationObject(pjpMock); assertThat(result).isNull(); } private static class MyEvent extends HMCEvent { protected MyEvent(final Object source, final HyperwalletWebhookNotification notification) { super(source, notification); } } }
5,560
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/notificationslogging
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/notificationslogging/loggincontext/NotificationServiceLoggingContextAspectTest.java
package com.paypal.observability.notificationslogging.loggincontext; import com.hyperwallet.clientsdk.model.HyperwalletWebhookNotification; import org.aspectj.lang.ProceedingJoinPoint; 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 static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class NotificationServiceLoggingContextAspectTest { @Spy @InjectMocks private NotificationServiceLoggingContextAspect testObj; @Mock private ProceedingJoinPoint pjpMock; @Test void interceptNotificationMethod_shouldCallSuper() throws Throwable { doNothing().when(testObj).doInterceptNotificationMethod(pjpMock); testObj.interceptNotificationMethod(pjpMock); verify(testObj).doInterceptNotificationMethod(pjpMock); } @Test void getNotificationObject_shouldReturnNotificationObjectWhenArgIsOfTypeHyperwalletNotification() { final HyperwalletWebhookNotification notification = new HyperwalletWebhookNotification(); when(pjpMock.getArgs()).thenReturn(new Object[] { notification }); final HyperwalletWebhookNotification result = testObj.getNotificationObject(pjpMock); assertThat(result).isEqualTo(notification); } @Test void getNotificationObject_shouldReturnNullWhenArgumentIsNotOfTypeHyperwalletNotification() { final String notification = ""; when(pjpMock.getArgs()).thenReturn(new Object[] { notification }); final HyperwalletWebhookNotification result = testObj.getNotificationObject(pjpMock); assertThat(result).isNull(); } @Test void getNotificationObject_shouldReturnNullWhenArgumentIsNull() { when(pjpMock.getArgs()).thenReturn(new Object[] { null }); final HyperwalletWebhookNotification result = testObj.getNotificationObject(pjpMock); assertThat(result).isNull(); } }
5,561
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/notificationslogging
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/notificationslogging/loggincontext/AbstractNotificationLoggingContextAspectTest.java
package com.paypal.observability.notificationslogging.loggincontext; import com.hyperwallet.clientsdk.model.HyperwalletWebhookNotification; import com.paypal.observability.loggingcontext.service.LoggingContextService; import com.paypal.observability.notificationslogging.model.NotificationLoggingTransaction; import org.aspectj.lang.ProceedingJoinPoint; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.*; import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class AbstractNotificationLoggingContextAspectTest { @Spy @InjectMocks private MyNotificationLoggingContextAspect testObj; @Mock private ProceedingJoinPoint pjpMock; @Mock private LoggingContextService loggingContextServiceMock; @Captor private ArgumentCaptor<NotificationLoggingTransaction> argumentCaptorLoggingNotification; @Test void interceptNotificationEventListeners_shouldCallProceedWhenNotificationIsNullAndZeroInteractionsWithLoggingContextService() throws Throwable { when(testObj.getNotificationObject(pjpMock)).thenReturn(null); testObj.doInterceptNotificationMethod(pjpMock); verify(pjpMock).proceed(); verifyNoInteractions(loggingContextServiceMock); } @Test void interceptNotificationEventListeners_shouldAddContextualLoggingInformationBasedOnNotificationReceivedOngetNotificationObject() throws Throwable { testObj.doInterceptNotificationMethod(pjpMock); verify(loggingContextServiceMock).executeInLoggingContext(any(), argumentCaptorLoggingNotification.capture()); final NotificationLoggingTransaction notificationLoggingTransaction = argumentCaptorLoggingNotification .getValue(); assertThat(notificationLoggingTransaction.getId()).isEqualTo("token"); assertThat(notificationLoggingTransaction.getType()).isEqualTo("Notification"); assertThat(notificationLoggingTransaction.getSubtype()).isEqualTo("USER.PAYMENT.MOCKED"); assertThat(notificationLoggingTransaction.getTargetToken()).isEqualTo("target-token"); assertThat(notificationLoggingTransaction.getMiraklShopId()).isEqualTo("clientUserId"); assertThat(notificationLoggingTransaction.getClientPaymentId()).isEqualTo("clientPaymentId"); } public static class MyNotificationLoggingContextAspect extends AbstractNotificationLoggingContextAspect { protected MyNotificationLoggingContextAspect(final LoggingContextService loggingContextService) { super(loggingContextService); } @Override protected HyperwalletWebhookNotification getNotificationObject(final ProceedingJoinPoint pjp) { final HyperwalletWebhookNotification notification = new HyperwalletWebhookNotification(); notification.setToken("token"); notification.setType("USER.PAYMENT.MOCKED"); notification.setObject(new InnerNotificationObject("target-token", "clientUserId", "clientPaymentId")); return notification; } public class InnerNotificationObject { private final String token; private final String clientUserId; private final String clientPaymentId; public InnerNotificationObject(final String token, final String clientUserId, final String clientPaymentId) { this.token = token; this.clientUserId = clientUserId; this.clientPaymentId = clientPaymentId; } public String getToken() { return token; } public String getClientUserId() { return clientUserId; } public String getClientPaymentId() { return clientPaymentId; } } } }
5,562
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/miraklschemadiffs
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/miraklschemadiffs/startup/AbstractMiraklSchemaStartupCheckPrinterTest.java
package com.paypal.observability.miraklschemadiffs.startup; import com.paypal.observability.mirakldocschecks.startup.MiraklDocSchemaStartupCheckProvider; import com.paypal.observability.miraklschemadiffs.model.diff.MiraklSchemaDiffEntry; import com.paypal.observability.miraklschemadiffs.model.report.MiraklSchemaDiffReportEntry; import com.paypal.observability.miraklschemadiffs.model.report.MiraklSchemaDiffReportSeverity; import com.paypal.observability.startupchecks.model.StartupCheck; import com.paypal.observability.startupchecks.model.StartupCheckProvider; 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 java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class AbstractMiraklSchemaStartupCheckPrinterTest { @InjectMocks MyMiraklSchemaStartupCheckPrinter testObj; @Mock StartupCheck startupCheckMock; @Mock MiraklSchemaDiffReportEntry miraklSchemaDiffReportEntry1Mock, miraklSchemaDiffReportEntry2Mock; @Mock MiraklSchemaDiffEntry miraklSchemaDiffEntry1Mock, miraklSchemaDiffEntry2Mock; @Test void print_shouldReturnReportEntryMessageAndSeverity() { final Map<String, Object> detailsMap = Map.of(MiraklDocSchemaStartupCheckProvider.STATUS_CHECK_DETAILS_DIFF_KEY, List.of(miraklSchemaDiffReportEntry1Mock, miraklSchemaDiffReportEntry2Mock)); when(startupCheckMock.getDetails()).thenReturn(detailsMap); when(miraklSchemaDiffReportEntry1Mock.getDiff()).thenReturn(miraklSchemaDiffEntry1Mock); when(miraklSchemaDiffReportEntry1Mock.getSeverity()).thenReturn(MiraklSchemaDiffReportSeverity.FAIL); when(miraklSchemaDiffReportEntry2Mock.getDiff()).thenReturn(miraklSchemaDiffEntry2Mock); when(miraklSchemaDiffReportEntry2Mock.getSeverity()).thenReturn(MiraklSchemaDiffReportSeverity.WARN); when(miraklSchemaDiffEntry1Mock.getMessage()).thenReturn("MESSAGE-1"); when(miraklSchemaDiffEntry2Mock.getMessage()).thenReturn("MESSAGE-2"); final String[] result = testObj.print(startupCheckMock); assertThat(result).hasSize(2); assertThat(result[0]).isEqualTo("%s%n%s".formatted("MESSAGE-1", "Severity: BLOCKER")); assertThat(result[1]).isEqualTo("%s%n%s".formatted("MESSAGE-2", "Severity: RECOMMENDATION")); } static class MyMiraklSchemaStartupCheckPrinter extends AbstractMiraklSchemaStartupCheckPrinter { @Override public Class<? extends StartupCheckProvider> getAssociatedStartupCheck() { return null; } } }
5,563
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/trafficauditor
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/trafficauditor/adapters/AbstractTrafficAuditorAdapterTest.java
package com.paypal.observability.trafficauditor.adapters; import com.paypal.observability.trafficauditor.configuration.TrafficAuditorConfiguration; import com.paypal.observability.trafficauditor.model.TrafficAuditorRequest; import com.paypal.observability.trafficauditor.model.TrafficAuditorResponse; import com.paypal.observability.trafficauditor.model.TrafficAuditorTarget; import com.paypal.observability.trafficauditor.model.TrafficAuditorTrace; 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 java.util.HashMap; import java.util.List; import java.util.Map; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class AbstractTrafficAuditorAdapterTest { @InjectMocks private MyTrafficAuditorAdapter testObj; @Mock private TrafficAuditorConfiguration trafficAuditorConfigurationMock; @Mock private TrafficAuditorTraceHolder trafficAuditorTraceHolderMock; @Test void captureMethods_WhenTrafficAuditorDisabled_ShouldDoNothing() { // given when(trafficAuditorConfigurationMock.isTrafficAuditorEnabled()).thenReturn(false); // when testObj.startTraceCapture(mock(Object.class)); testObj.endTraceCapture(mock(Object.class)); testObj.endTraceCapture(mock(Throwable.class)); // then verify(trafficAuditorTraceHolderMock, never()).request(any()); verify(trafficAuditorTraceHolderMock, never()).response(any()); verify(trafficAuditorTraceHolderMock, never()).noResponse(); } @Test void captureMethods_WhenTrafficAuditorDisabled_ShouldDoTraceCapture() { // given when(trafficAuditorConfigurationMock.isTrafficAuditorEnabled()).thenReturn(true); final TrafficAuditorTrace trafficAuditorTrace = new TrafficAuditorTrace(); trafficAuditorTrace.setRequest(testObj.trafficAuditorRequest); when(trafficAuditorTraceHolderMock.currentTrace()).thenReturn(trafficAuditorTrace); // when testObj.startTraceCapture(testObj.trafficAuditorRequest); testObj.endTraceCapture(testObj.trafficAuditorResponse); // then verify(trafficAuditorTraceHolderMock, times(1)).request(any()); verify(trafficAuditorTraceHolderMock, times(1)).response(any()); } @Test void captureRequest_shouldIgnoreRequest_whenItsMultipart() { // given when(trafficAuditorConfigurationMock.isTrafficAuditorEnabled()).thenReturn(true); final TrafficAuditorTrace trafficAuditorTrace = new TrafficAuditorTrace(); trafficAuditorTrace.setRequest(testObj.trafficAuditorRequest); testObj.trafficAuditorResponse.getHeaders().put("Content-Type", List.of("multipart/form-data")); when(trafficAuditorTraceHolderMock.currentTrace()).thenReturn(trafficAuditorTrace); // when testObj.startTraceCapture(testObj.trafficAuditorRequest); testObj.endTraceCapture(testObj.trafficAuditorResponse); // then verify(trafficAuditorTraceHolderMock, times(1)).request(any()); verify(trafficAuditorTraceHolderMock, never()).response(any()); } @Test void captureResponse_shouldIgnoreResponse_whenItsMultipart() { // given when(trafficAuditorConfigurationMock.isTrafficAuditorEnabled()).thenReturn(true); testObj.trafficAuditorRequest.getHeaders().put("Content-Type", List.of("multipart/form-data")); // when testObj.startTraceCapture(testObj.trafficAuditorRequest); // then verify(trafficAuditorTraceHolderMock, never()).request(any()); } static class MyTrafficAuditorAdapter extends AbstractTrafficAuditorAdapter<Object, Object> { private static TrafficAuditorAdapter<?, ?> instance; final TrafficAuditorRequest trafficAuditorRequest; final TrafficAuditorResponse trafficAuditorResponse; protected MyTrafficAuditorAdapter(final TrafficAuditorConfiguration trafficAuditorConfiguration, final TrafficAuditorTraceHolder trafficAuditorTraceHolder) { super(trafficAuditorConfiguration, trafficAuditorTraceHolder); trafficAuditorRequest = buildRequest(); trafficAuditorResponse = buildResponse(); } @SuppressWarnings("unchecked") public static <T, R> TrafficAuditorAdapter<T, R> get() { return (TrafficAuditorAdapter<T, R>) instance; } @Override protected TrafficAuditorRequest doCaptureRequest(final Object request) { return trafficAuditorRequest; } @Override protected TrafficAuditorResponse doCaptureResponse(final Object response) { return trafficAuditorResponse; } @Override protected TrafficAuditorTarget getTarget() { return TrafficAuditorTarget.HMC; } TrafficAuditorRequest buildRequest() { final TrafficAuditorRequest request = new TrafficAuditorRequest(); request.setBody("REQUEST BODY"); request.setMethod("GET"); request.setUrl("http://localhost:8080/something"); request.setQueryParameters(Map.of("param1", "value1", "param2", "value2")); request.setHeaders(new HashMap<>(Map.of("header1", List.of("value1"), "header2", List.of("value2")))); return request; } TrafficAuditorResponse buildResponse() { final TrafficAuditorResponse response = new TrafficAuditorResponse(); response.setResponseCode(200); response.setBody("RESPONSE BODY"); response.setHeaders(new HashMap<>(Map.of("header1", List.of("value1"), "header2", List.of("value2")))); return response; } @SuppressWarnings("java:S2696") @Override public void afterPropertiesSet() { instance = this; } } }
5,564
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/trafficauditor/adapters
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/trafficauditor/adapters/support/HyperwalletBodyDecrypterTest.java
package com.paypal.observability.trafficauditor.adapters.support; import com.hyperwallet.clientsdk.util.HyperwalletEncryption; import com.nimbusds.jose.JOSEException; 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 java.io.IOException; import java.text.ParseException; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class HyperwalletBodyDecrypterTest { @InjectMocks private HyperwalletBodyDecrypter testObj; @Mock private HyperwalletEncryption hyperwalletEncryptionMock; @Test void decryptBodyIfNeeded_shouldReturnBody_ifBodyIsNull() { // given final String body = null; // when final String result = testObj.decryptBodyIfNeeded(body); // then assertThat(result).isNull(); } @Test void decryptBodyIfNeeded_shouldReturnBody_ifBodyIsBlank() { // given final String body = ""; // when final String result = testObj.decryptBodyIfNeeded(body); // then assertThat(result).isEmpty(); } @Test void decryptBodyIfNeeded_shouldReturnBody_ifHyperwalletEncryptionIsNull() { // given final String body = "body"; testObj = new HyperwalletBodyDecrypter(null); // when final String result = testObj.decryptBodyIfNeeded(body); // then assertThat(result).isEqualTo("body"); } @Test void decryptBodyIfNeeded_shouldReturnBody_ifBodyIsNotEncrypted() throws Exception { // given final String body = "body"; doThrow(RuntimeException.class).when(hyperwalletEncryptionMock).decrypt(body); // when final String result = testObj.decryptBodyIfNeeded(body); // then assertThat(result).isEqualTo("body"); } @Test void decryptBodyIfNeeded_shouldReturnDecryptedBody_ifBodyIsEncrypted() throws Exception { // given final String body = "ENCRYPTED"; testObj = new HyperwalletBodyDecrypter(hyperwalletEncryptionMock); when(hyperwalletEncryptionMock.decrypt("ENCRYPTED")).thenReturn("DECRYPTED"); // when final String result = testObj.decryptBodyIfNeeded(body); // then assertThat(result).isEqualTo("DECRYPTED"); } }
5,565
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/trafficauditor/adapters
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/trafficauditor/adapters/support/QueryParamExtractorTest.java
package com.paypal.observability.trafficauditor.adapters.support; 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.Map; import static org.assertj.core.api.Assertions.assertThat; class QueryParamExtractorTest { @Test void getQueryParametersFromUri_WhenUriHasNoQueryParams_ShouldReturnEmptyMap() { // given final String uri = "http://localhost:8080/health"; // when final Map<String, String> result = QueryParamExtractor.getQueryParametersFromUri(uri); // then assertThat(result).isEmpty(); } @Test void getQueryParametersFromUri_WhenUriHasQueryParams_ShouldReturnMapOfQueryParams() { // given final String uri = "http://localhost:8080/health?param1=value1&param2=value2"; // when final Map<String, String> result = QueryParamExtractor.getQueryParametersFromUri(uri); // then assertThat(result).containsOnlyKeys("param1", "param2").containsValues("value1", "value2"); } }
5,566
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/trafficauditor/adapters
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/trafficauditor/adapters/support/TrafficAuditorAdapterUtilsTest.java
package com.paypal.observability.trafficauditor.adapters.support; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; class TrafficAuditorAdapterUtilsTest { @Test void cleanMap_shouldRemoveNullKeys() { // given final Map<String, String> map = new HashMap<>(); map.put("key1", "value1"); map.put(null, "value2"); // when final Map<String, String> result = TrafficAuditorAdapterUtils.cleanMap(map); // then assertThat(result).containsOnlyKeys("key1").containsValues("value1"); } @Test void cleanMap_shouldObfuscateAuthorizationEntry_whenValueIsString_ignoringCase() { // given final Map<String, String> map = new HashMap<>(); map.put("AuthorIzatIon", "value1"); map.put(null, "value2"); // when final Map<String, String> result = TrafficAuditorAdapterUtils.cleanMap(map); // then assertThat(result).containsEntry("AuthorIzatIon", "********"); } @Test void cleanMap_shouldObfuscateAuthorizationEntry_whenValueIsListOfString_ignoringCase() { // given final Map<String, List<String>> map = new HashMap<>(); map.put("AuthorIzatIon", List.of("value1")); map.put(null, List.of("value2")); // when final Map<String, List<String>> result = TrafficAuditorAdapterUtils.cleanMap(map); // then assertThat(result.get("AuthorIzatIon").get(0)).isEqualTo("********"); } }
5,567
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/trafficauditor/adapters
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/trafficauditor/adapters/hyperwallet/HyperwalletTrafficAuditorAdapterTest.java
package com.paypal.observability.trafficauditor.adapters.hyperwallet; import com.hyperwallet.clientsdk.util.Request; import com.paypal.observability.trafficauditor.adapters.TrafficAuditorTraceHolder; import com.paypal.observability.trafficauditor.adapters.support.HyperwalletBodyDecrypter; import com.paypal.observability.trafficauditor.configuration.TrafficAuditorConfiguration; import com.paypal.observability.trafficauditor.model.TrafficAuditorRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class HyperwalletTrafficAuditorAdapterTest { private HyperwalletTrafficAuditorAdapter testObj; @Mock private TrafficAuditorConfiguration trafficAuditorConfigurationMock; @Mock private TrafficAuditorTraceHolder trafficAuditorTraceHolderMock; @Mock private HyperwalletBodyDecrypter hyperwalletBodyDecrypterMock; @Test void doCaptureRequest_shouldCallDecryptBody() { // given testObj = new HyperwalletTrafficAuditorAdapter(trafficAuditorConfigurationMock, trafficAuditorTraceHolderMock, hyperwalletBodyDecrypterMock); final Request request = new Request("https://test.com", 50000, 50000, null, null, null); request.setHeaders(Map.of("Content-Type", List.of("application/jose+json"))); request.setBody("ENCRYPTED"); when(hyperwalletBodyDecrypterMock.decryptBodyIfNeeded("ENCRYPTED")).thenReturn("DECRYPTED"); // when final TrafficAuditorRequest result = testObj.doCaptureRequest(request); // then verify(hyperwalletBodyDecrypterMock).decryptBodyIfNeeded("ENCRYPTED"); assertThat(result.getBody()).isEqualTo("DECRYPTED"); } }
5,568
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/miraklapichecks
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/miraklapichecks/actuator/MiraklAPIHealthCheckHealthIndicatorTest.java
package com.paypal.observability.miraklapichecks.actuator; import com.paypal.observability.miraklapichecks.actuator.converters.MiraklAPIHealthCheckActuatorConverter; import com.paypal.observability.miraklapichecks.model.MiraklAPICheck; import com.paypal.observability.miraklapichecks.services.MiraklHealthCheckService; 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.boot.actuate.health.Health; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class MiraklAPIHealthCheckHealthIndicatorTest { @InjectMocks private MiraklAPIHealthCheckHealthIndicator testObj; @Mock private MiraklHealthCheckService miraklHealthCheckServiceMock; @Mock private MiraklAPIHealthCheckActuatorConverter miraklAPIHealthCheckActuatorConverterMock; @Mock private Health healthMock; @Mock private MiraklAPICheck miraklAPICheckMock; @Test void health_ShouldCheckHealthStatus_WhenMiraklV01ReturnsAnything() { when(miraklHealthCheckServiceMock.check()).thenReturn(miraklAPICheckMock); when(miraklAPIHealthCheckActuatorConverterMock.from(miraklAPICheckMock)).thenReturn(healthMock); final Health result = testObj.health(); assertThat(result).isEqualTo(healthMock); } }
5,569
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/miraklapichecks/actuator
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/miraklapichecks/actuator/converters/MiraklAPIHealthCheckActuatorConverterImplTest.java
package com.paypal.observability.miraklapichecks.actuator.converters; import com.paypal.observability.miraklapichecks.model.MiraklAPICheck; import com.paypal.observability.miraklapichecks.model.MiraklAPICheckStatus; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.Status; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(MockitoExtension.class) class MiraklAPIHealthCheckActuatorConverterImplTest { @InjectMocks private MiraklAPIHealthCheckActuatorConverterImpl testObj; @Test void from_ShouldConvertServiceOkResultIntoHealtObject() { //@formatter:off final MiraklAPICheck miraklAPICheck = MiraklAPICheck.builder() .miraklAPICheckStatus(MiraklAPICheckStatus.UP) .version("1.0.0") .location("LOCATION") .build(); //@formatter:on final Health result = testObj.from(miraklAPICheck); assertThat(result.getStatus()).isEqualTo(Status.UP); assertThat(result.getDetails()).containsEntry("version", "1.0.0"); assertThat(result.getDetails()).containsEntry("location", "LOCATION"); } @Test void from_ShouldConvertServiceDownResultIntoHealtObject() { //@formatter:off final MiraklAPICheck miraklAPICheck = MiraklAPICheck.builder() .miraklAPICheckStatus(MiraklAPICheckStatus.DOWN) .error("ERROR") .location("LOCATION") .build(); //@formatter:on final Health result = testObj.from(miraklAPICheck); assertThat(result.getStatus()).isEqualTo(Status.DOWN); assertThat(result.getDetails()).containsEntry("error", "ERROR"); assertThat(result.getDetails()).containsEntry("location", "LOCATION"); } }
5,570
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/miraklapichecks
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/miraklapichecks/services/MiraklHealthCheckServiceImplTest.java
package com.paypal.observability.miraklapichecks.services; import com.mirakl.client.mmp.domain.version.MiraklVersion; import com.paypal.observability.miraklapichecks.connectors.MiraklAPIHealthCheckConnector; import com.paypal.observability.miraklapichecks.model.MiraklAPICheck; import com.paypal.observability.miraklapichecks.services.converters.MiraklAPIHealthCheckConnectorConverter; 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 MiraklHealthCheckServiceImplTest { @InjectMocks private MiraklHealthCheckServiceImpl testObj; @Mock private MiraklAPIHealthCheckConnector miraklAPIHealthCheckConnectorMock; @Mock private MiraklAPIHealthCheckConnectorConverter miraklAPIHealthCheckConnectorConverterMock; @Mock private MiraklVersion miraklVersionMock; @Mock private MiraklAPICheck miraklAPICheckMock; @Test void check_ShouldReturnAPICheck_FromResponse_WhenGetMiraklVersionsReturnsAnything() { when(miraklAPIHealthCheckConnectorMock.getVersion()).thenReturn(miraklVersionMock); when(miraklAPIHealthCheckConnectorConverterMock.from(miraklVersionMock)).thenReturn(miraklAPICheckMock); final MiraklAPICheck miraklAPICheck = testObj.check(); assertThat(miraklAPICheck).isEqualTo(miraklAPICheckMock); } @Test void check_ShouldReturnAPICheck_FromError_WhenGetMiraklVersionsReturnsAnything() { final Exception e = new RuntimeException(); when(miraklAPIHealthCheckConnectorMock.getVersion()).thenThrow(e); when(miraklAPIHealthCheckConnectorConverterMock.from(e)).thenReturn(miraklAPICheckMock); final MiraklAPICheck miraklAPICheck = testObj.check(); assertThat(miraklAPICheck).isEqualTo(miraklAPICheckMock); } }
5,571
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/loggingcontext/batchjobs
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/loggingcontext/batchjobs/model/BatchJobLoggingTransactionTest.java
package com.paypal.observability.loggingcontext.batchjobs.model; import com.fasterxml.jackson.databind.node.ObjectNode; import com.paypal.observability.batchjoblogging.model.BatchJobLoggingTransaction; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class BatchJobLoggingTransactionTest { private BatchJobLoggingTransaction testObj; @Test void toJson_shouldConvertToJson_whenAllFieldsAreFilled() { final BatchJobLoggingTransaction testObj = new BatchJobLoggingTransaction(); testObj.setItemId("ITEM_ID"); testObj.setId("ID"); testObj.setSubtype("SUBTYPE"); testObj.setItemType("ITEM_TYPE"); final ObjectNode result = testObj.toJson(); assertThat(result).isNotNull(); } @Test void toJson_shouldConvertToJson_whenNotAllFieldsAreFilled() { final BatchJobLoggingTransaction testObj = new BatchJobLoggingTransaction(); testObj.setId("ID"); final ObjectNode result = testObj.toJson(); assertThat(result).isNotNull(); } }
5,572
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/loggingcontext/batchjobs
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/loggingcontext/batchjobs/listeners/BatchJobLoggingListenerTest.java
package com.paypal.observability.loggingcontext.batchjobs.listeners; import com.callibrity.logging.test.LogTracker; import com.callibrity.logging.test.LogTrackerStub; import com.paypal.jobsystem.batchjob.model.BatchJobContext; import com.paypal.jobsystem.batchjob.model.BatchJobItem; import com.paypal.jobsystem.batchjob.model.BatchJobItemValidationResult; import com.paypal.observability.batchjoblogging.listeners.BatchJobLoggingListener; import com.paypal.observability.batchjoblogging.service.BatchJobLoggingContextService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collection; import java.util.Optional; import static org.apache.commons.lang3.ArrayUtils.EMPTY_THROWABLE_ARRAY; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class BatchJobLoggingListenerTest { public static final String JOB_NAME = "jobName"; public static final int NUMBER_OF_ITEMS_TO_BE_PROCESSED = 22; public static final String ITEM_TYPE = "itemType"; public static final String ITEM_ID = "itemId"; public static final int NUMBER_OF_ITEMS_PROCESSED = 20; public static final int NUMBER_OF_ITEMS_FAILED = 2; public static final int NUMBER_OF_ITEMS_REMAINING = 0; public static final int NUMBER_OF_ITEMS_FAILED_DURING_EXTRACTION = 5; @InjectMocks private BatchJobLoggingListener testObj; @Mock private BatchJobLoggingContextService batchJobLoggingContextServiceMock; @RegisterExtension final LogTrackerStub logTrackerStub = LogTrackerStub.create().recordForType(BatchJobLoggingListener.class); @Mock private BatchJobContext batchJobContextMock; @Mock private BatchJobItem<?> batchJobItemMock; @Mock private BatchJobItemValidationResult batchJobItemValidationResultMock; @Mock private Collection<BatchJobItem<?>> extractedItemsMock; @Mock private Exception exceptionMock; @BeforeEach public void setUp() { lenient().when(batchJobContextMock.getJobName()).thenReturn(JOB_NAME); lenient().when(batchJobContextMock.getNumberOfItemsToBeProcessed()).thenReturn(NUMBER_OF_ITEMS_TO_BE_PROCESSED); lenient().when(batchJobContextMock.getNumberOfItemsProcessed()).thenReturn(NUMBER_OF_ITEMS_PROCESSED); lenient().when(batchJobContextMock.getNumberOfItemsFailed()).thenReturn(NUMBER_OF_ITEMS_FAILED); lenient().when(batchJobContextMock.getNumberOfItemsRemaining()).thenReturn(NUMBER_OF_ITEMS_REMAINING); lenient().when(batchJobItemMock.getItemType()).thenReturn(ITEM_TYPE); lenient().when(batchJobItemMock.getItemId()).thenReturn(ITEM_ID); lenient().when(batchJobContextMock.isPartialItemExtraction()).thenReturn(false); } @Test void beforeItemExtraction_ShouldLogAnInfoMessage() { testObj.beforeItemExtraction(batchJobContextMock); assertThat(logTrackerStub.contains("Starting extraction of items to be processed")).isTrue(); } @Test void onItemExtractionSuccessful_ShouldLogAnInfoMessage_WhenExtractionIsNotPartial() { testObj.onItemExtractionSuccessful(batchJobContextMock, extractedItemsMock); assertThat(logTrackerStub.contains( "Retrieved the following number of items to be processed: " + NUMBER_OF_ITEMS_TO_BE_PROCESSED)) .isTrue(); } @Test void onItemExtractionSuccessful_ShouldLogWarnMessage_WhenExtractionIsPartial() { when(batchJobContextMock.isPartialItemExtraction()).thenReturn(true); testObj.onItemExtractionSuccessful(batchJobContextMock, extractedItemsMock); assertThat(logTrackerStub.contains("Some of the items to be processed couldn't be retrieved. " + "Only the following number of items were retrieved and are going to be processed " + NUMBER_OF_ITEMS_TO_BE_PROCESSED)).isTrue(); } @Test void onItemExtractionSuccessful_ShouldLogWarnMessage_WhenExtractionIsPartial_AndNumberOfFailedItemsIsKnown() { when(batchJobContextMock.isPartialItemExtraction()).thenReturn(true); when(batchJobContextMock.getNumberOfItemsNotSuccessfullyExtracted()) .thenReturn(Optional.of(NUMBER_OF_ITEMS_FAILED_DURING_EXTRACTION)); testObj.onItemExtractionSuccessful(batchJobContextMock, extractedItemsMock); assertThat(logTrackerStub.contains("Some of the items to be processed couldn't be retrieved. " + "Only the following number of items were retrieved and is going to be processed " + NUMBER_OF_ITEMS_TO_BE_PROCESSED)).isFalse(); assertThat(logTrackerStub .contains("Retrieved the following number of items to be processed: " + NUMBER_OF_ITEMS_TO_BE_PROCESSED + ". " + "Additionally there are " + NUMBER_OF_ITEMS_FAILED_DURING_EXTRACTION + " items that couldn't be retrieved and can't be processed")).isTrue(); } @Test void onItemExtractionFailure_ShouldLogAnErrorMessage() { when(exceptionMock.getSuppressed()).thenReturn(EMPTY_THROWABLE_ARRAY); logTrackerStub.recordForLevel(LogTracker.LogLevel.ERROR); testObj.onItemExtractionFailure(batchJobContextMock, exceptionMock); assertThat(logTrackerStub.contains("Failed retrieval of items")).isTrue(); } @Test void beforeProcessingItem_ShouldLogAnInfoMessage() { testObj.beforeProcessingItem(batchJobContextMock, batchJobItemMock); assertThat(logTrackerStub.contains("Processing item of type " + ITEM_TYPE + " with id: " + ITEM_ID)).isTrue(); } @Test void onItemProcessingFailure_ShouldLogAnInfoAndAnErrorMessage() { when(exceptionMock.getSuppressed()).thenReturn(EMPTY_THROWABLE_ARRAY); logTrackerStub.recordForLevel(LogTracker.LogLevel.ERROR).recordForLevel(LogTracker.LogLevel.INFO); testObj.onItemProcessingFailure(batchJobContextMock, batchJobItemMock, exceptionMock); assertThat(logTrackerStub.contains("Failed processing item of type " + ITEM_TYPE + " with id: " + ITEM_ID)) .isTrue(); assertThat(logTrackerStub.contains(NUMBER_OF_ITEMS_PROCESSED + " items processed successfully. " + NUMBER_OF_ITEMS_FAILED + " items failed. " + NUMBER_OF_ITEMS_REMAINING + " items remaining")) .isTrue(); } @Test void onItemProcessingFailure_ShouldLogAnInfoAnErrorAndWarnMessage_WhenExtractionWasPartial() { when(exceptionMock.getSuppressed()).thenReturn(EMPTY_THROWABLE_ARRAY); when(batchJobContextMock.isPartialItemExtraction()).thenReturn(true); logTrackerStub.recordForLevel(LogTracker.LogLevel.ERROR).recordForLevel(LogTracker.LogLevel.INFO); testObj.onItemProcessingFailure(batchJobContextMock, batchJobItemMock, exceptionMock); assertThat(logTrackerStub.contains("Failed processing item of type " + ITEM_TYPE + " with id: " + ITEM_ID)) .isTrue(); assertThat(logTrackerStub.contains(NUMBER_OF_ITEMS_PROCESSED + " items processed successfully. " + NUMBER_OF_ITEMS_FAILED + " items failed. " + NUMBER_OF_ITEMS_REMAINING + " items remaining")) .isTrue(); assertThat(logTrackerStub.contains("Not all items were able to be retrieved during the extraction phase," + " so there are additional items that couldn't be processed since they weren't retrieved.")).isTrue(); } @Test void onItemProcessingFailure_ShouldLogAnInfoAnErrorAndWarnMessage_WhenExtractionWasPartialAndFailedItemsAreKnown() { when(exceptionMock.getSuppressed()).thenReturn(EMPTY_THROWABLE_ARRAY); when(batchJobContextMock.isPartialItemExtraction()).thenReturn(true); when(batchJobContextMock.getNumberOfItemsNotSuccessfullyExtracted()) .thenReturn(Optional.of(NUMBER_OF_ITEMS_FAILED_DURING_EXTRACTION)); logTrackerStub.recordForLevel(LogTracker.LogLevel.ERROR).recordForLevel(LogTracker.LogLevel.INFO); testObj.onItemProcessingFailure(batchJobContextMock, batchJobItemMock, exceptionMock); assertThat(logTrackerStub.contains("Failed processing item of type " + ITEM_TYPE + " with id: " + ITEM_ID)) .isTrue(); assertThat(logTrackerStub.contains(NUMBER_OF_ITEMS_PROCESSED + " items processed successfully. " + NUMBER_OF_ITEMS_FAILED + " items failed. " + NUMBER_OF_ITEMS_REMAINING + " items remaining")) .isTrue(); assertThat(logTrackerStub.contains("Not all items were able to be retrieved during the extraction phase," + " so there are additional items that couldn't be processed since they weren't retrieved.")).isFalse(); assertThat(logTrackerStub.contains("Additionally there were " + NUMBER_OF_ITEMS_FAILED_DURING_EXTRACTION + " items that couldn't be retrieved during the extraction phase," + " so they were not processed.")) .isTrue(); } @Test void onItemProcessingSuccess_ShouldLogInfoMessages() { testObj.onItemProcessingSuccess(batchJobContextMock, batchJobItemMock); assertThat(logTrackerStub.contains("Processed successfully item of type " + ITEM_TYPE + " with id: " + ITEM_ID)) .isTrue(); assertThat(logTrackerStub.contains(NUMBER_OF_ITEMS_PROCESSED + " items processed successfully. " + NUMBER_OF_ITEMS_FAILED + " items failed. " + NUMBER_OF_ITEMS_REMAINING + " items remaining")) .isTrue(); } @Test void onItemProcessingSuccess_ShouldLogInfoMessagesAndWarnMessage_WhenExtractionWasPartialAndIsLastItem() { when(batchJobContextMock.isPartialItemExtraction()).thenReturn(true); when(batchJobContextMock.getNumberOfItemsRemaining()).thenReturn(1); testObj.onItemProcessingSuccess(batchJobContextMock, batchJobItemMock); assertThat(logTrackerStub.contains("Processed successfully item of type " + ITEM_TYPE + " with id: " + ITEM_ID)) .isTrue(); assertThat(logTrackerStub.contains(NUMBER_OF_ITEMS_PROCESSED + " items processed successfully. " + NUMBER_OF_ITEMS_FAILED + " items failed. " + 1 + " items remaining")).isTrue(); assertThat(logTrackerStub.contains("Not all items were able to be retrieved during the extraction phase," + " so there are additional items that couldn't be processed since they weren't retrieved.")).isFalse(); when(batchJobContextMock.getNumberOfItemsRemaining()).thenReturn(0); testObj.onItemProcessingSuccess(batchJobContextMock, batchJobItemMock); assertThat(logTrackerStub.contains("Processed successfully item of type " + ITEM_TYPE + " with id: " + ITEM_ID)) .isTrue(); assertThat(logTrackerStub.contains(NUMBER_OF_ITEMS_PROCESSED + " items processed successfully. " + NUMBER_OF_ITEMS_FAILED + " items failed. " + 0 + " items remaining")).isTrue(); assertThat(logTrackerStub.contains("Not all items were able to be retrieved during the extraction phase," + " so there are additional items that couldn't be processed since they weren't retrieved.")).isTrue(); } @Test void onItemProcessingSuccess_ShouldLogInfoMessagesAndWarnMessage_WhenExtractionWasPartialAndIsLastItemAndNumberOfFailedItemsIsKnown() { when(batchJobContextMock.isPartialItemExtraction()).thenReturn(true); when(batchJobContextMock.getNumberOfItemsRemaining()).thenReturn(1); when(batchJobContextMock.getNumberOfItemsNotSuccessfullyExtracted()) .thenReturn(Optional.of(NUMBER_OF_ITEMS_FAILED_DURING_EXTRACTION)); testObj.onItemProcessingSuccess(batchJobContextMock, batchJobItemMock); assertThat(logTrackerStub.contains("Processed successfully item of type " + ITEM_TYPE + " with id: " + ITEM_ID)) .isTrue(); assertThat(logTrackerStub.contains(NUMBER_OF_ITEMS_PROCESSED + " items processed successfully. " + NUMBER_OF_ITEMS_FAILED + " items failed. " + 1 + " items remaining")).isTrue(); assertThat(logTrackerStub.contains("Not all items were able to be retrieved during the extraction phase," + " so there are additional items that couldn't be processed since they weren't retrieved.")).isFalse(); when(batchJobContextMock.getNumberOfItemsRemaining()).thenReturn(0); testObj.onItemProcessingSuccess(batchJobContextMock, batchJobItemMock); assertThat(logTrackerStub.contains("Processed successfully item of type " + ITEM_TYPE + " with id: " + ITEM_ID)) .isTrue(); assertThat(logTrackerStub.contains(NUMBER_OF_ITEMS_PROCESSED + " items processed successfully. " + NUMBER_OF_ITEMS_FAILED + " items failed. " + 0 + " items remaining")).isTrue(); assertThat(logTrackerStub.contains("Not all items were able to be retrieved during the extraction phase," + " so there are additional items that couldn't be processed since they weren't retrieved.")).isFalse(); assertThat(logTrackerStub.contains("Additionally there were " + NUMBER_OF_ITEMS_FAILED_DURING_EXTRACTION + " items that couldn't be retrieved during the extraction phase," + " so they were not processed.")) .isTrue(); } @Test void onItemProcessingValidationFailure_ShouldLogWarnMessage() { testObj.onItemProcessingValidationFailure(batchJobContextMock, batchJobItemMock, batchJobItemValidationResultMock); assertThat(logTrackerStub .contains("Validation of item of type " + ITEM_TYPE + " with id: " + ITEM_ID + " has failed")).isTrue(); } }
5,573
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/loggingcontext
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/loggingcontext/service/LoggingContextServiceImplTest.java
package com.paypal.observability.loggingcontext.service; import com.paypal.observability.loggingcontext.model.LoggingTransaction; import com.paypal.observability.loggingcontext.service.serializer.LoggingTransactionSerializer; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.MDC; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class LoggingContextServiceImplTest { @InjectMocks private LoggingContextServiceImpl testObj; @Mock private LoggingContextHolder loggingContextHolderMock; @Mock private LoggingTransactionSerializer loggingTransactionSerializerMock; @Mock private LoggingTransaction businessTransactionMock; private static MockedStatic<MDC> mdcMockedStatic; @BeforeAll static void setUp() { mdcMockedStatic = Mockito.mockStatic(MDC.class); } @Test void getCurrentLoggingTransaction_shouldReturnGetCurrentBusinessTransactionResult() { when(loggingContextHolderMock.getCurrentBusinessTransaction()).thenReturn(Optional.of(businessTransactionMock)); final Optional<LoggingTransaction> result = testObj.getCurrentLoggingTransaction(); assertThat(result).isEqualTo(Optional.of(businessTransactionMock)); } @Test void updateLoggingTransaction_shouldCallRefreshBusinessTransactionAndPutTheTransactionIntoTheMDCAsString() { final String serializedBusinessTransaction = "{id:102230, subtype:jobName}"; when(loggingTransactionSerializerMock.serialize(businessTransactionMock)) .thenReturn(serializedBusinessTransaction); testObj.updateLoggingTransaction(businessTransactionMock); verify(loggingContextHolderMock).refreshBusinessTransaction(businessTransactionMock); mdcMockedStatic.verify(() -> MDC.put("businessTransaction", serializedBusinessTransaction)); } @Test void closeLoggingTransactionShouldCloseBusinessTransactionAndClearMDC() { testObj.closeLoggingTransaction(); verify(loggingContextHolderMock).closeBusinessTransaction(); mdcMockedStatic.verify(MDC::clear); } }
5,574
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/loggingcontext
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/loggingcontext/service/LoggingContextHolderTest.java
package com.paypal.observability.loggingcontext.service; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.paypal.observability.loggingcontext.model.LoggingTransaction; 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.junit.jupiter.MockitoExtension; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(MockitoExtension.class) class LoggingContextHolderTest { @InjectMocks private LoggingContextHolder testObj; @BeforeEach void setUp() { testObj = new LoggingContextHolder(); } @Test void getCurrentBusinessTransaction_shouldReturnAnOptionalEmptyWhenNoTransactionIsOpen() { final Optional<LoggingTransaction> result = testObj.getCurrentBusinessTransaction(); assertThat(result).isEmpty(); } @Test void getCurrentBusinessTransaction_shouldReturnAnOptionalNonEmptyWhenTransactionIsOpen() { testObj.refreshBusinessTransaction(new MyLoggingTransaction()); final Optional<LoggingTransaction> result = testObj.getCurrentBusinessTransaction(); assertThat(result).isNotEmpty(); } @Test void getCurrentBusinessTransaction_shouldEnsureTheBusinessTransactionIsSetInTheThreadLocal() { final ThreadLocal<LoggingTransaction> businessTransactionInfoHolder = testObj .getBusinessTransactionInfoHolder(); testObj.refreshBusinessTransaction(new MyLoggingTransaction()); assertThat(businessTransactionInfoHolder.get()).isInstanceOf(MyLoggingTransaction.class); } @Test void closeBusinessTransaction_shouldRemoveFromThreadLocalTheLoggingTransactionAlreadyOpened() { final ThreadLocal<LoggingTransaction> businessTransactionInfoHolder = testObj .getBusinessTransactionInfoHolder(); testObj.refreshBusinessTransaction(new MyLoggingTransaction()); testObj.closeBusinessTransaction(); assertThat(businessTransactionInfoHolder.get()).isNull(); } @Test void closeBusinessTransaction_shouldNotFailWhenClosingANonExistingBusinessTransaction() { final ThreadLocal<LoggingTransaction> businessTransactionInfoHolder = testObj .getBusinessTransactionInfoHolder(); testObj.closeBusinessTransaction(); assertThat(businessTransactionInfoHolder.get()).isNull(); } private static class MyLoggingTransaction implements LoggingTransaction { @Override public String getId() { return "ID"; } @Override public String getType() { return "MyLoggingTransaction"; } @Override public String getSubtype() { return "Subtype"; } @Override public ObjectNode toJson() { final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return objectMapper.valueToTree(this); } } }
5,575
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/batchjoblogging
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/batchjoblogging/service/BatchJobLoggingContextServiceImplTest.java
package com.paypal.observability.batchjoblogging.service; import com.paypal.jobsystem.batchjobsupport.support.AbstractBatchJobItem; import com.paypal.jobsystem.batchjob.model.BatchJobContext; import com.paypal.observability.batchjoblogging.model.BatchJobLoggingTransaction; import com.paypal.observability.loggingcontext.model.LoggingTransaction; import com.paypal.observability.loggingcontext.service.LoggingContextService; 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 java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class BatchJobLoggingContextServiceImplTest { @InjectMocks private BatchJobLoggingContextServiceImpl testObj; @Mock private BatchJobContext batchJobContextMock; @Mock private LoggingContextService loggingContextServiceMock; @Captor private ArgumentCaptor<BatchJobLoggingTransaction> batchJobLoggingTransactionArgumentCaptor; @Test void refreshBatchJobInformation_shouldClearItemTypeAndItemIdAndSetAsSubTypeTheJobNameAndUpdateLoggingTransaction() { when(batchJobContextMock.getJobName()).thenReturn("jobName"); final LoggingTransaction batchJobLoggingTransaction = new BatchJobLoggingTransaction("102230", "jobName"); when(loggingContextServiceMock.getCurrentLoggingTransaction()) .thenReturn(Optional.of(batchJobLoggingTransaction)); testObj.refreshBatchJobInformation(batchJobContextMock); verify(loggingContextServiceMock).updateLoggingTransaction(batchJobLoggingTransactionArgumentCaptor.capture()); final BatchJobLoggingTransaction expectedLoggingTransaction = batchJobLoggingTransactionArgumentCaptor .getValue(); assertThat(expectedLoggingTransaction.getSubtype()).isEqualTo("jobName"); assertThat(expectedLoggingTransaction.getId()).isEqualTo("102230"); assertThat(expectedLoggingTransaction.getItemType()).isNull(); assertThat(expectedLoggingTransaction.getItemId()).isNull(); } @Test void testRefreshBatchJobInformation_shouldSetItemTypeAndItemIdWithItemInformationPassedAndUpdateLoggingTransaction() { final LoggingTransaction batchJobLoggingTransaction = new BatchJobLoggingTransaction("102230", "jobName"); when(loggingContextServiceMock.getCurrentLoggingTransaction()) .thenReturn(Optional.of(batchJobLoggingTransaction)); final MyItem myItem = new MyItem("The item"); testObj.refreshBatchJobInformation(batchJobContextMock, myItem); verify(loggingContextServiceMock).updateLoggingTransaction(batchJobLoggingTransactionArgumentCaptor.capture()); final BatchJobLoggingTransaction expectedLoggingTransaction = batchJobLoggingTransactionArgumentCaptor .getValue(); assertThat(expectedLoggingTransaction.getId()).isEqualTo("102230"); assertThat(expectedLoggingTransaction.getItemType()).isEqualTo("MyItem"); assertThat(expectedLoggingTransaction.getItemId()).isEqualTo("The item"); } @Test void removeBatchJobItemInformation_shouldClearItemTypeAndItemIdInformation() { final LoggingTransaction batchJobLoggingTransaction = new BatchJobLoggingTransaction("102230", "jobName"); when(loggingContextServiceMock.getCurrentLoggingTransaction()) .thenReturn(Optional.of(batchJobLoggingTransaction)); testObj.removeBatchJobItemInformation(); verify(loggingContextServiceMock).updateLoggingTransaction(batchJobLoggingTransactionArgumentCaptor.capture()); final BatchJobLoggingTransaction expectedLoggingTransaction = batchJobLoggingTransactionArgumentCaptor .getValue(); assertThat(expectedLoggingTransaction.getItemType()).isNull(); assertThat(expectedLoggingTransaction.getItemId()).isNull(); } @Test void removeBatchJobInformation_shouldCallCloseLoggingTransaction() { testObj.removeBatchJobInformation(); verify(loggingContextServiceMock).closeLoggingTransaction(); } private static class MyItem extends AbstractBatchJobItem<String> { protected MyItem(final String item) { super(item); } @Override public String getItemId() { return getItem(); } @Override public String getItemType() { return this.getClass().getSimpleName(); } } }
5,576
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/hyperwalletapichecks
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/hyperwalletapichecks/actuator/HyperwalletAPIHealthCheckHealthIndicatorTest.java
package com.paypal.observability.hyperwalletapichecks.actuator; import com.paypal.observability.hyperwalletapichecks.actuator.converters.HyperwalletAPIHealthCheckActuatorConverter; import com.paypal.observability.hyperwalletapichecks.model.HyperwalletAPICheck; import com.paypal.observability.hyperwalletapichecks.services.HyperwalletHealthCheckService; 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.boot.actuate.health.Health; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class HyperwalletAPIHealthCheckHealthIndicatorTest { @InjectMocks private HyperwalletAPIHealthCheckHealthIndicator testObj; @Mock private HyperwalletHealthCheckService hyperwalletHealthCheckServiceMock; @Mock private HyperwalletAPIHealthCheckActuatorConverter hyperwalletAPIHealthCheckActuatorConverterMock; @Mock private Health healthMock; @Mock private HyperwalletAPICheck hyperwalletAPICheckMock; @Test void health_ShouldCheckHealthStatus_WhenHyperwalletReturnsAnything() { when(hyperwalletHealthCheckServiceMock.check()).thenReturn(hyperwalletAPICheckMock); when(hyperwalletAPIHealthCheckActuatorConverterMock.from(hyperwalletAPICheckMock)).thenReturn(healthMock); final Health result = testObj.health(); assertThat(result).isEqualTo(healthMock); } }
5,577
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/hyperwalletapichecks/actuator
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/hyperwalletapichecks/actuator/converters/HyperwalletAPIHealthCheckActuatorConverterImplTest.java
package com.paypal.observability.hyperwalletapichecks.actuator.converters; import com.paypal.observability.hyperwalletapichecks.model.HyperwalletAPICheck; import com.paypal.observability.hyperwalletapichecks.model.HyperwalletAPICheckStatus; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.Status; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(MockitoExtension.class) class HyperwalletAPIHealthCheckActuatorConverterImplTest { @InjectMocks private HyperwalletAPIHealthCheckActuatorConverterImpl testObj; @Test void from_ShouldConvertServiceOkResultIntoHealtObject() { //@formatter:off final HyperwalletAPICheck hyperwalletAPICheck = HyperwalletAPICheck.builder() .hyperwalletAPICheckStatus(HyperwalletAPICheckStatus.UP) .location("LOCATION") .build(); //@formatter:on final Health result = testObj.from(hyperwalletAPICheck); assertThat(result.getStatus()).isEqualTo(Status.UP); assertThat(result.getDetails()).containsEntry("location", "LOCATION"); } @Test void from_ShouldConvertServiceDownResultIntoHealthObject() { //@formatter:off final HyperwalletAPICheck hyperwalletAPICheck = HyperwalletAPICheck.builder() .hyperwalletAPICheckStatus(HyperwalletAPICheckStatus.DOWN) .error("ERROR") .location("LOCATION") .build(); //@formatter:on final Health result = testObj.from(hyperwalletAPICheck); assertThat(result.getStatus()).isEqualTo(Status.DOWN); assertThat(result.getDetails()).containsEntry("error", "ERROR"); assertThat(result.getDetails()).containsEntry("location", "LOCATION"); } }
5,578
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/hyperwalletapichecks
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/hyperwalletapichecks/services/HyperwalletHealthCheckServiceImplTest.java
package com.paypal.observability.hyperwalletapichecks.services; import com.hyperwallet.clientsdk.model.HyperwalletProgram; import com.paypal.observability.hyperwalletapichecks.connectors.HyperwalletAPIHealthCheckConnector; import com.paypal.observability.hyperwalletapichecks.model.HyperwalletAPICheck; import com.paypal.observability.hyperwalletapichecks.services.converters.HyperwalletAPIHealthCheckConnectorConverter; 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 HyperwalletHealthCheckServiceImplTest { @InjectMocks private HyperwalletHealthCheckServiceImpl testObj; @Mock private HyperwalletAPIHealthCheckConnector hyperwalletAPIHealthCheckConnectorMock; @Mock private HyperwalletAPIHealthCheckConnectorConverter hyperwalletAPIHealthCheckConnectorConverterMock; @Mock private HyperwalletProgram hyperwalletProgramMock; @Mock private HyperwalletAPICheck hyperwalletAPICheckMock; @Test void check_ShouldReturnAPICheck_FromResponse_WhenGetHyperwalletProgramReturnsAnything() { when(hyperwalletAPIHealthCheckConnectorMock.getProgram()).thenReturn(hyperwalletProgramMock); when(hyperwalletAPIHealthCheckConnectorConverterMock.from(hyperwalletProgramMock)) .thenReturn(hyperwalletAPICheckMock); final HyperwalletAPICheck hyperwalletAPICheck = testObj.check(); assertThat(hyperwalletAPICheck).isEqualTo(hyperwalletAPICheckMock); } @Test void check_ShouldReturnAPICheck_FromError_WhenGetHyperwalletProgramReturnsAnything() { final Exception e = new RuntimeException(); when(hyperwalletAPIHealthCheckConnectorMock.getProgram()).thenThrow(e); when(hyperwalletAPIHealthCheckConnectorConverterMock.from(e)).thenReturn(hyperwalletAPICheckMock); final HyperwalletAPICheck hyperwalletAPICheck = testObj.check(); assertThat(hyperwalletAPICheck).isEqualTo(hyperwalletAPICheckMock); } }
5,579
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/miraklfieldschecks
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/test/java/com/paypal/observability/miraklfieldschecks/diffs/MiraklFieldSchemaDiffEntrySeverityAssignerTest.java
package com.paypal.observability.miraklfieldschecks.diffs; import com.paypal.observability.miraklfieldschecks.model.MiraklField; import com.paypal.observability.miraklfieldschecks.model.MiraklFieldPermissions; import com.paypal.observability.miraklschemadiffs.model.diff.MiraklSchemaDiffEntryIncorrectAttributeValue; import com.paypal.observability.miraklschemadiffs.model.diff.MiraklSchemaDiffEntryType; import com.paypal.observability.miraklschemadiffs.model.report.MiraklSchemaDiffReportSeverity; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class MiraklFieldSchemaDiffEntrySeverityAssignerTest { @InjectMocks private MiraklFieldSchemaDiffEntrySeverityAssigner testObj; @Mock private MiraklSchemaDiffEntryIncorrectAttributeValue miraklSchemaDiffEntryIncorrectAttributeValueMock; @Mock private MiraklField miraklFieldActualMock, miraklFieldExpectedMock; @ParameterizedTest @MethodSource void getSeverityFor_shouldReturnBlockerWhenAddingMorePermissionsThanTheExpectedOnes( final MiraklFieldPermissions expectedPermissions, final MiraklFieldPermissions actualPermissions, final MiraklSchemaDiffReportSeverity expectedSeverity) { when(miraklSchemaDiffEntryIncorrectAttributeValueMock.getDiffType()) .thenReturn(MiraklSchemaDiffEntryType.INCORRECT_ATTRIBUTE_VALUE); when(miraklSchemaDiffEntryIncorrectAttributeValueMock.getAttributeName()).thenReturn("permissions"); when(miraklSchemaDiffEntryIncorrectAttributeValueMock.getActual()).thenReturn(miraklFieldActualMock); when(miraklSchemaDiffEntryIncorrectAttributeValueMock.getExpected()).thenReturn(miraklFieldExpectedMock); when(miraklFieldExpectedMock.getPermissions()).thenReturn(expectedPermissions); when(miraklFieldActualMock.getPermissions()).thenReturn(actualPermissions); final MiraklSchemaDiffReportSeverity result = testObj .getSeverityFor(miraklSchemaDiffEntryIncorrectAttributeValueMock); assertThat(result).isEqualTo(expectedSeverity); } private static Stream<Arguments> getSeverityFor_shouldReturnBlockerWhenAddingMorePermissionsThanTheExpectedOnes() { //@formatter:off return Stream.of( Arguments.of(MiraklFieldPermissions.INVISIBLE, MiraklFieldPermissions.READ_ONLY, MiraklSchemaDiffReportSeverity.FAIL), Arguments.of(MiraklFieldPermissions.INVISIBLE, MiraklFieldPermissions.READ_WRITE, MiraklSchemaDiffReportSeverity.FAIL), Arguments.of(MiraklFieldPermissions.READ_ONLY, MiraklFieldPermissions.INVISIBLE, MiraklSchemaDiffReportSeverity.WARN), Arguments.of(MiraklFieldPermissions.READ_ONLY, MiraklFieldPermissions.READ_WRITE, MiraklSchemaDiffReportSeverity.FAIL), Arguments.of(MiraklFieldPermissions.READ_WRITE, MiraklFieldPermissions.READ_ONLY, MiraklSchemaDiffReportSeverity.WARN), Arguments.of(MiraklFieldPermissions.READ_WRITE, MiraklFieldPermissions.INVISIBLE, MiraklSchemaDiffReportSeverity.WARN) ); //@formatter:on } }
5,580
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/AbstractObservabilityIntegrationTest.java
package com.paypal.observability; import com.paypal.observability.testsupport.fixtures.AdditionalFieldsMockServerFixtures; import com.paypal.observability.testsupport.fixtures.DocsMockServerFixtures; import com.paypal.observability.testsupport.fixtures.HealthMockServerFixtures; import com.paypal.observability.testsupport.fixtures.HyperwalletHealthMockServerFixtures; import com.paypal.testsupport.AbstractMockEnabledIntegrationTest; import org.junit.jupiter.api.BeforeEach; public abstract class AbstractObservabilityIntegrationTest extends AbstractMockEnabledIntegrationTest { protected AdditionalFieldsMockServerFixtures additionalFieldsMockServerFixtures; protected DocsMockServerFixtures docsMockServerFixtures; protected HealthMockServerFixtures healthMockServerFixtures; protected HyperwalletHealthMockServerFixtures hyperwalletHealthMockServerFixtures; @BeforeEach void setUpFixtures() { additionalFieldsMockServerFixtures = new AdditionalFieldsMockServerFixtures(mockServerClient); docsMockServerFixtures = new DocsMockServerFixtures(mockServerClient); healthMockServerFixtures = new HealthMockServerFixtures(mockServerClient); hyperwalletHealthMockServerFixtures = new HyperwalletHealthMockServerFixtures(mockServerClient); } }
5,581
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/ignoredprogramschecks/HmcIgnoredProgramsStartupCheckProviderTestTest.java
package com.paypal.observability.ignoredprogramschecks; import com.paypal.infrastructure.hyperwallet.configuration.HyperwalletProgramsConfiguration; import com.paypal.observability.AbstractObservabilityIntegrationTest; import com.paypal.observability.ignoredprogramschecks.startup.HmcIgnoredProgramsStartupCheckProvider; import com.paypal.observability.startupchecks.model.StartupCheck; import com.paypal.observability.startupchecks.model.StartupCheckStatus; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.util.ReflectionTestUtils; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; class HmcIgnoredProgramsStartupCheckProviderTestTest extends AbstractObservabilityIntegrationTest { @Autowired private HmcIgnoredProgramsStartupCheckProvider testObj; @Autowired private HyperwalletProgramsConfiguration hyperwalletProgramsConfiguration; private List<String> hyperwalletPrograms; private List<String> ignoredHyperwalletPrograms; private List<String> hyperwalletUserProgramTokens; private List<String> hyperwalletPaymentProgramTokens; private List<String> hyperwalletBankAccountTokens; @BeforeEach void setUp() { saveProgramsConfiguration(); } @AfterEach void tearDown() { reloadSavedProgramsConfiguration(); } @Test void check_shouldReturnReadyWhenIgnoredProgramsAreSubsetOfProgramTokens() { updateProgramsConfiguration(List.of("UK", "EUROPE"), List.of("EUROPE"), List.of("UT1", ""), List.of("PT1", ""), List.of("BT1", "")); final StartupCheck check = testObj.check(); assertThat(check.getStatus()).isEqualTo(StartupCheckStatus.READY); } @Test void check_shouldReturnReadyWithWarningsWhenIgnoredProgramsAreNotSubsetOfProgramTokens() { updateProgramsConfiguration(List.of("UK", "EUROPE"), List.of("DEFAULT"), List.of("UT1", ""), List.of("PT1", ""), List.of("BT1", "")); final StartupCheck check = testObj.check(); assertThat(check.getStatus()).isEqualTo(StartupCheckStatus.READY_WITH_WARNINGS); } @Test void check_shouldReturnReadyWhenIgnoredProgramsIsEmpty() { updateProgramsConfiguration(List.of("UK", "EUROPE"), List.of(), List.of("UT1", "UT2"), List.of("PT1", "PT2"), List.of("BT1", "BT2")); final StartupCheck check = testObj.check(); assertThat(check.getStatus()).isEqualTo(StartupCheckStatus.READY); } @Test void check_shouldReturnReadyWhenIgnoredProgramsIsNull() { ReflectionTestUtils.setField(hyperwalletProgramsConfiguration, "hyperwalletProgramsNames", List.of("UK", "EUROPE")); ReflectionTestUtils.setField(hyperwalletProgramsConfiguration, "ignoredHyperwalletPrograms", null); final StartupCheck check = testObj.check(); assertThat(check.getStatus()).isEqualTo(StartupCheckStatus.READY); } void updateProgramsConfiguration(final List<String> hyperwalletPrograms, final List<String> ignoredHyperwalletPrograms, final List<String> hyperwalletUserProgramTokens, final List<String> hyperwalletPaymentProgramTokens, final List<String> hyperwalletBankAccountTokens) { ReflectionTestUtils.setField(hyperwalletProgramsConfiguration, "hyperwalletProgramsNames", hyperwalletPrograms); ReflectionTestUtils.setField(hyperwalletProgramsConfiguration, "ignoredHyperwalletPrograms", ignoredHyperwalletPrograms); ReflectionTestUtils.setField(hyperwalletProgramsConfiguration, "hyperwalletUserProgramTokens", hyperwalletUserProgramTokens); ReflectionTestUtils.setField(hyperwalletProgramsConfiguration, "hyperwalletPaymentProgramTokens", hyperwalletPaymentProgramTokens); ReflectionTestUtils.setField(hyperwalletProgramsConfiguration, "hyperwalletBankAccountTokens", hyperwalletBankAccountTokens); ReflectionTestUtils.invokeMethod(hyperwalletProgramsConfiguration, "buildProgramTokensMap"); } @SuppressWarnings("unchecked") void saveProgramsConfiguration() { hyperwalletPrograms = new ArrayList<>((List<String>) ReflectionTestUtils .getField(hyperwalletProgramsConfiguration, "hyperwalletProgramsNames")); ignoredHyperwalletPrograms = new ArrayList<>((List<String>) ReflectionTestUtils .getField(hyperwalletProgramsConfiguration, "ignoredHyperwalletPrograms")); hyperwalletUserProgramTokens = new ArrayList<>((List<String>) ReflectionTestUtils .getField(hyperwalletProgramsConfiguration, "hyperwalletUserProgramTokens")); hyperwalletPaymentProgramTokens = new ArrayList<>((List<String>) ReflectionTestUtils .getField(hyperwalletProgramsConfiguration, "hyperwalletPaymentProgramTokens")); hyperwalletBankAccountTokens = new ArrayList<>((List<String>) ReflectionTestUtils .getField(hyperwalletProgramsConfiguration, "hyperwalletBankAccountTokens")); } void reloadSavedProgramsConfiguration() { updateProgramsConfiguration(hyperwalletPrograms, ignoredHyperwalletPrograms, hyperwalletUserProgramTokens, hyperwalletPaymentProgramTokens, hyperwalletBankAccountTokens); } }
5,582
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/testsupport/MiraklSchemaAssertions.java
package com.paypal.observability.testsupport; import com.paypal.observability.miraklschemadiffs.model.MiraklSchemaItem; import com.paypal.observability.miraklschemadiffs.model.diff.MiraklSchemaDiffEntryIncorrectAttributeValue; import com.paypal.observability.miraklschemadiffs.model.diff.MiraklSchemaDiffEntryType; import com.paypal.observability.miraklschemadiffs.model.report.MiraklSchemaDiffReport; import com.paypal.observability.miraklschemadiffs.model.report.MiraklSchemaDiffReportEntry; import com.paypal.observability.miraklschemadiffs.model.report.MiraklSchemaDiffReportSeverity; import org.assertj.core.api.Condition; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; public final class MiraklSchemaAssertions { private MiraklSchemaAssertions() { } public static void assertThatContainsEntry(final MiraklSchemaDiffReport diffReport, final MiraklSchemaDiffEntryType entryType, final String affectedItem) { //@formatter:off final Condition<MiraklSchemaDiffReportEntry> condition = new Condition<>(entry -> { if (entry.getDiff().getDiffType().equals(entryType)) { return matchsItem(entry, affectedItem); } else { return false; } }, "Entry of type " + entryType + " affecting field: " + affectedItem); //@formatter:on assertThat(diffReport.getDiffs()).haveAtLeast(1, condition); } public static void assertThatContainsEntry(final MiraklSchemaDiffReport diffReport, final MiraklSchemaDiffEntryType entryType, final String affectedItem, final String affectedField) { //@formatter:off final Condition<MiraklSchemaDiffReportEntry> condition = new Condition<>(entry -> { if (entry.getDiff().getDiffType().equals(entryType)) { return matchsItem(entry, affectedItem) && matchsField(entry, affectedField); } else { return false; } }, "Entry of type " + entryType + " affecting field: " + affectedItem); //@formatter:on assertThat(diffReport.getDiffs()).haveAtLeast(1, condition); } private static boolean matchsField(final MiraklSchemaDiffReportEntry entry, final String affectedField) { return ((MiraklSchemaDiffEntryIncorrectAttributeValue) entry.getDiff()).getAttributeName() .equals(affectedField); } private static boolean matchsItem(final MiraklSchemaDiffReportEntry entry, final String affectedItem) { if (ReflectionUtils.findField(entry.getDiff().getClass(), "expected") != null) { final MiraklSchemaItem item = (MiraklSchemaItem) ReflectionTestUtils.getField(entry.getDiff(), entry.getDiff().getClass(), "expected"); return item.getCode().equals(affectedItem); } else { final MiraklSchemaItem item = (MiraklSchemaItem) ReflectionTestUtils.getField(entry.getDiff(), entry.getDiff().getClass(), "item"); return item.getCode().equals(affectedItem); } } public static void assertSeverityForDiffType(final MiraklSchemaDiffReport diffReport, final MiraklSchemaDiffReportSeverity severity, final MiraklSchemaDiffEntryType miraklSchemaDiffEntryType) { //@formatter:off diffReport.getDiffs().stream() .filter(p -> p.getDiff().getDiffType() == miraklSchemaDiffEntryType) .forEach(p -> assertThat(p.getSeverity()).as("The severity [%s] of entry [%s] is not [%s]", p.getSeverity(), miraklSchemaDiffEntryType, severity).isEqualTo(severity)); //@formatter:on } public static void assertSeverityForDiffType(final MiraklSchemaDiffReport diffReport, final MiraklSchemaDiffReportSeverity severity, final String affectedField) { //@formatter:off diffReport.getDiffs().stream() .filter(p -> p.getDiff().getDiffType() == MiraklSchemaDiffEntryType.INCORRECT_ATTRIBUTE_VALUE && ((MiraklSchemaDiffEntryIncorrectAttributeValue) p.getDiff()).getAttributeName().equals(affectedField)) .forEach(p -> assertThat(p.getSeverity()).as("The severity [%s] of entry [%s] is not [%s]", p.getSeverity(), MiraklSchemaDiffEntryType.INCORRECT_ATTRIBUTE_VALUE, severity).isEqualTo(severity)); //@formatter:on } }
5,583
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/testsupport/MiraklReportAssertions.java
package com.paypal.observability.testsupport; import java.util.Arrays; import static org.assertj.core.api.Assertions.assertThat; public final class MiraklReportAssertions { private MiraklReportAssertions() { } public static void assertThatContainsMessage(final String[] report, final String error) { assertThat(Arrays.stream(report).filter(x -> matchErrorMessage(error, x)).findAny()).isPresent(); } private static boolean matchErrorMessage(final String error, final String reportMessage) { return reportMessage.contains(error) && reportMessage.contains("\nExpected value:") && reportMessage.contains("\nActual value:"); } public static void assertThatContainsSetMessage(final String[] report, final String error) { assertThat(Arrays.stream(report).filter(x -> matchSetErrorMessage(error, x)).findAny()).isPresent(); } private static boolean matchSetErrorMessage(final String error, final String reportMessage) { return reportMessage.contains(error) && reportMessage.contains("\nOffending field details:"); } }
5,584
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/testsupport
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/testsupport/fixtures/AdditionalFieldsMockServerFixtures.java
package com.paypal.observability.testsupport.fixtures; import com.paypal.testsupport.mocks.AbstractMockServerFixtures; import org.mockserver.client.MockServerClient; public class AdditionalFieldsMockServerFixtures extends AbstractMockServerFixtures { public AdditionalFieldsMockServerFixtures(final MockServerClient mockServerClient) { super(mockServerClient); } @Override protected String getFolder() { return "mirakl/fields"; } private void mockGetAdditionalFields(final String responseFile, final int statusCode) { mockGet("/api/additional_fields", responseFile, statusCode); } private void mockGetAdditionalFieldsStatusOK(final String responseFile) { mockGetAdditionalFields(responseFile, 200); } private void mockGetAdditionalFieldsStatusServerError(final String responseFile) { mockGetAdditionalFields(responseFile, 500); } public void mockGetAdditionalFields_emptySchema() { mockGetAdditionalFieldsStatusOK("custom-fields-00.json"); } public void mockGetAdditionalFields_kyc_correct() { mockGetAdditionalFieldsStatusOK("custom-fields-01.json"); } public void mockGetAdditionalFields_kyc_correctWithWarnings() { mockGetAdditionalFieldsStatusOK("custom-fields-13.json"); } public void mockGetAdditionalFields_kyc_incorrectWithFails() { mockGetAdditionalFieldsStatusOK("custom-fields-14.json"); } public void mockGetAdditionalFields_internalServerError() { mockGetAdditionalFieldsStatusServerError("internal-server-error.json"); } public void mockGetAdditionalFields_nonkyc_correct() { mockGetAdditionalFieldsStatusOK("custom-fields-02.json"); } public void mockGetAdditionalFields_nonkyc_additionalField() { mockGetAdditionalFieldsStatusOK("custom-fields-03.json"); } public void mockGetAdditionalFields_nonkyc_notFoundField() { mockGetAdditionalFieldsStatusOK("custom-fields-04.json"); } public void mockGetAdditionalFields_nonkyc_incorrectLabel() { mockGetAdditionalFieldsStatusOK("custom-fields-05.json"); } public void mockGetAdditionalFields_nonkyc_incorrectDescription() { mockGetAdditionalFieldsStatusOK("custom-fields-06.json"); } public void mockGetAdditionalFields_nonkyc_incorrectType() { mockGetAdditionalFieldsStatusOK("custom-fields-07.json"); } public void mockGetAdditionalFields_nonkyc_incorrectAllowedValues() { mockGetAdditionalFieldsStatusOK("custom-fields-08.json"); } public void mockGetAdditionalFields_nonkyc_incorrectPermissions() { mockGetAdditionalFieldsStatusOK("custom-fields-09.json"); } public void mockGetAdditionalFields_nonkyc_incorrectRegex() { mockGetAdditionalFieldsStatusOK("custom-fields-12.json"); } public void mockGetAdditionalFields_nonkyc_multipleErrorsOnSameField() { mockGetAdditionalFieldsStatusOK("custom-fields-10.json"); } public void mockGetAdditionalFields_nonkyc_multipleErrorsOnDifferentFields() { mockGetAdditionalFieldsStatusOK("custom-fields-11.json"); } }
5,585
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/testsupport
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/testsupport/fixtures/HealthMockServerFixtures.java
package com.paypal.observability.testsupport.fixtures; import com.paypal.testsupport.mocks.AbstractMockServerFixtures; import org.mockserver.client.MockServerClient; public class HealthMockServerFixtures extends AbstractMockServerFixtures { public HealthMockServerFixtures(final MockServerClient mockServerClient) { super(mockServerClient); } @Override protected String getFolder() { return "mirakl/health"; } private void mockGetVersion(final String responseFile, final int statusCode) { mockGet("/api/version", responseFile, statusCode); } private void mockGetVersionStatusOK(final String responseFile) { mockGetVersion(responseFile, 200); } private void mockGetVersionStatusError(final String responseFile) { mockGetVersion(responseFile, 500); } public void mockGetVersion_up() { mockGetVersionStatusOK("health-00.json"); } public void mockGetVersion_down() { mockGetVersionStatusError("health-error500.json"); } }
5,586
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/testsupport
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/testsupport/fixtures/DocsMockServerFixtures.java
package com.paypal.observability.testsupport.fixtures; import com.paypal.testsupport.mocks.AbstractMockServerFixtures; import org.mockserver.client.MockServerClient; public class DocsMockServerFixtures extends AbstractMockServerFixtures { public DocsMockServerFixtures(final MockServerClient mockServerClient) { super(mockServerClient); } @Override protected String getFolder() { return "mirakl/docs"; } private void mockGetDocsConfiguration(final String responseFile, final int statusCode) { mockGet("/api/documents", responseFile, statusCode); } private void mockGetDocsConfigurationStatusOK(final String responseFile) { mockGetDocsConfiguration(responseFile, 200); } public void mockGetDocsConfiguration_emptyResponse() { mockGetDocsConfigurationStatusOK("docs-00.json"); } public void mockGetDocsConfiguration_correctSchemaResponse() { mockGetDocsConfigurationStatusOK("docs-01.json"); } public void mockGetDocsConfiguration_additionalDoc() { mockGetDocsConfigurationStatusOK("docs-02.json"); } public void mockGetDocsConfiguration_notFoundDoc() { mockGetDocsConfigurationStatusOK("docs-03.json"); } public void mockGetDocsConfiguration_incorrectLabel() { mockGetDocsConfigurationStatusOK("docs-04.json"); } public void mockGetDocsConfiguration_incorrectDescription() { mockGetDocsConfigurationStatusOK("docs-05.json"); } public void mockGetDocsConfiguration_mutipleDiffs() { mockGetDocsConfigurationStatusOK("docs-06.json"); } public void mockGetDocsConfiguration_withWarnings() { mockGetDocsConfigurationStatusOK("docs-07.json"); } }
5,587
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/testsupport
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/testsupport/fixtures/HyperwalletHealthMockServerFixtures.java
package com.paypal.observability.testsupport.fixtures; import com.paypal.testsupport.mocks.AbstractMockServerFixtures; import org.mockserver.client.MockServerClient; import java.util.Map; public class HyperwalletHealthMockServerFixtures extends AbstractMockServerFixtures { public HyperwalletHealthMockServerFixtures(final MockServerClient mockServerClient) { super(mockServerClient); } @Override protected String getFolder() { return "hyperwallet/health"; } private void mockGetProgram(final String responseFile, final int statusCode, final String programToken) { mockGet("/api/rest/v4/programs/{programToken}", responseFile, statusCode, Map.of("programToken", programToken)); } private void mockGetProgramStatusOK(final String responseFile, final String programToken) { mockGetProgram(responseFile, 200, programToken); } private void mockGetProgramStatusError(final String responseFile, final String programToken) { mockGetProgram(responseFile, 500, programToken); } public void mockGetHealth_up() { mockGetProgramStatusOK("health-00.json", "prg-1fb3df0d-787b-4bbd-9eb7-1d9fe8ed6c8e"); } public void mockGetHealth_down() { mockGetProgramStatusError("health-error500.json", "prg-1fb3df0d-787b-4bbd-9eb7-1d9fe8ed6c8e"); } }
5,588
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/trafficauditor/TrafficAuditorWebhooksTest.java
package com.paypal.observability.trafficauditor; import com.paypal.observability.AbstractObservabilityIntegrationTest; import com.paypal.observability.trafficauditor.interceptors.webhooks.WebhookLoggingRequestFilter; import com.paypal.observability.trafficauditor.loggers.TrafficAuditorLogger; import com.paypal.observability.trafficauditor.model.TrafficAuditorTarget; import com.paypal.observability.trafficauditor.model.TrafficAuditorTrace; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; 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.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; import org.springframework.util.ResourceUtils; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; 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.status; @AutoConfigureMockMvc(addFilters = false) class TrafficAuditorWebhooksTest extends AbstractObservabilityIntegrationTest { @Autowired private MockMvc mockMvc; @Autowired private DefaultMockMvcBuilder mockMvcBuilder; @Autowired private WebhookLoggingRequestFilter webhookLoggingRequestFilter; @SpyBean private TrafficAuditorLogger trafficAuditorLogger; @Captor private ArgumentCaptor<TrafficAuditorTrace> traceArgumentCaptor; @Test void webhooks_shouldBeAudited() throws Exception { mockMvc = mockMvcBuilder.addFilter(webhookLoggingRequestFilter).build(); mockMvc.perform( post("/webhooks/notifications").contentType(MediaType.APPLICATION_JSON).content(getWebhookBody())) .andDo(print()).andExpect(status().isOk()); verify(trafficAuditorLogger, atLeastOnce()).log(traceArgumentCaptor.capture()); final List<TrafficAuditorTrace> capturedTraces = traceArgumentCaptor.getAllValues(); final TrafficAuditorTrace capturedTrace = capturedTraces.get(capturedTraces.size() - 1); assertThat(capturedTrace.getTarget()).isEqualTo(TrafficAuditorTarget.HMC); assertThat(capturedTrace.getRequest().getUrl()).contains("/webhooks/notifications"); assertThat(capturedTrace.getRequest().getBody()).contains("clientUserId"); assertThat(capturedTrace.getRequest().getHeaders()).containsKey("Content-Type"); assertThat(capturedTrace.getRequest().getHeaders().get("Content-Type").get(0)).contains("application/json"); assertThat(capturedTrace.getRequest().getMethod()).contains("POST"); assertThat(capturedTrace.getRequest().getQueryParameters()).isEmpty(); assertThat(capturedTrace.getResponse()).isEmpty(); } @Test void webhooks_ignoredUrls_shouldNotBeAudited() throws Exception { mockMvc = mockMvcBuilder.addFilter(webhookLoggingRequestFilter).build(); mockMvc.perform(post("/unknown").contentType(MediaType.APPLICATION_JSON).content(getWebhookBody())) .andDo(print()); verify(trafficAuditorLogger, never()) .log(argThat(argument -> argument.getRequest().getUrl().contains("/unknown"))); } private String getWebhookBody() throws IOException { final File file = ResourceUtils.getFile("classpath:" + "trafficauditor/webhooks/webhook-00.json"); return new String(Files.readAllBytes(file.toPath())); } }
5,589
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/trafficauditor/TrafficAuditorMiraklTest.java
package com.paypal.observability.trafficauditor; import com.mirakl.client.mmp.domain.shop.MiraklShopKyc; import com.mirakl.client.mmp.domain.shop.MiraklShopKycStatus; import com.mirakl.client.mmp.domain.shop.MiraklShops; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdateShop; 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.shop.MiraklGetShopsRequest; import com.paypal.infrastructure.mirakl.client.DirectMiraklClient; import com.paypal.observability.AbstractObservabilityIntegrationTest; import com.paypal.observability.trafficauditor.loggers.TrafficAuditorLogger; import com.paypal.observability.trafficauditor.model.TrafficAuditorTarget; import com.paypal.observability.trafficauditor.model.TrafficAuditorTrace; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.mock.mockito.SpyBean; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; class TrafficAuditorMiraklTest extends AbstractObservabilityIntegrationTest { @Autowired private DirectMiraklClient miraklClient; @SpyBean private TrafficAuditorLogger trafficAuditorLogger; @Captor private ArgumentCaptor<TrafficAuditorTrace> traceArgumentCaptor; @Test void httpMiraklGetOperation_shouldBeAudited() { // given mockServerExpectationsLoader.loadExpectationsFromFolder("trafficauditor/expectations", "mirakl", Map.of()); // when final MiraklGetShopsRequest miraklGetShopsRequest = new MiraklGetShopsRequest(); miraklGetShopsRequest.setShopIds(List.of("10000")); final MiraklShops result = miraklClient.getShops(miraklGetShopsRequest); // then assertThat(result.getShops()).isNotEmpty(); assertThat(result).isNotNull(); verify(trafficAuditorLogger, atLeastOnce()).log(traceArgumentCaptor.capture()); final List<TrafficAuditorTrace> capturedTraces = traceArgumentCaptor.getAllValues(); final TrafficAuditorTrace capturedTrace = capturedTraces.get(capturedTraces.size() - 1); assertThat(capturedTrace.getTarget()).isEqualTo(TrafficAuditorTarget.MIRAKL); assertThat(capturedTrace.getRequest().getUrl()).contains("/api/shops"); assertThat(capturedTrace.getRequest().getQueryParameters()).containsEntry("shop_ids", "10000"); assertThat(capturedTrace.getRequest().getHeaders()).containsEntry("Accept", List.of("application/json; charset=UTF-8")); assertThat(capturedTrace.getRequest().getBody()).isNullOrEmpty(); assertThat(capturedTrace.getRequest().getMethod()).contains("GET"); assertThat(capturedTrace.getResponse().orElseThrow(IllegalStateException::new).getBody()) .contains("hw-user-token"); assertThat(capturedTrace.getResponse().orElseThrow(IllegalStateException::new).getResponseCode()) .isEqualTo(200); assertThat(capturedTrace.getResponse().orElseThrow(IllegalStateException::new).getHeaders()) .containsEntry("Content-Type", List.of("application/json")); } @Test void httpMiraklPutOperation_shouldBeAudited() { // given mockServerExpectationsLoader.loadExpectationsFromFolder("trafficauditor/expectations", "mirakl", Map.of()); // when final MiraklUpdateShop miraklUpdateShop = new MiraklUpdateShop(); miraklUpdateShop.setShopId(10000L); miraklUpdateShop.setKyc(new MiraklShopKyc(MiraklShopKycStatus.APPROVED, "")); final MiraklUpdateShopsRequest miraklUpdatedShops = new MiraklUpdateShopsRequest(List.of(miraklUpdateShop)); final MiraklUpdatedShops result = miraklClient.updateShops(miraklUpdatedShops); // then assertThat(result.getShopReturns()).isNotEmpty(); assertThat(result).isNotNull(); verify(trafficAuditorLogger, atLeastOnce()).log(traceArgumentCaptor.capture()); final List<TrafficAuditorTrace> capturedTraces = traceArgumentCaptor.getAllValues(); final TrafficAuditorTrace capturedTrace = capturedTraces.get(capturedTraces.size() - 1); assertThat(capturedTrace.getTarget()).isEqualTo(TrafficAuditorTarget.MIRAKL); assertThat(capturedTrace.getRequest().getUrl()).contains("/api/shops"); assertThat(capturedTrace.getRequest().getBody()).contains("shop_id"); assertThat(capturedTrace.getRequest().getHeaders()).containsEntry("Accept", List.of("application/json; charset=UTF-8")); assertThat(capturedTrace.getRequest().getMethod()).contains("PUT"); assertThat(capturedTrace.getRequest().getQueryParameters()).containsEntry("sdk-module", "mmp-sdk-operator") .containsKey("sdk-version"); assertThat(capturedTrace.getResponse().orElseThrow(IllegalStateException::new).getBody()).contains("shop_id") .contains("10000"); assertThat(capturedTrace.getResponse().orElseThrow(IllegalStateException::new).getResponseCode()) .isEqualTo(200); assertThat(capturedTrace.getResponse().orElseThrow(IllegalStateException::new).getHeaders()) .containsEntry("Content-Type", List.of("application/json")); } }
5,590
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/trafficauditor/TrafficAuditorHyperwalletTest.java
package com.paypal.observability.trafficauditor; import com.hyperwallet.clientsdk.Hyperwallet; import com.hyperwallet.clientsdk.model.HyperwalletList; import com.hyperwallet.clientsdk.model.HyperwalletUser; import com.hyperwallet.clientsdk.model.HyperwalletUsersListPaginationOptions; import com.paypal.infrastructure.hyperwallet.services.UserHyperwalletSDKService; import com.paypal.observability.AbstractObservabilityIntegrationTest; import com.paypal.observability.trafficauditor.loggers.TrafficAuditorLogger; import com.paypal.observability.trafficauditor.model.TrafficAuditorTarget; import com.paypal.observability.trafficauditor.model.TrafficAuditorTrace; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.mock.mockito.SpyBean; import java.util.Date; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; class TrafficAuditorHyperwalletTest extends AbstractObservabilityIntegrationTest { @Autowired private UserHyperwalletSDKService hyperwalletSDKService; @SpyBean private TrafficAuditorLogger trafficAuditorLogger; @Captor private ArgumentCaptor<TrafficAuditorTrace> traceArgumentCaptor; @Test void httpGetOperation_shouldBeAudited() { // given final Hyperwallet hyperwallet = hyperwalletSDKService.getHyperwalletInstance(); mockServerExpectationsLoader.loadExpectationsFromFolder("trafficauditor/expectations", "hyperwallet", Map.of()); // when final HyperwalletUsersListPaginationOptions options = new HyperwalletUsersListPaginationOptions(); options.setCreatedAfter(new Date()); options.setCreatedBefore(new Date()); final HyperwalletList<HyperwalletUser> result = hyperwallet.listUsers(options); // then assertThat(result).isNotNull(); verify(trafficAuditorLogger, atLeastOnce()).log(traceArgumentCaptor.capture()); final List<TrafficAuditorTrace> capturedTraces = traceArgumentCaptor.getAllValues(); final TrafficAuditorTrace capturedTrace = capturedTraces.get(capturedTraces.size() - 1); assertThat(capturedTrace.getTarget()).isEqualTo(TrafficAuditorTarget.HYPERWALLET); assertThat(capturedTrace.getRequest().getUrl()).contains("/api/rest/v4/users"); assertThat(capturedTrace.getRequest().getQueryParameters()).containsKey("createdAfter") .containsKey("createdBefore"); assertThat(capturedTrace.getRequest().getHeaders()).containsEntry("Accept", List.of("application/json")); assertThat(capturedTrace.getRequest().getBody()).isNullOrEmpty(); assertThat(capturedTrace.getRequest().getMethod()).contains("GET"); assertThat(capturedTrace.getResponse().orElseThrow(IllegalStateException::new).getBody()) .contains("usr-31a60e4c-dc9d-4061-899b-46575d2508d7"); assertThat(capturedTrace.getResponse().orElseThrow(IllegalStateException::new).getResponseCode()) .isEqualTo(200); assertThat(capturedTrace.getResponse().orElseThrow(IllegalStateException::new).getHeaders()) .containsEntry("Content-Type", List.of("application/json")); } @Test void httpPostOperation_shouldBeAudited() { // given final Hyperwallet hyperwallet = hyperwalletSDKService.getHyperwalletInstance(); mockServerExpectationsLoader.loadExpectationsFromFolder("trafficauditor/expectations", "hyperwallet", Map.of()); final HyperwalletUser hyperwalletUser = new HyperwalletUser(); hyperwalletUser.setClientUserId("mockedClientUserId"); // when final HyperwalletUser result = hyperwallet.createUser(hyperwalletUser); // then assertThat(result).isNotNull(); assertThat(result.getClientUserId()).isEqualTo("mockedClientUserId"); verify(trafficAuditorLogger, atLeastOnce()).log(traceArgumentCaptor.capture()); final List<TrafficAuditorTrace> capturedTraces = traceArgumentCaptor.getAllValues(); final TrafficAuditorTrace capturedTrace = capturedTraces.get(capturedTraces.size() - 1); assertThat(capturedTrace.getTarget()).isEqualTo(TrafficAuditorTarget.HYPERWALLET); assertThat(capturedTrace.getRequest().getUrl()).contains("/api/rest/v4/users"); assertThat(capturedTrace.getRequest().getBody()).contains("mockedClientUserId"); assertThat(capturedTrace.getRequest().getHeaders()).containsKey("Content-Type"); assertThat(capturedTrace.getRequest().getMethod()).contains("POST"); assertThat(capturedTrace.getResponse().orElseThrow(IllegalStateException::new).getBody()) .contains("mockedToken"); assertThat(capturedTrace.getResponse().orElseThrow(IllegalStateException::new).getResponseCode()) .isEqualTo(200); assertThat(capturedTrace.getResponse().orElseThrow(IllegalStateException::new).getHeaders()) .containsEntry("Content-Type", List.of("application/json")); } @Test void httpPutOperation_shouldBeAudited() { // given final Hyperwallet hyperwallet = hyperwalletSDKService.getHyperwalletInstance(); mockServerExpectationsLoader.loadExpectationsFromFolder("trafficauditor/expectations", "hyperwallet", Map.of()); final HyperwalletUser hyperwalletUser = new HyperwalletUser(); hyperwalletUser.setClientUserId("mockedClientUserId"); hyperwalletUser.setToken("mockedToken"); // when final HyperwalletUser result = hyperwallet.updateUser(hyperwalletUser); // then assertThat(result).isNotNull(); assertThat(result.getClientUserId()).isEqualTo("mockedClientUserId"); verify(trafficAuditorLogger, atLeastOnce()).log(traceArgumentCaptor.capture()); final List<TrafficAuditorTrace> capturedTraces = traceArgumentCaptor.getAllValues(); final TrafficAuditorTrace capturedTrace = capturedTraces.get(capturedTraces.size() - 1); assertThat(capturedTrace.getTarget()).isEqualTo(TrafficAuditorTarget.HYPERWALLET); assertThat(capturedTrace.getRequest().getUrl()).contains("/api/rest/v4/users/mockedToken"); assertThat(capturedTrace.getRequest().getBody()).contains("mockedClientUserId"); assertThat(capturedTrace.getRequest().getHeaders()).containsKey("Content-Type"); assertThat(capturedTrace.getRequest().getMethod()).contains("PUT"); assertThat(capturedTrace.getResponse().orElseThrow(IllegalStateException::new).getBody()) .contains("mockedToken"); assertThat(capturedTrace.getResponse().orElseThrow(IllegalStateException::new).getResponseCode()) .isEqualTo(200); assertThat(capturedTrace.getResponse().orElseThrow(IllegalStateException::new).getHeaders()) .containsEntry("Content-Type", List.of("application/json")); } }
5,591
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/trafficauditor/TrafficAuditorManagementControllerTest.java
package com.paypal.observability.trafficauditor; import com.fasterxml.jackson.databind.ObjectMapper; import com.paypal.observability.trafficauditor.configuration.TrafficAuditorConfiguration; import com.paypal.observability.trafficauditor.controllers.dtos.TrafficAuditorConfigurationDto; import com.paypal.testsupport.AbstractIntegrationTest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; 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.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultActions; import java.io.StringWriter; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @AutoConfigureMockMvc(addFilters = false) class TrafficAuditorManagementControllerTest extends AbstractIntegrationTest { @Autowired private MockMvc mockMvc; @Autowired private TrafficAuditorConfiguration trafficAuditorConfiguration; private boolean trafficAuditorEnabled; @BeforeEach void storeTrafficAuditorEnabled() { trafficAuditorEnabled = trafficAuditorConfiguration.isTrafficAuditorEnabled(); } @AfterEach void restoreTrafficAuditorEnabled() { trafficAuditorConfiguration.setTrafficAuditorEnabled(trafficAuditorEnabled); } @Test void shouldGetTrafficAuditorConfiguration_whenIsTrue() throws Exception { trafficAuditorConfiguration.setTrafficAuditorEnabled(true); final TrafficAuditorConfigurationDto response = doGetTrafficAuditorConfiguration(); assertThat(response.isTrafficAuditorEnabled()).isTrue(); } @Test void shouldGetTrafficAuditorConfiguration_whenIsFalse() throws Exception { trafficAuditorConfiguration.setTrafficAuditorEnabled(false); final TrafficAuditorConfigurationDto response = doGetTrafficAuditorConfiguration(); assertThat(response.isTrafficAuditorEnabled()).isFalse(); } @Test void shouldSetTrafficAuditorConfiguration_whenIsFalse() throws Exception { trafficAuditorConfiguration.setTrafficAuditorEnabled(false); final TrafficAuditorConfigurationDto requestBody = new TrafficAuditorConfigurationDto(true); this.mockMvc .perform(put("/management/traffic-auditor/configuration").contentType(MediaType.APPLICATION_JSON) .content(serializeCommissionsConfigurationDto(requestBody))) .andDo(print()).andExpect(status().isOk()); assertThat(trafficAuditorConfiguration.isTrafficAuditorEnabled()).isTrue(); } private TrafficAuditorConfigurationDto doGetTrafficAuditorConfiguration() throws Exception { final ResultActions resultActions = this.mockMvc.perform(get("/management/traffic-auditor/configuration")) .andDo(print()).andExpect(status().isOk()); final TrafficAuditorConfigurationDto response = getCommissionsConfigurationDto(resultActions); return response; } private TrafficAuditorConfigurationDto getCommissionsConfigurationDto(final ResultActions resultActions) throws Exception { final MvcResult result = resultActions.andReturn(); final String contentAsString = result.getResponse().getContentAsString(); final ObjectMapper objectMapper = new ObjectMapper(); final TrafficAuditorConfigurationDto response = objectMapper.readValue(contentAsString, TrafficAuditorConfigurationDto.class); return response; } private static String serializeCommissionsConfigurationDto( final TrafficAuditorConfigurationDto trafficAuditorConfigurationDto) throws Exception { final ObjectMapper objectMapper = new ObjectMapper(); final StringWriter stringWriter = new StringWriter(); objectMapper.writeValue(stringWriter, trafficAuditorConfigurationDto); return stringWriter.toString(); } }
5,592
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/miraklapichecks/MiraklAPIChecksActuatorAdapterITTest.java
package com.paypal.observability.miraklapichecks; import com.paypal.infrastructure.mirakl.configuration.MiraklApiClientConfig; import com.paypal.observability.AbstractObservabilityIntegrationTest; 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.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @AutoConfigureMockMvc(addFilters = false) class MiraklAPIChecksActuatorAdapterITTest extends AbstractObservabilityIntegrationTest { @Autowired private MockMvc mockMvc; @Autowired private MiraklApiClientConfig miraklApiClientConfig; @Test void miraklAPICheckShouldReturnHealthUp() throws Exception { this.hyperwalletHealthMockServerFixtures.mockGetHealth_up(); this.healthMockServerFixtures.mockGetVersion_up(); //@formatter:off final ResultActions perform = this.mockMvc.perform(MockMvcRequestBuilders.get("/actuator/health")); perform .andExpect(status().isOk()) .andExpect(jsonPath("$.components.miraklAPIHealthCheck.status").value("UP")) .andExpect(jsonPath("$.components.miraklAPIHealthCheck.details.version").value("3.210")) .andExpect(jsonPath("$.components.miraklAPIHealthCheck.details.location") .value(this.miraklApiClientConfig.getEnvironment())); //@formatter:on } @Test void miraklAPICheckShouldReturnHealthDown() throws Exception { hyperwalletHealthMockServerFixtures.mockGetHealth_up(); healthMockServerFixtures.mockGetVersion_down(); //@formatter:off mockMvc.perform(MockMvcRequestBuilders.get("/actuator/health")) .andExpect(status().is5xxServerError()) .andExpect(jsonPath("$.components.miraklAPIHealthCheck.status").value("DOWN")) .andExpect(jsonPath("$.components.miraklAPIHealthCheck.details.error") .value("[500] Internal Server Error")) .andExpect(jsonPath("$.components.miraklAPIHealthCheck.details.location") .value(miraklApiClientConfig.getEnvironment())); //@formatter:on } }
5,593
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/miraklapichecks/MiraklAPIChecksStartupAdapterITTest.java
package com.paypal.observability.miraklapichecks; import com.paypal.observability.AbstractObservabilityIntegrationTest; import com.paypal.observability.miraklapichecks.startup.MiraklHealthCheckStartupCheckPrinter; import com.paypal.observability.miraklapichecks.startup.MiraklHealthCheckStartupProvider; import com.paypal.observability.startupchecks.model.StartupCheck; import com.paypal.observability.startupchecks.model.StartupCheckStatus; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import static org.assertj.core.api.Assertions.assertThat; class MiraklAPIChecksStartupAdapterITTest extends AbstractObservabilityIntegrationTest { @Autowired private MiraklHealthCheckStartupProvider miraklHealthCheckStartupProvider; @Autowired private MiraklHealthCheckStartupCheckPrinter miraklHealthCheckStartupCheckPrinter; @Test void shouldCheckAndReturnReadyStatusWhenAllItsOK() { healthMockServerFixtures.mockGetVersion_up(); final StartupCheck startupCheck = miraklHealthCheckStartupProvider.check(); final String[] startupCheckReport = miraklHealthCheckStartupCheckPrinter.print(startupCheck); assertThat(startupCheck.getStatus()).isEqualTo(StartupCheckStatus.READY); //@formatter:off assertThat(startupCheckReport[0]).contains("Mirakl API is accessible") .contains("status: UP") .contains("version: 3.210") .contains("location: http://localhost"); //@formatter:on } @Test void shouldCheckAndReturnReadyWithWarningsStatusWhenAllItsOK() { healthMockServerFixtures.mockGetVersion_down(); final StartupCheck startupCheck = miraklHealthCheckStartupProvider.check(); final String[] startupCheckReport = miraklHealthCheckStartupCheckPrinter.print(startupCheck); assertThat(startupCheck.getStatus()).isEqualTo(StartupCheckStatus.READY_WITH_WARNINGS); //@formatter:off assertThat(startupCheckReport[0]).contains("Mirakl API is not accessible") .contains("status: DOWN") .contains("error: [500] Internal Server Error") .contains("location: http://localhost"); //@formatter:on } }
5,594
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/miraklapichecks/MiraklAPIChecksITTest.java
package com.paypal.observability.miraklapichecks; import com.paypal.observability.AbstractObservabilityIntegrationTest; import com.paypal.observability.miraklapichecks.model.MiraklAPICheck; import com.paypal.observability.miraklapichecks.model.MiraklAPICheckStatus; import com.paypal.observability.miraklapichecks.services.MiraklHealthCheckService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import static org.assertj.core.api.Assertions.assertThat; class MiraklAPIChecksITTest extends AbstractObservabilityIntegrationTest { @Value("${server.url}") private String serverUrl; @Autowired private MiraklHealthCheckService miraklHealthCheckService; @Test void shouldCheckWhenMiraklIsUp() { healthMockServerFixtures.mockGetVersion_up(); final MiraklAPICheck miraklAPICheck = miraklHealthCheckService.check(); assertThat(miraklAPICheck.getMiraklAPICheckStatus()).isEqualTo(MiraklAPICheckStatus.UP); assertThat(miraklAPICheck.getVersion()).isEqualTo("3.210"); assertThat(miraklAPICheck.getLocation()).isEqualTo(this.serverUrl); assertThat(miraklAPICheck.getError()).isNull(); } @Test void shouldCheckWhenMiraklIsDown() { healthMockServerFixtures.mockGetVersion_down(); final MiraklAPICheck miraklAPICheck = miraklHealthCheckService.check(); assertThat(miraklAPICheck.getMiraklAPICheckStatus()).isEqualTo(MiraklAPICheckStatus.DOWN); assertThat(miraklAPICheck.getLocation()).isEqualTo(this.serverUrl); assertThat(miraklAPICheck.getError()).isEqualTo("[500] Internal Server Error"); } }
5,595
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/startupchecks/StartupChecksITTest.java
package com.paypal.observability.startupchecks; import com.callibrity.logging.test.LogTrackerStub; import com.paypal.observability.AbstractObservabilityIntegrationTest; import com.paypal.observability.startupchecks.model.StartupCheckPrinterRegistry; import com.paypal.observability.startupchecks.model.StartupCheckProvider; import com.paypal.observability.startupchecks.service.StartupCheckerService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.event.ContextRefreshedEvent; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; class StartupChecksITTest extends AbstractObservabilityIntegrationTest { @Autowired private ApplicationContext applicationContext; @Autowired private ApplicationEventPublisher publisher; @SpyBean private MyStartupCheckerService startupCheckerService; @RegisterExtension final LogTrackerStub logTrackerStub = LogTrackerStub.create().recordForType(StartupCheckerService.class); @BeforeEach void disableAutomaticShutdown() { startupCheckerService.setStartupChecksExitOnFail(false); } @Test void shouldDoStartupCheckTest_AfterApplicationStarts_WhenEnabled() { additionalFieldsMockServerFixtures.mockGetAdditionalFields_emptySchema(); startupCheckerService.setStartupChecksEnabled(true); publisher.publishEvent(new ContextRefreshedEvent(applicationContext)); verify(startupCheckerService, atLeastOnce()).doStartupChecks(); } @Test void shouldShutdownApplication_AfterApplicationStarts_WhenChecksAreNotOk() { additionalFieldsMockServerFixtures.mockGetAdditionalFields_emptySchema(); startupCheckerService.setStartupChecksEnabled(true); publisher.publishEvent(new ContextRefreshedEvent(applicationContext)); verify(startupCheckerService, atLeastOnce()).doStartupChecks(); verify(startupCheckerService, atLeastOnce()).shutdownSpringApplication(); } @Test void shouldNotShutdownApplication_AfterApplicationStarts_WhenChecksOk() { additionalFieldsMockServerFixtures.mockGetAdditionalFields_kyc_correct(); startupCheckerService.setStartupChecksEnabled(true); publisher.publishEvent(new ContextRefreshedEvent(applicationContext)); verify(startupCheckerService, atLeastOnce()).doStartupChecks(); verify(startupCheckerService, times(0)).shutdownSpringApplication(); } @Test void shouldNotShutdownApplication_AfterApplicationStarts_WhenChecksOkWithWarns() { additionalFieldsMockServerFixtures.mockGetAdditionalFields_kyc_correctWithWarnings(); startupCheckerService.setStartupChecksEnabled(true); publisher.publishEvent(new ContextRefreshedEvent(applicationContext)); verify(startupCheckerService, atLeastOnce()).doStartupChecks(); verify(startupCheckerService, times(0)).shutdownSpringApplication(); } @Test void shouldNotShutdownApplication_AfterApplicationStarts_WhenChecksFails() { additionalFieldsMockServerFixtures.mockGetAdditionalFields_internalServerError(); startupCheckerService.setStartupChecksEnabled(true); publisher.publishEvent(new ContextRefreshedEvent(applicationContext)); verify(startupCheckerService, atLeastOnce()).doStartupChecks(); verify(startupCheckerService, times(0)).shutdownSpringApplication(); } @Test void shouldTriggerAllChecks_AfterApplicationStarts_WhenEnabled() { additionalFieldsMockServerFixtures.mockGetAdditionalFields_emptySchema(); startupCheckerService.setStartupChecksEnabled(true); publisher.publishEvent(new ContextRefreshedEvent(applicationContext)); assertThat(logTrackerStub.contains("Startup Check: <miraklCustomFieldsSchemaCheck>")).isTrue(); assertThat(logTrackerStub.contains("Startup Check: <miraklDocSchemaCheck>")).isTrue(); assertThat(logTrackerStub.contains("Startup Check: <miraklHealthCheck>")).isTrue(); assertThat(logTrackerStub.contains("Startup Check: <hyperwalletHealthCheck>")).isTrue(); } @Test void shouldShowReport_AfterApplicationStarts_WhenEverythingIsOK() { additionalFieldsMockServerFixtures.mockGetAdditionalFields_kyc_correct(); healthMockServerFixtures.mockGetVersion_up(); hyperwalletHealthMockServerFixtures.mockGetHealth_up(); docsMockServerFixtures.mockGetDocsConfiguration_correctSchemaResponse(); startupCheckerService.setStartupChecksEnabled(true); publisher.publishEvent(new ContextRefreshedEvent(applicationContext)); assertThat(logTrackerStub.contains("Startup Check Report -> Status: <READY>")).isTrue(); assertThat(logTrackerStub.contains(StartupCheckerService.LOGMSG_STATUS_READY)).isTrue(); } @Test void shouldShowReport_AfterApplicationStarts_WhenThereAreWarnings() { additionalFieldsMockServerFixtures.mockGetAdditionalFields_kyc_correctWithWarnings(); docsMockServerFixtures.mockGetDocsConfiguration_correctSchemaResponse(); startupCheckerService.setStartupChecksEnabled(true); publisher.publishEvent(new ContextRefreshedEvent(applicationContext)); assertThat(logTrackerStub.contains("Startup Check Report -> Status: <READY_WITH_WARNINGS>")).isTrue(); assertThat(logTrackerStub.contains(StartupCheckerService.LOGMSG_STATUS_READY_WITH_WARNINGS)).isTrue(); } @Test void shouldShowReport_AfterApplicationStarts_WhenThereAreFails() { additionalFieldsMockServerFixtures.mockGetAdditionalFields_emptySchema(); startupCheckerService.setStartupChecksEnabled(true); publisher.publishEvent(new ContextRefreshedEvent(applicationContext)); assertThat(logTrackerStub.contains("Startup Check Report -> Status: <NOT_READY>")).isTrue(); assertThat(logTrackerStub.contains(StartupCheckerService.LOGMSG_STATUS_NOT_READY)).isTrue(); } @Test void shouldShowReport_AfterApplicationStart_WhenUnexpectedErrorsOccursWhileChecking() { additionalFieldsMockServerFixtures.mockGetAdditionalFields_internalServerError(); startupCheckerService.setStartupChecksEnabled(true); publisher.publishEvent(new ContextRefreshedEvent(applicationContext)); assertThat(logTrackerStub.contains("Startup Check Report -> Status: <UNKNOWN>")).isTrue(); assertThat(logTrackerStub.contains(StartupCheckerService.LOGMSG_STATUS_UNKNOWN)).isTrue(); } @Qualifier("startupCheckerService") static class MyStartupCheckerService extends StartupCheckerService { public MyStartupCheckerService(final List<StartupCheckProvider> startupCheckProviders, final StartupCheckPrinterRegistry startupCheckPrinterRegistry, final ConfigurableApplicationContext applicationContext) { super(startupCheckProviders, startupCheckPrinterRegistry, applicationContext); } @Override protected void doStartupChecks() { super.doStartupChecks(); } @Override protected void shutdownSpringApplication() { super.shutdownSpringApplication(); } public void setStartupChecksEnabled(final boolean startupChecksEnabled) { this.startupChecksEnabled = startupChecksEnabled; } public void setStartupChecksExitOnFail(final boolean startupChecksExitOnFail) { this.startupChecksExitOnFail = startupChecksExitOnFail; } } }
5,596
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/mirakldocschecks/MiraklDocSchemaChecksITTest.java
package com.paypal.observability.mirakldocschecks; import com.paypal.observability.AbstractObservabilityIntegrationTest; import com.paypal.observability.mirakldocschecks.services.MiraklDocSchemaCheckerService; import com.paypal.observability.miraklschemadiffs.model.diff.MiraklSchemaDiffEntryType; import com.paypal.observability.miraklschemadiffs.model.report.MiraklSchemaDiffReport; import com.paypal.observability.testsupport.MiraklSchemaAssertions; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; class MiraklDocSchemaChecksITTest extends AbstractObservabilityIntegrationTest { @Value("${hmc.toggle-features.automated-kyc}") private boolean originalIsKycAutomated; @Autowired private MiraklDocSchemaCheckerService miraklDocSchemaCheckerService; @BeforeEach void setupKycAutomatedStatus() { setKycAutomated(true); } @AfterEach void resetKycAutomatedStatus() { setKycAutomated(originalIsKycAutomated); } @Test void shouldCheckAllDocuments() { docsMockServerFixtures.mockGetDocsConfiguration_correctSchemaResponse(); final MiraklSchemaDiffReport diffReport = miraklDocSchemaCheckerService.checkMiraklDocs(); assertThat(diffReport.hasEntries()).isFalse(); } @Test void shouldNotCheckDocumentsWhenKycIsDeactivated() { docsMockServerFixtures.mockGetDocsConfiguration_emptyResponse(); setKycAutomated(false); final MiraklSchemaDiffReport diffReport = miraklDocSchemaCheckerService.checkMiraklDocs(); assertThat(diffReport.hasEntries()).isFalse(); } @Test void shouldDetectAdditionalDocs() { docsMockServerFixtures.mockGetDocsConfiguration_additionalDoc(); final MiraklSchemaDiffReport diffReport = miraklDocSchemaCheckerService.checkMiraklDocs(); assertThat(diffReport.getDiffs()).hasSize(1); MiraklSchemaAssertions.assertThatContainsEntry(diffReport, MiraklSchemaDiffEntryType.UNEXPECTED_ITEM, "hw-unexpected-doc-1"); } @Test void shouldDetectNotFoundDocs() { docsMockServerFixtures.mockGetDocsConfiguration_notFoundDoc(); final MiraklSchemaDiffReport diffReport = miraklDocSchemaCheckerService.checkMiraklDocs(); assertThat(diffReport.getDiffs()).hasSize(1); MiraklSchemaAssertions.assertThatContainsEntry(diffReport, MiraklSchemaDiffEntryType.ITEM_NOT_FOUND, "hw-bsh5-proof-identity-back"); } @Test void shouldDetectIncorrectLabel() { docsMockServerFixtures.mockGetDocsConfiguration_incorrectLabel(); final MiraklSchemaDiffReport diffReport = miraklDocSchemaCheckerService.checkMiraklDocs(); assertThat(diffReport.getDiffs()).hasSize(1); MiraklSchemaAssertions.assertThatContainsEntry(diffReport, MiraklSchemaDiffEntryType.INCORRECT_ATTRIBUTE_VALUE, "hw-bsh5-proof-identity-back"); } @Test void shouldDetectIncorrectDescription() { docsMockServerFixtures.mockGetDocsConfiguration_incorrectDescription(); final MiraklSchemaDiffReport diffReport = miraklDocSchemaCheckerService.checkMiraklDocs(); assertThat(diffReport.getDiffs()).hasSize(1); MiraklSchemaAssertions.assertThatContainsEntry(diffReport, MiraklSchemaDiffEntryType.INCORRECT_ATTRIBUTE_VALUE, "hw-bsh5-proof-identity-back"); } @Test void shouldDetectMultipleDiffs() { docsMockServerFixtures.mockGetDocsConfiguration_mutipleDiffs(); final MiraklSchemaDiffReport diffReport = miraklDocSchemaCheckerService.checkMiraklDocs(); assertThat(diffReport.getDiffs()).hasSize(4); MiraklSchemaAssertions.assertThatContainsEntry(diffReport, MiraklSchemaDiffEntryType.UNEXPECTED_ITEM, "hw-bsh5-proof-identity-back-CHANGED"); MiraklSchemaAssertions.assertThatContainsEntry(diffReport, MiraklSchemaDiffEntryType.ITEM_NOT_FOUND, "hw-bsh5-proof-identity-back"); MiraklSchemaAssertions.assertThatContainsEntry(diffReport, MiraklSchemaDiffEntryType.INCORRECT_ATTRIBUTE_VALUE, "hw-bsh5-proof-identity-front"); MiraklSchemaAssertions.assertThatContainsEntry(diffReport, MiraklSchemaDiffEntryType.INCORRECT_ATTRIBUTE_VALUE, "hw-bsh5-proof-identity-front"); } private void setKycAutomated(final boolean isKycAutomated) { ReflectionTestUtils.setField(miraklDocSchemaCheckerService, "isKycAutomated", isKycAutomated); } }
5,597
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/mirakldocschecks/MiraklDocSchemaStartupAdapterITTest.java
package com.paypal.observability.mirakldocschecks; import com.paypal.observability.AbstractObservabilityIntegrationTest; import com.paypal.observability.mirakldocschecks.startup.MiraklDocSchemaStartupCheckPrinter; import com.paypal.observability.mirakldocschecks.startup.MiraklDocSchemaStartupCheckProvider; import com.paypal.observability.startupchecks.model.StartupCheck; import com.paypal.observability.startupchecks.model.StartupCheckStatus; import com.paypal.observability.testsupport.MiraklReportAssertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import static org.assertj.core.api.Assertions.assertThat; class MiraklDocSchemaStartupAdapterITTest extends AbstractObservabilityIntegrationTest { @Autowired private MiraklDocSchemaStartupCheckProvider miraklDocSchemaStartupCheckProvider; @Autowired private MiraklDocSchemaStartupCheckPrinter miraklDocSchemaStartupCheckPrinter; @Test void shouldCheckAndReturnReadyStatusWhenAllItsOK() { docsMockServerFixtures.mockGetDocsConfiguration_correctSchemaResponse(); final StartupCheck startupCheck = miraklDocSchemaStartupCheckProvider.check(); assertThat(startupCheck.getStatus()).isEqualTo(StartupCheckStatus.READY); assertThat(startupCheck.getStatusMessage()).contains("The current schema in Mirakl is the expected one."); final String[] report = miraklDocSchemaStartupCheckPrinter.print(startupCheck); assertThat(report).isEmpty(); } @Test void shouldCheckAndReturnReadyWithWarningsStatusWhenThereAreWarnings() { docsMockServerFixtures.mockGetDocsConfiguration_withWarnings(); final StartupCheck startupCheck = miraklDocSchemaStartupCheckProvider.check(); assertThat(startupCheck.getStatus()).isEqualTo(StartupCheckStatus.READY_WITH_WARNINGS); assertThat(startupCheck.getStatusMessage()).contains( "The current schema in Mirakl server is compatible with this version of HMC although there are some differences that are recommended to be solved."); final String[] report = miraklDocSchemaStartupCheckPrinter.print(startupCheck); assertThat(report).hasSize(3); MiraklReportAssertions.assertThatContainsMessage(report, "Property 'label' doesn't have the correct value"); MiraklReportAssertions.assertThatContainsMessage(report, "Property 'description' doesn't have the correct value"); MiraklReportAssertions.assertThatContainsSetMessage(report, "An unexpected field named 'hw-bsh4-proof-identity-back-unexpected' has been found"); } @Test void shouldCheckAndReturnNotReadyWhenThereAreFails() { docsMockServerFixtures.mockGetDocsConfiguration_mutipleDiffs(); final StartupCheck startupCheck = miraklDocSchemaStartupCheckProvider.check(); assertThat(startupCheck.getStatus()).isEqualTo(StartupCheckStatus.NOT_READY); assertThat(startupCheck.getStatusMessage()) .contains("The current schema in Mirakl server is not compatible with this version of HMC."); final String[] report = miraklDocSchemaStartupCheckPrinter.print(startupCheck); assertThat(report).hasSize(4); MiraklReportAssertions.assertThatContainsMessage(report, "Property 'label' doesn't have the correct value"); MiraklReportAssertions.assertThatContainsMessage(report, "Property 'description' doesn't have the correct value"); MiraklReportAssertions.assertThatContainsSetMessage(report, "Expected field 'hw-bsh5-proof-identity-back' has not been found"); MiraklReportAssertions.assertThatContainsSetMessage(report, "An unexpected field named 'hw-bsh5-proof-identity-back-CHANGED' has been found"); } }
5,598
0
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability
Create_ds/mirakl-hyperwallet-connector/hmc-observability/src/integrationTest/java/com/paypal/observability/hyperwalletapichecks/HyperwalletAPIChecksStartupAdapterITTest.java
package com.paypal.observability.hyperwalletapichecks; import com.paypal.observability.AbstractObservabilityIntegrationTest; import com.paypal.observability.hyperwalletapichecks.startup.HyperwalletHealthCheckStartupCheckPrinter; import com.paypal.observability.hyperwalletapichecks.startup.HyperwalletHealthCheckStartupProvider; import com.paypal.observability.startupchecks.model.StartupCheck; import com.paypal.observability.startupchecks.model.StartupCheckStatus; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import static org.assertj.core.api.Assertions.assertThat; class HyperwalletAPIChecksStartupAdapterITTest extends AbstractObservabilityIntegrationTest { @Autowired private HyperwalletHealthCheckStartupProvider hyperwalletHealthCheckStartupProvider; @Autowired private HyperwalletHealthCheckStartupCheckPrinter hyperwalletHealthCheckStartupCheckPrinter; @Test void shouldCheckAndReturnReadyStatusWhenAllItsOK() { hyperwalletHealthMockServerFixtures.mockGetHealth_up(); final StartupCheck startupCheck = hyperwalletHealthCheckStartupProvider.check(); final String[] startupCheckReport = hyperwalletHealthCheckStartupCheckPrinter.print(startupCheck); assertThat(startupCheck.getStatus()).isEqualTo(StartupCheckStatus.READY); //@formatter:off assertThat(startupCheckReport[0]).contains("Hyperwallet API is accessible") .contains("status: UP") .contains("location: http://localhost"); //@formatter:on } @Test void shouldCheckAndReturnReadyWithWarningsStatusWhenAllItsOK() { hyperwalletHealthMockServerFixtures.mockGetHealth_down(); final StartupCheck startupCheck = hyperwalletHealthCheckStartupProvider.check(); final String[] startupCheckReport = hyperwalletHealthCheckStartupCheckPrinter.print(startupCheck); assertThat(startupCheck.getStatus()).isEqualTo(StartupCheckStatus.READY_WITH_WARNINGS); //@formatter:off assertThat(startupCheckReport[0]).contains("Hyperwallet API is not accessible") .contains("status: DOWN") .contains("error: Error message") .contains("location: http://localhost"); //@formatter:on } }
5,599