Picker.java 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package org.dbsyncer.parser.model;
  2. import org.dbsyncer.common.util.CollectionUtils;
  3. import org.dbsyncer.connector.config.ConnectorConfig;
  4. import org.dbsyncer.connector.model.Field;
  5. import org.springframework.util.Assert;
  6. import java.util.ArrayList;
  7. import java.util.HashMap;
  8. import java.util.List;
  9. import java.util.Map;
  10. import java.util.stream.Collectors;
  11. public class Picker {
  12. private List<Field> sourceFields;
  13. private List<Field> targetFields;
  14. public Picker(List<FieldMapping> fieldMapping) {
  15. sourceFields = new ArrayList<>();
  16. targetFields = new ArrayList<>();
  17. if (!CollectionUtils.isEmpty(fieldMapping)) {
  18. fieldMapping.forEach(m -> {
  19. sourceFields.add(m.getSource());
  20. targetFields.add(m.getTarget());
  21. });
  22. }
  23. }
  24. public List<Map> pickData(List<Map> data) {
  25. List<Map> targetMapList = new ArrayList<>();
  26. if (!CollectionUtils.isEmpty(data)) {
  27. final int size = data.size();
  28. final int sFieldSize = sourceFields.size();
  29. Map<String, Object> target = null;
  30. for (int i = 0; i < size; i++) {
  31. target = new HashMap<>();
  32. exchange(sFieldSize, sourceFields, targetFields, data.get(i), target);
  33. targetMapList.add(target);
  34. }
  35. }
  36. return targetMapList;
  37. }
  38. private void exchange(int sFieldSize, List<Field> sFields, List<Field> tFields, Map<String, Object> source,
  39. Map<String, Object> target) {
  40. Field sField = null;
  41. Field tField = null;
  42. Object v = null;
  43. for (int k = 0; k < sFieldSize; k++) {
  44. sField = sFields.get(k);
  45. tField = tFields.get(k);
  46. if (null != sField && null != tField) {
  47. v = source.get(sField.isUnmodifiabled() ? sField.getLabelName() : sField.getName());
  48. target.put(tField.getName(), v);
  49. }
  50. }
  51. }
  52. public String getSourcePrimaryKeyName(ConnectorConfig config) {
  53. for (Field f : sourceFields) {
  54. if (null != f && f.isPk()) {
  55. return f.getName();
  56. }
  57. }
  58. String primaryKey = config.getPrimaryKey();
  59. Assert.hasText(primaryKey, "主键为空");
  60. return primaryKey;
  61. }
  62. public List<Field> getSourceFields() {
  63. return sourceFields.stream().filter(f -> null != f).collect(Collectors.toList());
  64. }
  65. public List<Field> getTargetFields() {
  66. return targetFields.stream().filter(f -> null != f).collect(Collectors.toList());
  67. }
  68. public Map<String, Field> getSourceFieldMap() {
  69. return getSourceFields().stream().collect(Collectors.toMap(Field::getName, f -> f, (k1, k2) -> k1));
  70. }
  71. }