Implementati servizi base di retrieve delle sincronizzazioni attive

This commit is contained in:
2024-01-25 15:14:39 +01:00
parent eea5f9cb8b
commit df46ac1e93
23 changed files with 659 additions and 162 deletions

View File

@@ -1,4 +1,4 @@
package it.integry.ems.migration._base;
package it.integry.ems.migration.model._base;
import com.fasterxml.jackson.core.type.TypeReference;
import it.integry.ems.settings.Model.SettingsModel;
@@ -12,9 +12,7 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.context.ContextLoader;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;
public abstract class BaseMigration implements MigrationModelInterface {
@@ -33,8 +31,9 @@ public abstract class BaseMigration implements MigrationModelInterface {
this.droolsDataCompleting = droolsDataCompleting;
}
protected <R>R getContextBean(Class<R> clazz) {
TypeReference<R> type = new TypeReference<R>() {};
protected <R> R getContextBean(Class<R> clazz) {
TypeReference<R> type = new TypeReference<R>() {
};
return ContextLoader.getCurrentWebApplicationContext().getBean(clazz);
}
@@ -69,12 +68,24 @@ public abstract class BaseMigration implements MigrationModelInterface {
}
public void createTable(Connection connection, String sql) throws SQLException {
executeStatement(connection, sql);
protected long executeInsertStatement(Connection connection, String sql) throws SQLException {
long generatedId = -1;
try (PreparedStatement pstmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
int affectedRows = pstmt.executeUpdate();
if (affectedRows > 0) {
// get the ID back
try (ResultSet rs = pstmt.getGeneratedKeys()) {
if (rs.next()) {
generatedId = rs.getLong(1);
}
}
}
}
public void updateFunction(Connection connection, String sql) throws SQLException {
executeStatement(connection, sql);
return generatedId;
}
}

View File

@@ -0,0 +1,110 @@
package it.integry.ems.migration.model;
import it.integry.ems.migration.model._base.BaseMigration;
import it.integry.ems.migration.model._base.MigrationModelInterface;
import it.integry.ems_model.utility.Query;
import it.integry.ems_model.utility.UtilityDB;
import it.integry.ems_model.utility.UtilityHashMap;
import javax.validation.constraints.NotNull;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
public class Migration_20240124171059 extends BaseMigration implements MigrationModelInterface {
@Override
public void up() throws Exception {
if (isHistoryDB())
return;
String sql = "SELECT * FROM stb_publications";
final List<HashMap<String, Object>> oldStbPublications = UtilityDB.executeSimpleQuery(advancedDataSource.getConnection(), sql);
sql = "SELECT * FROM stb_publications_detail";
final List<HashMap<String, Object>> oldStbPublicationsDetails = UtilityDB.executeSimpleQuery(advancedDataSource.getConnection(), sql);
dropOldTables(advancedDataSource.getConnection());
createNewTables(advancedDataSource.getConnection());
for (HashMap<String, Object> oldStbPublication : oldStbPublications) {
String publicationDescription = UtilityHashMap.getValueIfExists(oldStbPublication, "publication_description");
String insertSql = Query.format("INSERT INTO stb_publications (publication_description) VALUES (%s)", publicationDescription);
long generatedId = executeInsertStatement(advancedDataSource.getConnection(), insertSql);
oldStbPublication.putIfAbsent("id", generatedId);
}
for (HashMap<String, Object> oldStbPublicationDetail : oldStbPublicationsDetails) {
String oldId = UtilityHashMap.getValueIfExists(oldStbPublicationDetail, "publication_id");
String entityName = UtilityHashMap.getValueIfExists(oldStbPublicationDetail, "entity_name");
String whereCondSql = UtilityHashMap.getValueIfExists(oldStbPublicationDetail, "where_cond_sql");
String recalcColumns = UtilityHashMap.getValueIfExists(oldStbPublicationDetail, "recalc_columns");
String syncronize = UtilityHashMap.getValueIfExists(oldStbPublicationDetail, "syncronize");
String whereCond = UtilityHashMap.getValueIfExists(oldStbPublicationDetail, "where_cond");
Long newParentId = getNewGeneratedIdFromOldKey(oldId, oldStbPublications);
String insertSql = Query.format("INSERT INTO stb_publications_detail " +
"(stb_publication_id, entity_name, where_cond_sql, recalc_columns, syncronize, where_cond) " +
"VALUES (%s, %s, %s, %s, %s, %s)", newParentId, entityName, whereCondSql, recalcColumns, syncronize.equalsIgnoreCase("S") || syncronize.equalsIgnoreCase("R"), whereCond);
long generatedId = executeInsertStatement(advancedDataSource.getConnection(), insertSql);
oldStbPublicationDetail.putIfAbsent("id", generatedId);
}
}
@Override
public void down() throws Exception {
}
private void dropOldTables(@NotNull Connection connection) throws SQLException {
String dropSql = "DROP TABLE stb_publications_detail";
executeStatement(connection, dropSql);
dropSql = "DROP TABLE stb_publications";
executeStatement(connection, dropSql);
}
private void createNewTables(@NotNull Connection connection) throws SQLException {
String createSql = "CREATE TABLE dbo.stb_publications\n" +
"(\n" +
" id BIGINT IDENTITY,\n" +
" publication_description VARCHAR(1024) NOT NULL\n" +
")";
executeStatement(connection, createSql);
createSql = "CREATE UNIQUE CLUSTERED INDEX stb_publications_id_uindex\n" +
" ON dbo.stb_publications (id)";
executeStatement(connection, createSql);
createSql = "CREATE TABLE dbo.stb_publications_detail\n" +
"(\n" +
" id BIGINT IDENTITY\n" +
" CONSTRAINT stb_publications_detail_pk\n" +
" PRIMARY KEY,\n" +
" stb_publication_id BIGINT NOT NULL\n" +
" CONSTRAINT stb_publications_detail_stb_publications_id_fk\n" +
" REFERENCES dbo.stb_publications (id),\n" +
" entity_name VARCHAR(40) NOT NULL,\n" +
" where_cond_sql VARCHAR(MAX),\n" +
" recalc_columns VARCHAR(MAX),\n" +
" syncronize BIT DEFAULT 1 NOT NULL,\n" +
" where_cond VARCHAR(MAX)" +
")";
executeStatement(connection, createSql);
}
public Long getNewGeneratedIdFromOldKey(String oldKey, List<HashMap<String, Object>> oldList) {
return oldList.stream()
.filter(x -> ((String) x.getOrDefault("publication_id", "")).equalsIgnoreCase(oldKey))
.map(x -> (long) x.getOrDefault("id", -1))
.findFirst()
.orElse(null);
}
}

View File

@@ -4,7 +4,8 @@ import com.annimon.stream.ComparatorCompat;
import com.annimon.stream.Optional;
import com.annimon.stream.Stream;
import it.integry.common.var.CommonConstants;
import it.integry.ems_model.annotation.*;
import it.integry.ems_model.annotation.ReloadRow;
import it.integry.ems_model.annotation.SqlField;
import it.integry.ems_model.base.EntityBase;
import it.integry.ems_model.config.EmsRestConstants;
import it.integry.ems_model.db.ResultSetMapper;
@@ -16,7 +17,6 @@ import it.integry.ems_model.rulescompleting.DroolsDataCompleting;
import it.integry.ems_model.types.ApplicationName;
import it.integry.ems_model.types.OperationType;
import it.integry.ems_model.utility.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
@@ -179,7 +179,7 @@ public class CommonRules extends QueryRules {
Object object = field.get(testata);
if (object != null && field.getType().isAssignableFrom(List.class) && ( field.getAnnotation(ReloadRow.class) != null || testata.getOperation() == OperationType.SUBSTITUTE)) {
List<? extends EntityBase> rows = (ArrayList<EntityBase>) object;
List<EntityBase> list = null;
List<? extends EntityBase> list = null;
if (testata.getOperation() != OperationType.DELETE_THEN_INSERT &&
testata.getOperation() != OperationType.INSERT) {
list = UtilityDB.reloadOnlyDbRow(conn, testata, rows, field);

View File

@@ -16,6 +16,7 @@ public class ForeignKeyDTO {
put(CtbIreg.ENTITY, "Codice registro documenti inesistente");
put(WtbJrept.ENTITY, "Report inesistente");
put(StbDevice.ENTITY, "Dispositivo inesistente");
put(StbPublications.ENTITY, "Pubblicazione inesistente");
}};
String tableName;

View File

@@ -155,23 +155,10 @@ public class EntityProcessor {
return entity.selectAndMergeEntity(mdb.getPrimaryConnection(), (EntityBase) entity);
//return entity;
} else if (entity.getOperation() == OperationType.SELECT) {
String json = (String) entity.select(mdb.getPrimaryConnection());
if (json != null) {
EntityBase[] entityList = null;
//json to entity
if (json.charAt(0) == '[') {
entityList = jsonObjectMapper.readValue(json, EntityBase[].class);
} else if (json.charAt(0) == '{') {
EntityBase ent = jsonObjectMapper.readValue(json, EntityBase.class);
entityList = new EntityBase[]{ent};
}
for (int i = 0; i < entityList.length; i++) {
entityList[i].setOperation(entity.getOperation());
}
List<? extends EntityBase> entityList = entity.select(mdb.getPrimaryConnection());
return entityList;
}
} else {
processInternal(entity, isSync, mdb, completeEntity);
}

View File

@@ -93,9 +93,9 @@ public class AsyncManager {
}
}
public static String getPublicationIdIfExists(String dbName, EntityBase entityBase) throws Exception {
public static long getPublicationIdIfExists(String dbName, EntityBase entityBase) throws Exception {
if (!cachedSetup.containsKey(dbName) || cachedSetup.get(dbName) == null || cachedSetup.get(dbName).isEmpty())
return null;
return 0;
String tableName = entityBase.getTableName().toUpperCase();
StbPublicationsDetail activePublication = cachedSetup.get(dbName).stream()
@@ -104,7 +104,7 @@ public class AsyncManager {
.orElse(null);
if (activePublication == null)
return null;
return 0;
logger.debug("SYNC OFFLINE ABILITATA SU " + tableName);
@@ -124,9 +124,9 @@ public class AsyncManager {
List<?> res = qr.getResults();
if (res == null || res.isEmpty())
return null;
return 0;
return activePublication.getPublicationId();
return activePublication.getStbPublicationId();
}

View File

@@ -48,7 +48,7 @@ public class UtilityEntity {
}
public static <T extends EntityBase> List<T> toCustomEntity(List<EntityBase> entities) {
public static <T extends EntityBase> List<T> toCustomEntity(List<? extends EntityBase> entities) {
List<T> respList = new ArrayList<T>();
for (EntityBase entity : entities) {

View File

@@ -7,13 +7,8 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonTypeResolver;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Joiner;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import it.integry.common.var.CommonConstants;
import it.integry.common.var.EmsDBConst;
import it.integry.ems.object_storage.minio.MinIOService;
@@ -31,7 +26,6 @@ import it.integry.ems_model.config.EmsRestConstants;
import it.integry.ems_model.db.ResultSetMapper;
import it.integry.ems_model.exception.*;
import it.integry.ems_model.resolver.PropertyTypeResolver;
import it.integry.ems_model.resolver.ResultSetSerializer;
import it.integry.ems_model.resolver.SqlFieldHolder;
import it.integry.ems_model.rulescompleting.DroolsDataCompleting;
import it.integry.ems_model.types.OperationType;
@@ -51,7 +45,6 @@ import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@@ -419,10 +412,9 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
this.exception = exception;
}
public Object select(Connection connection) throws Exception {
public List<? extends EntityBase> select(Connection connection) throws Exception {
String query = "";
if (nativeSql != null) {
String columnList;
int sIdx = nativeSql.toUpperCase().indexOf("SELECT DISTINCT");
@@ -451,8 +443,8 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
List<String> colList = new ArrayList<String>();
for (String sqlFieldName : fields.split(",")) {
Field f = getEntityHolder().getFieldBySql("", sqlFieldName);
sqlFieldName += " as " + f.getName();
//Field f = getEntityHolder().getFieldBySql("", sqlFieldName);
//sqlFieldName += " as " + f.getName();
colList.add(sqlFieldName);
}
columnList = StringUtils.join(colList, ", ");
@@ -463,41 +455,17 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
} else {
String wherePK = getEntityHolder().getWherePK(this);
String columnList = getEntityHolder().getColumnList(this.getClass(), this.getTableName());
if (!UtilityString.isNullOrEmpty(wherePK))
query = "SELECT " + columnList + ", '" + getTableName() + "' as type FROM " + getTableName() + " WHERE " + wherePK;
else return null;
if (!UtilityString.isNullOrEmpty(wherePK)) {
query = "SELECT " + columnList + ", '" + getTableName() + "' as type FROM " + getTableName();
if (!wherePK.equalsIgnoreCase("()"))
query += " WHERE " + wherePK;
} else return null;
}
return selectRawData(connection, query);
}
private Object selectRawData(Connection connection, String query) throws Exception {
SimpleModule module = new SimpleModule();
module.addSerializer(new ResultSetSerializer());
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(module);
PreparedStatement ps = connection.prepareStatement(query);
ps.setQueryTimeout(queryTimeoutSeconds);
ResultSet resultset = ps.executeQuery();
// Use the DataBind Api here
ObjectNode objectNode = objectMapper.createObjectNode();
// put the resultset in a containing structure
objectNode.putPOJO("results", resultset);
// generate all
StringWriter writer = new StringWriter();
objectMapper.writeValue(writer, objectNode.get("results"));
//chiusura resultset
resultset.close();
ps.close();
String json = writer.toString();
JsonArray array = new JsonParser().parse(json).getAsJsonArray();
if (array.size() == 0) return null;
return json;
return UtilityDB.executeSimpleQueryDTO(connection, query, this.getClass());
}
private boolean checkPkValueNull(EntityBase entityBase) throws IllegalAccessException {
@@ -539,7 +507,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
return entityDB;
}
public List<EntityBase> selectEntityRowList(Connection connection, EntityBase entity, Class<? extends EntityBase> rowClass, String tableName, String whereConds) throws IOException, FieldMissingException, IllegalAccessException, SQLException, DataConverterNotFoundException, InstantiationException {
public List<? extends EntityBase> selectEntityRowList(Connection connection, EntityBase entity, Class<? extends EntityBase> rowClass, String tableName, String whereConds) throws IOException, FieldMissingException, IllegalAccessException, SQLException, DataConverterNotFoundException, InstantiationException {
if (!UtilityString.isNullOrEmpty(whereConds)) {
whereConds = " AND " + whereConds;
@@ -895,6 +863,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
}
}
@Override
public void checkPreSave() throws Exception {
}
@@ -946,9 +915,9 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
managePriorityPost();
if (this.getClass().getAnnotation(Master.class) != null) {
String publicationId = AsyncManager.getPublicationIdIfExists(dbName, this);
long publicationId = AsyncManager.getPublicationIdIfExists(dbName, this);
if (publicationId != null) {
if (publicationId > 0) {
if (transactionGroupId == null) transactionGroupId = AsyncManager.getNextTransactionGroupId(connection);
AsyncManager.saveNewTransaction(connection, this, transactionGroupId);
}

View File

@@ -25,7 +25,7 @@ public interface EntityInterface {
void applyDefault() throws IllegalAccessException, IOException;
Object select(Connection connection) throws Exception;
List<? extends EntityBase> select(Connection connection) throws Exception;
OperationType getOperation();

View File

@@ -172,6 +172,29 @@ public class EntityPropertyHolder {
}
}
public Field getEntityChildField(Class<? extends EntityBase> parentClazz, Class<? extends EntityBase> childClass) {
final List<Field> entityChildField = getEntityChildField(parentClazz);
final Field foundField = entityChildField.stream()
.filter(x -> {
if(x.getType().isAssignableFrom(childClass)) return true;
if(x.getType().isAssignableFrom(List.class)) {
ParameterizedType type = (ParameterizedType)x.getGenericType();
Class listItemType = type.getActualTypeArguments().length > 0 ? (Class<?>) type.getActualTypeArguments()[0] : null;
if(listItemType == null) return false;
return listItemType.isAssignableFrom(childClass);
}
return false;
})
.findFirst()
.orElse(null);
return foundField;
}
public Boolean isEntityChild(Class<? extends EntityBase> clazz, String childName) {
Boolean isChild = false;
List<Field> children = getEntityChildField(clazz);
@@ -220,7 +243,7 @@ public class EntityPropertyHolder {
if (object instanceof List) {
List<EntityBase> list = ((List<EntityBase>) object);
List<EntityBase> listRowDB = UtilityDB.reloadOnlyDbRow(conn, entityInsert, list, field);
List<? extends EntityBase> listRowDB = UtilityDB.reloadOnlyDbRow(conn, entityInsert, list, field);
if (listRowDB != null) {
for (EntityBase entDB : listRowDB) {
EntityBase cloningDB = (EntityBase) entDB.clone();
@@ -314,10 +337,14 @@ public class EntityPropertyHolder {
if (identity != null) {
pkIdentityNull = true;
}
} else {
if (identity != null && (field.getType().isPrimitive() && ((long) obj) == 0)) {
pkIdentityNull = true;
} else {
Object dato = SqlFieldHolder.getSqlValueField(obj);
where.add(SqlFieldHolder.getSqlValue(colName, field) + " = " + dato);
}
}
}
@@ -368,7 +395,7 @@ public class EntityPropertyHolder {
}
public String getColumnList(Class clazz, String tableName) {
return getColumnList(clazz, false, tableName, true);
return getColumnList(clazz, true, tableName, true);
}
public String getColumnList(Class clazz, boolean isSql, String tableName, boolean includeForcedRecalc) {

View File

@@ -0,0 +1,79 @@
package it.integry.ems_model.entity;
import com.fasterxml.jackson.annotation.JsonTypeName;
import it.integry.ems_model.annotation.*;
import it.integry.ems_model.base.EntityBase;
import org.kie.api.definition.type.PropertyReactive;
import java.util.ArrayList;
import java.util.List;
@Master
@PropertyReactive
@Table(StbPublications.ENTITY)
@JsonTypeName(StbPublications.ENTITY)
public class StbPublications extends EntityBase {
private static final long serialVersionUID = 1L;
public static final String ENTITY = "stb_publications";
@PK
@Identity
@SqlField(value = "id", nullable = false)
private long id;
@SqlField(value = "publication_description")
private String publicationDescription;
@EntityChild
private List<StbPublicationsDetail> stbPublicationsDetails = new ArrayList<>();
public long getId() {
return id;
}
public StbPublications setId(long id) {
this.id = id;
return this;
}
public String getPublicationDescription() {
return publicationDescription;
}
public StbPublications setPublicationDescription(String publicationDescription) {
this.publicationDescription = publicationDescription;
return this;
}
public List<StbPublicationsDetail> getStbPublicationsDetails() {
return stbPublicationsDetails;
}
public StbPublications setStbPublicationsDetails(List<StbPublicationsDetail> stbPublicationsDetails) {
this.stbPublicationsDetails = stbPublicationsDetails;
return this;
}
@Override
protected void insertChilds() throws Exception {
for (StbPublicationsDetail stbPublicationsDetail : getStbPublicationsDetails()) {
stbPublicationsDetail.manageWithParentConnection(connection, stbPublicationsDetail.getOperation(), dataCompleting, entityHolder);
}
}
@Override
protected void updateChilds() throws Exception {
for (StbPublicationsDetail stbPublicationsDetail : getStbPublicationsDetails()) {
stbPublicationsDetail.manageWithParentConnection(connection, stbPublicationsDetail.getOperation(), dataCompleting, entityHolder);
}
}
@Override
protected void deleteChilds() throws Exception {
StbPublicationsDetail stbPublicationsDetail = new StbPublicationsDetail();
stbPublicationsDetail.deleteAllEntities(connection, this);
}
}

View File

@@ -1,14 +1,10 @@
package it.integry.ems_model.entity;
import com.fasterxml.jackson.annotation.JsonTypeName;
import it.integry.ems_model.annotation.Master;
import it.integry.ems_model.annotation.PK;
import it.integry.ems_model.annotation.SqlField;
import it.integry.ems_model.annotation.Table;
import it.integry.ems_model.annotation.*;
import it.integry.ems_model.base.EntityBase;
import org.kie.api.definition.type.PropertyReactive;
@Master
@PropertyReactive
@Table(StbPublicationsDetail.ENTITY)
@JsonTypeName(StbPublicationsDetail.ENTITY)
@@ -16,23 +12,49 @@ public class StbPublicationsDetail extends EntityBase {
private static final long serialVersionUID = 1L;
public static final String ENTITY = "stb_publications_detail";
@PK
@Identity
@SqlField(value = "id", nullable = false)
private long id;
@FK(tableName = StbPublications.ENTITY, columnName = "id")
@SqlField(value = "stb_publication_id", nullable = false)
@ImportFromParent( value = "id")
private long stbPublicationId;
@SqlField(value = "entity_name")
private String entityName;
@PK
@SqlField(value = "publication_id")
private String publicationId;
@SqlField(value = "recalc_columns")
private String recalcColumns;
private String recalcColumnsField;
@SqlField(value = "syncronize", defaultObjectValue="S")
private String syncronize;
@SqlField(value = "syncronize", defaultObjectValue="1", nullable = false)
private boolean syncronize;
@SqlField(value = "where_cond_sql")
private String whereCondSql;
@SqlField(value = "where_cond")
private String whereCondField;
public long getId() {
return id;
}
public StbPublicationsDetail setId(long id) {
this.id = id;
return this;
}
public long getStbPublicationId() {
return stbPublicationId;
}
public StbPublicationsDetail setStbPublicationId(long stbPublicationId) {
this.stbPublicationId = stbPublicationId;
return this;
}
public String getEntityName() {
return entityName;
}
@@ -42,29 +64,20 @@ public class StbPublicationsDetail extends EntityBase {
return this;
}
public String getPublicationId() {
return publicationId;
}
public StbPublicationsDetail setPublicationId(String publicationId) {
this.publicationId = publicationId;
return this;
}
public String getRecalcColumnsField() {
return recalcColumns;
return recalcColumnsField;
}
public StbPublicationsDetail setRecalcColumns(String recalcColumns) {
this.recalcColumns = recalcColumns;
this.recalcColumnsField = recalcColumns;
return this;
}
public String getSyncronize() {
public boolean isSyncronize() {
return syncronize;
}
public StbPublicationsDetail setSyncronize(String syncronize) {
public StbPublicationsDetail setSyncronize(boolean syncronize) {
this.syncronize = syncronize;
return this;
}
@@ -78,6 +91,15 @@ public class StbPublicationsDetail extends EntityBase {
return this;
}
public String getWhereCondField() {
return this.whereCondField;
}
public StbPublicationsDetail setWhereCondField(String whereCond) {
this.whereCondField = whereCond;
return this;
}
@Override
public void checkPreSave() throws Exception {}

View File

@@ -105,7 +105,7 @@ public class UtilityDB {
statement.close();
}
public static List<EntityBase> reloadOnlyDbRow(Connection conn, EntityBase testata,
public static List<? extends EntityBase> reloadOnlyDbRow(Connection conn, EntityBase testata,
List<? extends EntityBase> rows, Field field) throws NoSuchFieldException, IllegalAccessException, DataConverterNotFoundException, SQLException, IOException, FieldMissingException, InstantiationException {
ParameterizedType pType = (ParameterizedType) field.getGenericType();
@@ -115,7 +115,7 @@ public class UtilityDB {
f.setAccessible(true);
String keyType = (String) f.get(null);
List<EntityBase> list;
List<? extends EntityBase> list;
String whereCond = null;
if (!rows.isEmpty()) {
EntityPropertyHolder holder = testata.getEntityHolder();

View File

@@ -3,7 +3,6 @@ package it.integry.ems.document.service;
import com.annimon.stream.Stream;
import it.integry.ems.document.dto.CambioTipoDocDTO;
import it.integry.ems.javabeans.RequestDataDTO;
import it.integry.ems.rules.completing.CommonRules;
import it.integry.ems.service.EntityProcessor;
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
import it.integry.ems_model.base.EntityBase;
@@ -148,9 +147,9 @@ public class CambioTipoDocService {
Field f = rowClass.getDeclaredField("ENTITY");
f.setAccessible(true);
String tableName = (String) f.get(null);
List<EntityBase> list = testata.selectEntityRowList(multiDBTransactionManager.getPrimaryConnection(), testata, rowClass, tableName, whereCond);
List<? extends EntityBase> list = testata.selectEntityRowList(multiDBTransactionManager.getPrimaryConnection(), testata, rowClass, tableName, whereCond);
if (list == null) {
list = (ArrayList<EntityBase>) object;
list = (List<? extends EntityBase>) object;
}
field.set(testata, list);
}

View File

@@ -20,7 +20,10 @@ import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import java.sql.Connection;
import java.util.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@Service
@Scope("request")
@@ -176,11 +179,11 @@ public class ProduzioniLamonarcaMaxidataService {
dtbOrdt.setNativeSql(sql);
dtbOrdt.setOperation(OperationType.SELECT);
EntityBase[] orderListResult = entityProcessor.processEntity(dtbOrdt, multiDBTransactionManager);
List<EntityBase> orderListResult = entityProcessor.processEntity(dtbOrdt, multiDBTransactionManager);
if (orderListResult != null && orderListResult.length > 0) {
List<DtbOrdt> orderList = UtilityEntity.toCustomEntity(Arrays.asList(orderListResult));
if (orderListResult != null && !orderListResult.isEmpty()) {
List<DtbOrdt> orderList = UtilityEntity.toCustomEntity(orderListResult);
orderList.get(0).setOperation(OperationType.INSERT_OR_UPDATE);
return orderList.get(0);
}

View File

@@ -1,7 +1,6 @@
package it.integry.ems.system.controller;
import it.integry.common.var.CommonConstants;
import it.integry.ems.response.EsitoType;
import it.integry.ems.response.ServiceRestResponse;
import it.integry.ems.system.service.AnagImportService;
import it.integry.ems.system.service.SystemService;
@@ -36,50 +35,27 @@ public class AnagImportController {
ServiceRestResponse importClieAnag(HttpServletRequest request,
@RequestParam(CommonConstants.PROFILE_DB) String configuration,
@RequestParam(value = "precode", defaultValue = "", required = false) String precode,
@RequestBody GtbAnag gtbAnag) {
ServiceRestResponse response;
try {
@RequestBody GtbAnag gtbAnag) throws Exception {
List<EntityBase> entities = anagImportService.importClieAnagInternal(gtbAnag, precode);
return UtilityEntity.toServiceRestResponse(entities).get(0);
} catch (Exception e) {
logger.error(request.getRequestURI(), e);
response = new ServiceRestResponse(EsitoType.KO, configuration, e);
}
return response;
}
@RequestMapping(value = EmsRestConstants.PATH_SET_COORDINATE_GEO_CLIE, method = RequestMethod.POST)
public @ResponseBody
ServiceRestResponse setCoodinateGeoClie(HttpServletRequest request,
@RequestParam(CommonConstants.PROFILE_DB) String configuration) {
@RequestParam(CommonConstants.PROFILE_DB) String configuration) throws Exception {
ServiceRestResponse response = new ServiceRestResponse();
try {
anagImportService.setCoodinateGeoClie();
return response;
//UtilityEntity.toServiceRestResponse(entities).get(0);
} catch (Exception e) {
logger.error(request.getRequestURI(), e);
response = new ServiceRestResponse(EsitoType.KO, configuration, e);
}
return response;
return ServiceRestResponse.createPositiveResponse();
}
@RequestMapping(value = EmsRestConstants.PATH_MIGRATE_GTB_ANAG_NOTE_FILES, method = RequestMethod.POST)
public @ResponseBody
ServiceRestResponse migrateGtbAnagNoteFiles(HttpServletRequest request,
@RequestParam(CommonConstants.PROFILE_DB) String configuration) {
@RequestParam(CommonConstants.PROFILE_DB) String configuration) throws Exception {
ServiceRestResponse response = new ServiceRestResponse();
try {
systemService.migrateGtbAnagNoteFiles();
return response;
} catch (Exception e) {
logger.error(request.getRequestURI(), e);
response = new ServiceRestResponse(EsitoType.KO, configuration, e);
}
return response;
return ServiceRestResponse.createPositiveResponse();
}
}

View File

@@ -28,13 +28,8 @@ public class MenuController {
@RequestMapping(value = EmsRestConstants.PATH_RETRIEVE_MENU_CONFIG, method = RequestMethod.GET)
public ServiceRestResponse retreiveMenuConfig(HttpServletRequest request,
@RequestParam(CommonConstants.PROFILE_DB) String configuration,
@RequestParam String rootCodOpz) {
try {
@RequestParam String rootCodOpz) throws Exception {
return ServiceRestResponse.createEntityPositiveResponse(menuService.retrieveMenuConfig(rootCodOpz));
} catch (Exception ex) {
logger.error(request.getRequestURI(), ex);
return ServiceRestResponse.createNegativeResponse(ex);
}
}
}

View File

@@ -0,0 +1,44 @@
package it.integry.ems.system.controller;
import it.integry.ems.response.ServiceRestResponse;
import it.integry.ems.system.dto.syncronization.InsertPublicationGroupRequestDTO;
import it.integry.ems.system.service.RemoteSyncronizationSetupService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Scope("request")
@RequestMapping("system/remote-sync/setup")
public class RemoteSyncronizationSetupController {
private final Logger logger = LogManager.getLogger();
@Autowired
private RemoteSyncronizationSetupService remoteSyncronizationSetupService;
@RequestMapping(value = "publications/retrieve", method = RequestMethod.GET)
public ServiceRestResponse retrievePublications() throws Exception {
return ServiceRestResponse.createPositiveResponse(remoteSyncronizationSetupService.retrievePublications());
}
@RequestMapping(value = "publications/insert-group", method = RequestMethod.POST)
public ServiceRestResponse insertPublicationGroup(@RequestBody InsertPublicationGroupRequestDTO request) throws Exception {
return ServiceRestResponse.createPositiveResponse(remoteSyncronizationSetupService.addPublicationGroup(request.getDescription()));
}
@RequestMapping(value = "publications/insert", method = RequestMethod.POST)
public ServiceRestResponse insertPublications() throws Exception {
return ServiceRestResponse.createPositiveResponse(remoteSyncronizationSetupService.retrievePublications());
}
}

View File

@@ -0,0 +1,15 @@
package it.integry.ems.system.dto.syncronization;
public class InsertPublicationGroupRequestDTO {
private String description;
public String getDescription() {
return description;
}
public InsertPublicationGroupRequestDTO setDescription(String description) {
this.description = description;
return this;
}
}

View File

@@ -0,0 +1,15 @@
package it.integry.ems.system.dto.syncronization;
public class InsertPublicationGroupResponseDTO {
private long id;
public long getId() {
return id;
}
public InsertPublicationGroupResponseDTO setId(long id) {
this.id = id;
return this;
}
}

View File

@@ -0,0 +1,65 @@
package it.integry.ems.system.dto.syncronization;
public class PublicationDTO {
private long id;
private String entityName;
private String whereCondSql;
private String recalcColumns;
private boolean syncronize;
private String whereCond;
public long getId() {
return id;
}
public PublicationDTO setId(long id) {
this.id = id;
return this;
}
public String getEntityName() {
return entityName;
}
public PublicationDTO setEntityName(String entityName) {
this.entityName = entityName;
return this;
}
public String getWhereCondSql() {
return whereCondSql;
}
public PublicationDTO setWhereCondSql(String whereCondSql) {
this.whereCondSql = whereCondSql;
return this;
}
public String getRecalcColumns() {
return recalcColumns;
}
public PublicationDTO setRecalcColumns(String recalcColumns) {
this.recalcColumns = recalcColumns;
return this;
}
public boolean isSyncronize() {
return syncronize;
}
public PublicationDTO setSyncronize(boolean syncronize) {
this.syncronize = syncronize;
return this;
}
public String getWhereCond() {
return whereCond;
}
public PublicationDTO setWhereCond(String whereCond) {
this.whereCond = whereCond;
return this;
}
}

View File

@@ -0,0 +1,39 @@
package it.integry.ems.system.dto.syncronization;
import java.util.ArrayList;
import java.util.List;
public class PublicationGroupDTO {
private long id;
private String description;
private List<PublicationDTO> publications = new ArrayList<>();
public long getId() {
return id;
}
public PublicationGroupDTO setId(long id) {
this.id = id;
return this;
}
public String getDescription() {
return description;
}
public PublicationGroupDTO setDescription(String description) {
this.description = description;
return this;
}
public List<PublicationDTO> getPublications() {
return publications;
}
public PublicationGroupDTO setPublications(List<PublicationDTO> publications) {
this.publications = publications;
return this;
}
}

View File

@@ -0,0 +1,140 @@
package it.integry.ems.system.service;
import it.integry.ems.service.EntityProcessor;
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
import it.integry.ems.system.dto.syncronization.PublicationDTO;
import it.integry.ems.system.dto.syncronization.PublicationGroupDTO;
import it.integry.ems.utility.UtilityEntity;
import it.integry.ems_model.base.EntityBase;
import it.integry.ems_model.base.EntityPropertyHolder;
import it.integry.ems_model.entity.StbPublications;
import it.integry.ems_model.entity.StbPublicationsDetail;
import it.integry.ems_model.types.OperationType;
import it.integry.ems_model.utility.UtilityDB;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import javax.validation.constraints.NotNull;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
@Service
@Scope(value = "request")
public class RemoteSyncronizationSetupService {
private final Logger logger = LogManager.getLogger();
@Autowired
private MultiDBTransactionManager multiDBTransactionManager;
@Autowired
private EntityProcessor entityProcessor;
@Autowired
private EntityPropertyHolder entityPropertyHolder;
public List<PublicationGroupDTO> retrievePublications() throws Exception {
StbPublications tmp = new StbPublications();
tmp.setOperation(OperationType.SELECT);
tmp.setOnlyPkMaster(false);
List<EntityBase> selectedEntities = entityProcessor.processEntity(tmp, multiDBTransactionManager);
if (selectedEntities == null) return null;
List<StbPublications> stbPublicationsToRetrieve = UtilityEntity.toCustomEntity(selectedEntities);
List<PublicationGroupDTO> publicationGroups = new ArrayList<>();
for (StbPublications stbPublication : stbPublicationsToRetrieve) {
final PublicationGroupDTO publicationGroupDTO = new PublicationGroupDTO()
.setId(stbPublication.getId())
.setDescription(stbPublication.getPublicationDescription());
publicationGroups.add(publicationGroupDTO);
final Field entityChildField = entityPropertyHolder.getEntityChildField(StbPublications.class, StbPublicationsDetail.class);
final List<? extends EntityBase> entityBases = UtilityDB.reloadOnlyDbRow(multiDBTransactionManager.getPrimaryConnection(), stbPublication, stbPublication.getStbPublicationsDetails(), entityChildField);
final List<PublicationDTO> publications = UtilityEntity.<StbPublicationsDetail>toCustomEntity(entityBases).stream()
.map(x -> new PublicationDTO()
.setId(x.getId())
.setSyncronize(x.isSyncronize())
.setEntityName(x.getEntityName())
.setWhereCond(x.getWhereCondField())
.setWhereCondSql(x.getWhereCondSql())
.setRecalcColumns(x.getRecalcColumnsField()))
.collect(toList());
publicationGroupDTO.setPublications(publications);
}
return publicationGroups;
}
public long addPublicationGroup(String description) throws Exception {
StbPublications stbPublications = new StbPublications()
.setPublicationDescription(description);
stbPublications.setOperation(OperationType.INSERT);
entityProcessor.processEntity(stbPublications, multiDBTransactionManager);
return stbPublications.getId();
}
public void addPublications(long publicationId, @NotNull List<PublicationDTO> publications) throws Exception {
final List<StbPublicationsDetail> stbPublicationsToInsert = publications.stream()
.map(x -> new StbPublicationsDetail()
.setStbPublicationId(publicationId)
.setEntityName(x.getEntityName())
.setWhereCondSql(x.getWhereCondSql())
.setRecalcColumns(x.getRecalcColumns())
.setSyncronize(x.isSyncronize())
.setWhereCondField(x.getWhereCond()))
.collect(Collectors.toList());
StbPublications stbPublications = new StbPublications()
.setId(publicationId);
stbPublications.setOperation(OperationType.NO_OP);
final List<EntityBase> savedEntities = entityProcessor.processEntityList(stbPublicationsToInsert, multiDBTransactionManager, true);
UtilityEntity.throwEntitiesException(savedEntities);
}
public void deletePublications(@NotNull List<Long> publicationsId) throws Exception {
final Map<Long, List<StbPublicationsDetail>> stbPubblicationsDetail = publicationsId.stream()
.map(x -> {
final StbPublicationsDetail stbPublicationsDetail = new StbPublicationsDetail()
.setId(x);
stbPublicationsDetail.setOperation(OperationType.DELETE);
return stbPublicationsDetail;
})
.collect(groupingBy(StbPublicationsDetail::getStbPublicationId));
final AtomicReference<List<StbPublications>> stbPublications = new AtomicReference<>(new ArrayList<>());
stbPubblicationsDetail.forEach((k, v) -> {
StbPublications stbPublication = new StbPublications()
.setId(k)
.setStbPublicationsDetails(v);
stbPublication.setOperation(OperationType.NO_OP);
stbPublications.get().add(stbPublication);
});
final List<EntityBase> savedEntities = entityProcessor.processEntityList(stbPublications.get(), multiDBTransactionManager, true);
UtilityEntity.throwEntitiesException(savedEntities);
}
}