diff --git a/clearing-parent/imdg/pom.xml b/clearing-parent/imdg/pom.xml index c0db709b4..5a35a391a 100644 --- a/clearing-parent/imdg/pom.xml +++ b/clearing-parent/imdg/pom.xml @@ -1,17 +1,17 @@ - - 4.0.0 + 4.0.0 imdg Clearing in memory data grid jar SPCEX-1.0.0.0 - - clearing-parent - ru.spcex.clearing + + clearing-parent + ru.spcex.clearing SPCEX-1.0.0.0 @@ -74,8 +74,23 @@ - org.testng - testng + org.springframework + spring-test + test + + + org.skyscreamer + jsonassert + test + + + org.junit.jupiter + junit-jupiter + test + + + org.assertj + assertj-core test @@ -117,6 +132,23 @@ ${project.artifactId} + + org.apache.maven.plugins + maven-surefire-plugin + 2.21.0 + + + org.junit.platform + junit-platform-surefire-provider + 1.2.0-M1 + + + org.junit.jupiter + junit-jupiter-engine + 5.2.0-M1 + + + \ No newline at end of file diff --git a/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/AllMapStoreTest.java b/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/AllMapStoreTest.java new file mode 100644 index 000000000..ec72032fe --- /dev/null +++ b/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/AllMapStoreTest.java @@ -0,0 +1,73 @@ +package ru.spcex.clearing.imdg; + +import com.hazelcast.core.IMap; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import ru.spcex.clearing.imdg.config.DbTestConnectionConfig; +import ru.spcex.clearing.imdg.config.TestConfiguration; +import ru.spcex.clearing.imdg.structure.ObjectForCheckMapStore; +import ru.spcex.clearing.imdg.utils.DbDataUtils; +import ru.spcex.platform.classes.base.SpcexObjectBase; + +import javax.annotation.PostConstruct; +import java.lang.reflect.InvocationTargetException; + +import static ru.spcex.clearing.imdg.structure.GeneratorMapNamesForHazelcast.objectForCheckMapStores; + +@ContextConfiguration(classes = { + TestConfiguration.class, + DbTestConnectionConfig.class}) +@ExtendWith(SpringExtension.class) +@TestPropertySource(properties = "spring.config.location=D:/repo/mfd/clearing/clearing-parent/imdg/src/main/resources") +public class AllMapStoreTest { + private static final Long ID = 1000000L; + private final Logger log = LoggerFactory.getLogger(this.getClass()); + @Autowired + TestConfiguration testConfig; + + @PostConstruct + public void initTestObjects() { + try { + for (ObjectForCheckMapStore objectForCheck : objectForCheckMapStores) { + SpcexObjectBase object = objectForCheck.getClazz().getDeclaredConstructor().newInstance(); + DbDataUtils.fillObjectDefaultValues(object, object.getClass()); + objectForCheck.setPredictableObj(object); + } + } catch (InstantiationException | IllegalAccessException e) { + log.error(e.getMessage()); + } catch (InvocationTargetException | NoSuchMethodException e) { + throw new RuntimeException(e); + } + } + + @Test + public void storeAllTest() { + saveObjectToMaps(); + testConfig.shutDownHazelcast(); + testConfig.reinitHazlecastInstance(); + + for (ObjectForCheckMapStore objectForCheck : objectForCheckMapStores) { + SpcexObjectBase object = objectForCheck.getPredictableObj(); + IMap map = testConfig.getHazelcastInstance().getMap(objectForCheck.getMapName()); + SpcexObjectBase actual = map.get(ID); + objectForCheck.getMATCHER().assertMatch(actual, objectForCheck.getPredictableObj()); + } + } + + private void saveObjectToMaps() { + for (ObjectForCheckMapStore objectForCheck : objectForCheckMapStores) { + String mapName = objectForCheck.getMapName(); + IMap map = testConfig.getHazelcastInstance().getMap(mapName); + SpcexObjectBase spcexObjectBase = objectForCheck.getPredictableObj(); + spcexObjectBase.setId(ID); + log.info("Запись в мап {} объекта {}", mapName, spcexObjectBase); + map.put(spcexObjectBase.getId(), spcexObjectBase); + } + } +} \ No newline at end of file diff --git a/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/config/DbTestConnectionConfig.java b/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/config/DbTestConnectionConfig.java new file mode 100644 index 000000000..51fbc8e3b --- /dev/null +++ b/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/config/DbTestConnectionConfig.java @@ -0,0 +1,66 @@ +package ru.spcex.clearing.imdg.config; + +import com.mchange.v2.c3p0.ComboPooledDataSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.core.JdbcTemplate; +import ru.spcex.clearing.imdg.error.ModuleInitializeException; + +import javax.sql.DataSource; +import java.sql.Connection; + +@SuppressWarnings("UnnecessaryLocalVariable") +@Configuration +public class DbTestConnectionConfig { + private final Logger log = LoggerFactory.getLogger(this.getClass()); + + private ConfigurationRootElement configRoot = DfaConfig.get().getRoot(); + + @Bean + public DataSource dataSource() { + DataSource result; + String login = "clearing"; + String password = "Aa111111"; + String logTimeoutPart = ""; + String dbPath = "jdbc:postgresql://10.200.200.133:5432/postgres"; + int timeoutSec = configRoot.getDatabase().getConnectionAcquireTimeoutSeconds(); + + ComboPooledDataSource cpds = new ComboPooledDataSource(); + try { + cpds.setDriverClass("org.postgresql.Driver"); + } catch (Exception ue) { + throw new RuntimeException(ue); + } + cpds.setJdbcUrl(dbPath); + cpds.setUser(login); + cpds.setPassword(password); + cpds.setInitialPoolSize(configRoot.getDatabase().getMinPoolSize()); + cpds.setMinPoolSize(configRoot.getDatabase().getMinPoolSize()); + cpds.setMaxPoolSize(configRoot.getDatabase().getMaxPoolSize()); + cpds.setNumHelperThreads(configRoot.getDatabase().getNumHelperThreads()); + cpds.setCheckoutTimeout(timeoutSec * 1000/*todo common 1000==ConstsCommon.SECOND*/); + logTimeoutPart = String.format(" (timeout=%ds)", timeoutSec); + result = cpds; + + String OPERATION_DATABASE_CONNECTION_CHECK = String.format("Database [%s] connection check", dbPath); + try { + Connection conn = result.getConnection(); + conn.close(); + log.info("{}: success", OPERATION_DATABASE_CONNECTION_CHECK); + return result; + } catch (Throwable e) { + String msg = String.format("%s%s: failed: %s -> %s", + OPERATION_DATABASE_CONNECTION_CHECK, logTimeoutPart, e.getClass().getSimpleName(), e.getMessage()); + log.error(msg); + throw new ModuleInitializeException(msg, e); + } + } + + @Bean + public JdbcTemplate jdbcTemplate(DataSource dataSource) { + JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); + return jdbcTemplate; + } +} diff --git a/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/config/TestConfiguration.java b/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/config/TestConfiguration.java new file mode 100644 index 000000000..39c46e355 --- /dev/null +++ b/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/config/TestConfiguration.java @@ -0,0 +1,51 @@ +package ru.spcex.clearing.imdg.config; + +import com.hazelcast.config.Config; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + +@Configuration +@Import({HazelcastConfiguration.class, PoolMapConfigs.class}) +@ComponentScan(basePackages = {"ru.spcex.clearing.imdg"}) +public class TestConfiguration { + private final Logger log = LoggerFactory.getLogger(this.getClass()); + @Autowired + private HazelcastInstance hazelcastInstance; + + @Autowired + private Config hazelcastConfig; + + public void shutDownHazelcast() { + if (hazelcastInstance != null) { + hazelcastInstance.getLifecycleService().shutdown(); + + while (hazelcastInstance.getLifecycleService().isRunning()) { + try { + Thread.sleep(1000); + log.info("Waiting to complete hazelCast"); + } catch (InterruptedException e) { + log.warn("Test at ShutDownHazelcast(): thread interrupted {}", e); + } + } + } + hazelcastInstance = null; + } + + public void reinitHazlecastInstance() { + hazelcastInstance = Hazelcast.getOrCreateHazelcastInstance(hazelcastConfig); + } + + public Config getHazelcastConfig() { + return hazelcastConfig; + } + + public HazelcastInstance getHazelcastInstance() { + return hazelcastInstance; + } +} diff --git a/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/structure/GeneratorMapNamesForHazelcast.java b/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/structure/GeneratorMapNamesForHazelcast.java new file mode 100644 index 000000000..642076a33 --- /dev/null +++ b/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/structure/GeneratorMapNamesForHazelcast.java @@ -0,0 +1,43 @@ +package ru.spcex.clearing.imdg.structure; + +import ru.clearing.classes.statics.data.account.Account; +import ru.spcex.clearing.imdg.IMDGDistributedNames; + +import java.util.*; + +public class GeneratorMapNamesForHazelcast { + public static Map mapStoreNameByClass; + public static List objectForCheckMapStores; + + static { + init(); + mapStoreNameByClass = createMapStoreNameByClass(); + } + + private static void init() { + objectForCheckMapStores = new LinkedList<>(); + + objectForCheckMapStores.add(new ObjectForCheckMapStore(IMDGDistributedNames.Map_Account, Account.class)); + } + + public static Map createClassByMapStoreName() { + return Collections.unmodifiableMap( + new HashMap() {{ + objectForCheckMapStores.forEach(objectForCheckMapStore -> { + put(objectForCheckMapStore.getMapName(), objectForCheckMapStore.getClazz()); + }); + }} + ); + } + + public static Map createMapStoreNameByClass() { + return Collections.unmodifiableMap( + new HashMap() {{ + objectForCheckMapStores.forEach(objectForCheckMapStore -> { + put(objectForCheckMapStore.getClazz(), objectForCheckMapStore.getMapName()); + }); + }} + ); + } + +} diff --git a/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/structure/ObjectForCheckMapStore.java b/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/structure/ObjectForCheckMapStore.java new file mode 100644 index 000000000..b3aefd7ce --- /dev/null +++ b/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/structure/ObjectForCheckMapStore.java @@ -0,0 +1,41 @@ +package ru.spcex.clearing.imdg.structure; + + +import ru.spcex.clearing.imdg.utils.MatcherFactory.Matcher; +import ru.spcex.platform.classes.base.SpcexObjectBase; + +import static ru.spcex.clearing.imdg.utils.MatcherFactory.usingIgnoringFieldsComparator; + +public class ObjectForCheckMapStore { + + public final Matcher MATCHER = usingIgnoringFieldsComparator(); + private final String mapName; + private final Class clazz; + + private SpcexObjectBase predictableObj; + + public ObjectForCheckMapStore(String mapName, Class clazz) { + this.mapName = mapName; + this.clazz = clazz; + } + + public String getMapName() { + return mapName; + } + + public Class getClazz() { + return clazz; + } + + public Matcher getMATCHER() { + return MATCHER; + } + + public SpcexObjectBase getPredictableObj() { + return predictableObj; + } + + public void setPredictableObj(SpcexObjectBase predictableObj) { + this.predictableObj = predictableObj; + } +} diff --git a/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/utils/DbDataUtils.java b/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/utils/DbDataUtils.java new file mode 100644 index 000000000..c2197b92c --- /dev/null +++ b/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/utils/DbDataUtils.java @@ -0,0 +1,280 @@ +package ru.spcex.clearing.imdg.utils; + + +import com.hazelcast.config.Config; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.jdbc.core.JdbcTemplate; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.math.BigDecimal; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDate; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static ru.spcex.clearing.imdg.structure.GeneratorMapNamesForHazelcast.createClassByMapStoreName; +import static ru.spcex.clearing.imdg.structure.GeneratorMapNamesForHazelcast.createMapStoreNameByClass; + +/** + * Утилитарный класс для работы с embedded базой. + * Так же используется для заполнения значений классов для подготовки вставки в базу + */ +public final class DbDataUtils { + public final static Map classByMapStoreName = createClassByMapStoreName(); + public final static Map mapStoreNameByClass = createMapStoreNameByClass(); + private static final Logger log = LoggerFactory.getLogger(DbDataUtils.class); + /** + * Паттерн который проверяет что исполняемый скрипт пересоздает таблицу (recreate table * (*)) + */ + private final static Pattern PATTERN_CREATE_TABLE = Pattern.compile( + "(?m)(?i)^\\s*?(?:re)*(create\\s*?table\\s*?[^\\s$]+?\\s*?\\([\\S\\s]+?(?:\\);|^\\)\\s*?$))"); + private final static Pattern PATTERN_ALTER_TABLE = Pattern.compile( + "(?m)(?i)^\\s*?(alter\\s*?table\\s*?[^\\s$]+?\\s*?add\\s*?constraint\\s*?[^\\s$]+?\\s*?primary\\s*?key\\s*?\\([\\S\\s]+?(?:\\);|^\\)\\s*?$))"); + private final static Pattern PATTERN_UPDATE_OR_INSERT_TABLE = Pattern.compile( + "(?i)update\\s+\\w+\\s+set\\s+\\w+|update\\s+or\\s+insert\\s+into\\s+\\w+.*?values|insert\\s+into\\s+\\w+.*?values"); + private final static Pattern PATTERN_UPDATE_OR_INSERT_VERSIONDB = Pattern.compile( + "(?m)(?i)^\\s*?(update or insert into VERSIONEDID\\s*?[\\w\\s\\(\\,)]+\\s*values\\s*?[\\w\\s\\.'\\(\\,)]+matching\\s*?[\\w\\s,\\(\\)]+\\s*;)"); + private final static Pattern PATTERN_CHANGE_CREATE_TO_RECREATE = Pattern.compile( + "(?i)^\\s*?create"); + private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("ddMMyyyy"); + + /** + * Создавать объект этого типа нельзя + */ + private DbDataUtils() { + } + + /** + * Создает пустую базу по DDL скрипту (только таблицы), так же проверяет скрипты DDL на валидность. + */ + public static void executeAllDDL(List DDLs, JdbcTemplate jdbcTemplate) { + Logger log = LoggerFactory.getLogger(DbDataUtils.class); + log.info("Создание всех таблиц по DDL.sql"); + int executed = 0; + for (String dll : DDLs) { + executed += executeOneDDL(dll, jdbcTemplate); + } + log.info("Закончено создание таблиц... выполненых запросов {}", executed); + } + + public static int executeOneDDL(String ddl, JdbcTemplate jdbcTemplate) { + Logger log = LoggerFactory.getLogger(DbDataUtils.class); + Matcher m = PATTERN_CREATE_TABLE.matcher(ddl); +// Matcher alterMatcher = PATTERN_ALTER_TABLE.matcher(ddl); + List sqls = new ArrayList<>(); +// List alterSqls = new ArrayList<>(); + while (m.find()) { + String oneDDL = m.group(1); + Matcher mr = PATTERN_CHANGE_CREATE_TO_RECREATE.matcher(oneDDL); + oneDDL = mr.replaceAll("RECREATE"); + sqls.add(oneDDL); + } + +// while (alterMatcher.find()) { +// String oneDDL = alterMatcher.group(1); +// alterSqls.add(oneDDL); +// } + log.info("Exec batch"); + int[] result = jdbcTemplate.batchUpdate(sqls.toArray(new String[0])); +// int alterResult[] = jdbcTemplate.batchUpdate(alterSqls.toArray(new String[0])); + log.info("Batch sql done"); + + // Для проставления версии БД + int insertCount = 0; + Matcher versionM = PATTERN_UPDATE_OR_INSERT_VERSIONDB.matcher(ddl); + while (versionM.find()) { + String oneSQL = versionM.group(1); + jdbcTemplate.execute(oneSQL); + log.trace("Executed version SQL: {}", oneSQL); + insertCount++; + } + + return result.length + insertCount; + } + + public static void fillMandatorySqlData(Map mandatorySql, JdbcTemplate jdbcTemplate) { + Logger log = LoggerFactory.getLogger(DbDataUtils.class); + log.info("Заполнение базы общими значениями"); + fillSqlData(mandatorySql, jdbcTemplate); + } + + public static void fillAdditionalSqlData(Map additionalSql, JdbcTemplate jdbcTemplate) { + Logger log = LoggerFactory.getLogger(DbDataUtils.class); + log.info("Заполнение базы дополнительными значениями"); + fillSqlData(additionalSql, jdbcTemplate); + } + + public static void fillSqlData(Map sqlMap, JdbcTemplate jdbcTemplate) { + Logger log = LoggerFactory.getLogger(DbDataUtils.class); + for (Map.Entry sqlEntry : sqlMap.entrySet()) { + String sql = sqlEntry.getValue(); + String[] lines = sql.split("\n"); + List sqls = new ArrayList<>(); + for (String line : lines) { + if (StringUtils.isEmpty(line) || StringUtils.isWhitespace(line)) + continue; + String execLine = line.trim(); + if (!execLine.endsWith(";")) + execLine += ";"; + Matcher updateOrInsertMatcher = PATTERN_UPDATE_OR_INSERT_TABLE.matcher(execLine); + if (updateOrInsertMatcher.find()) { + execLine = execLine.replaceAll("(?i)update\\s+or\\s+insert\\s*", "insert "); + log.info("Скрипт {}", execLine); + sqls.add(execLine); + } + } + log.info("Exec batch"); + int[] result = jdbcTemplate.batchUpdate(sqls.toArray(new String[0])); + log.info("Batch sql done"); + } + log.info("Заполнение базы значениями завершено"); + + } + + private static void fillObjectDefaultValues(Object object) { + fillObjectDefaultValues(object, object.getClass()); + for (Field field : object.getClass().getDeclaredFields()) { + if (!Modifier.isFinal(field.getModifiers())) { + field.setAccessible(true); + setFieldDefaultValue(field, object); + } + } + } + + public static void fillObjectDefaultValues(Object object, Class clazz) { + if (!clazz.getSuperclass().getName().equals(Object.class.getName())) { + fillObjectDefaultValues(object, clazz.getSuperclass()); + } + for (Field field : clazz.getDeclaredFields()) { + if (!Modifier.isFinal(field.getModifiers()) && !Modifier.isStatic(field.getModifiers())) { + field.setAccessible(true); + setFieldDefaultValue(field, object); + } + } + } + + public static void getObjectsFieldValues(Object object, Map values, boolean deepScan) throws IllegalAccessException { + if (!object.getClass().getSuperclass().getName().equals(Object.class.getName())) { + log.trace("Scan values of {}", object.getClass().getName()); + getObjectsFieldValues(object.getClass().getSuperclass(), values, deepScan); + for (Field field : object.getClass().getDeclaredFields()) { + if (!Modifier.isFinal(field.getModifiers())) { + field.setAccessible(true); + Object value = field.get(object); + values.put(field, value); + if (deepScan && isBusinessObject(value)) { // пройти внутрь наших классов + getObjectsFieldValues(value, values, deepScan); // go to deeper + } + } + } + } + } + + /** + * Это наш класс и не примитив + * + * @param value объект, возможно otc-объект. + * @return нужно ли применять deepScan + */ + private static boolean isBusinessObject(Object value) { + String classesClassPathPrefix = "ru.clearing.classes.objects"; + return value != null && value.getClass().getName().startsWith(classesClassPathPrefix); + } + + private static void setFieldDefaultValue(Field field, Object object) { + Logger log = LoggerFactory.getLogger(DbDataUtils.class); + Class typeField = field.getType(); + try { + if (typeField.getName().equals(String.class.getName())) { + field.set(object, "qwer"); + } else if (typeField.equals(Integer.TYPE) || typeField.equals(Integer.class)) { + field.set(object, 0); + } else if (typeField.getName().equals(BigDecimal.class.getName())) { + field.set(object, BigDecimal.valueOf(23.22)); + } else if (typeField.equals(Long.TYPE) || typeField.equals(Long.class)) { + field.set(object, 0L); + } else if (typeField.equals(LocalDate.class)) { + field.set(object, LocalDate.of(2017, 11, 11)); + } else if (typeField.getName().equals(Date.class.getName())) { + field.set(object, new Date()); + } else if (typeField.getName().equals(Boolean.class.getName())) { + field.set(object, true); + } else if (typeField.getName().equals(UUID.class.getName())) { + field.set(object, UUID.randomUUID()); + } else if (typeField.getName().equals(Instant.class.getName())) { + field.set(object, Instant.parse("2022-10-05T15:39:18.659Z")); +// } else if (typeField.getSimpleName().equals(BusinessObjectRef.class.getSimpleName())) { +// field.set(object, BusinessObjectRef.createFromId(0L, BusinessObject.class)); +// } else if (typeField.getName().equals(Set.class.getName())) { +// Set hashSet = new HashSet<>(); +// hashSet.add(BusinessObjectRef.createFromId(0L, BusinessObject.class)); +// field.set(object, hashSet); +// } else if (typeField.getName().equals(Instant.class.getName())) { +// field.set(object, Instant.now()); +// } else if (typeField.getName().equals(Party.class.getName())) { +// Party party = new Party(); +// fillObjectDefaultValues(party, party.getClass()); +// field.set(object, party); +// } else if (typeField.getName().equals(LegalEntityProfile.class.getName())) { +// LegalEntityProfile legalEntityProfile = new LegalEntityProfile(); +// fillObjectDefaultValues(legalEntityProfile, legalEntityProfile.getClass()); +// legalEntityProfile.setId(1L); +// field.set(object, legalEntityProfile); + } else { + if (Collection.class.isAssignableFrom(field.getType())) { + // ignore List, Set, etc. + log.debug("Any collection variable skipped: {}", field.getName()); + } else if (typeField.getName().equalsIgnoreCase("[Z") && field.getName().equalsIgnoreCase("$jacocoData")) { // Массив объектов в переменной $jacocoData + log.debug("Jacoco debug variable skipped: {}", field.getName()); + } else { + log.error("Для данного поля (в объекте " + object.getClass().getName() + "->" + field.getName() + ") значение по умолчению не может быть определенно для типа: " + typeField.getName()); + throw new RuntimeException(); + } + } + } catch (IllegalAccessException e) { + log.info(e.getMessage()); + } + } + + public static void setFieldDefaultValue(Field field, Object object, String value) { + Logger log = LoggerFactory.getLogger(DbDataUtils.class); + if (value == null || value.equals("null")) + return; + Class typeField = field.getType(); + try { + if (typeField.getName().equals(String.class.getName())) { + field.set(object, value); + } else if (typeField.equals(Integer.TYPE) || typeField.equals(Integer.class)) { + field.set(object, Integer.valueOf(value)); + } else if (typeField.getName().equals(BigDecimal.class.getName())) { + field.set(object, new BigDecimal(value)); + } else if (typeField.equals(Long.TYPE) || typeField.equals(Long.class)) { + field.set(object, Long.valueOf(value)); + } else if (typeField.getName().equals(Date.class.getName())) { + field.set(object, SIMPLE_DATE_FORMAT.parse(value)); + } else if (typeField.getName().equals(Boolean.class.getName())) { + field.set(object, Boolean.valueOf(value)); + } + } catch (IllegalAccessException e) { + log.info(e.getMessage()); + } catch (ParseException e) { + e.printStackTrace(); + } + } + + public static List> setImplementsClasses(Config hazelcastConfig) { + List> mapStoreClasses = new ArrayList<>(); + for (String mapName : hazelcastConfig.getMapConfigs().keySet()) { + Class clazz = classByMapStoreName.get(mapName); + if (clazz != null) + mapStoreClasses.add(clazz); + } + return mapStoreClasses; + } +} diff --git a/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/utils/MatcherFactory.java b/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/utils/MatcherFactory.java new file mode 100644 index 000000000..e4f858eb6 --- /dev/null +++ b/clearing-parent/imdg/src/test/ru/spcex/clearing/imdg/utils/MatcherFactory.java @@ -0,0 +1,38 @@ +package ru.spcex.clearing.imdg.utils; + +import java.util.Arrays; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Factory for creating test matchers. + *

+ * Comparing actual and expected objects via AssertJ + */ +public class MatcherFactory { + + public static Matcher usingIgnoringFieldsComparator(String... fieldsToIgnore) { + return new Matcher<>(fieldsToIgnore); + } + + public static class Matcher { + private final String[] fieldsToIgnore; + + private Matcher(String... fieldsToIgnore) { + this.fieldsToIgnore = fieldsToIgnore; + } + + public void assertMatch(T actual, T expected) { + assertThat(actual).usingRecursiveComparison().ignoringFields(fieldsToIgnore).isEqualTo(expected); + } + + @SafeVarargs + public final void assertMatch(Iterable actual, T... expected) { + assertMatch(actual, Arrays.asList(expected)); + } + + public void assertMatch(Iterable actual, Iterable expected) { + assertThat(actual).usingRecursiveFieldByFieldElementComparatorIgnoringFields(fieldsToIgnore).isEqualTo(expected); + } + } +}