Merge remote-tracking branch 'origin/develop' into develop

This commit is contained in:
2024-01-11 18:52:17 +01:00
23 changed files with 465 additions and 396 deletions

View File

@@ -3,7 +3,6 @@ package it.integry.ems.async.controller;
import it.integry.common.var.CommonConstants;
import it.integry.ems.async.service.AsyncServiceNew;
import it.integry.ems.controller.EmsController;
import it.integry.ems.response.EsitoType;
import it.integry.ems.response.ServiceRestResponse;
import it.integry.ems.response.StatusResponse;
import it.integry.ems.status.ServiceChecker;
@@ -46,18 +45,9 @@ public class AsyncControllerNew {
HttpServletRequest request,
@RequestParam(CommonConstants.PROFILE_DB) String configuration,
@RequestParam String subscriptionName
) {
ServiceRestResponse response;
try {
asyncServiceNew.startSync(subscriptionName);
response = ServiceRestResponse.createPositiveResponse();
} catch (Exception ex) {
logger.error(ex);
response = new ServiceRestResponse(EsitoType.KO, configuration, ex);
}
return response;
) throws Exception {
asyncServiceNew.startSync(subscriptionName);
return ServiceRestResponse.createPositiveResponse();
}
@@ -67,18 +57,8 @@ public class AsyncControllerNew {
HttpServletRequest request,
@RequestParam(CommonConstants.PROFILE_DB) String configuration,
@RequestParam(value = "limit", required = false, defaultValue = "1") Integer limit
) {
ServiceRestResponse response;
try {
response = ServiceRestResponse.createPositiveResponse(asyncServiceNew.retrieveTransactions(limit));
} catch (Exception ex) {
logger.error(ex);
response = new ServiceRestResponse(EsitoType.KO, configuration, ex);
}
return response;
) throws Exception {
return ServiceRestResponse.createPositiveResponse(asyncServiceNew.retrieveTransactions(limit));
}
@@ -87,16 +67,10 @@ public class AsyncControllerNew {
ServiceRestResponse updateTransactionImportID(HttpServletRequest request,
@RequestParam Integer transactionImportID,
@RequestParam String sender,
@RequestParam String publicationID) {
try {
asyncServiceNew.updateTransactionImportCounterInDB(transactionImportID, publicationID, sender);
return ServiceRestResponse.createPositiveResponse();
} catch (Exception ex) {
logger.error(ex);
return new ServiceRestResponse(EsitoType.KO, ex.toString());
}
@RequestParam String publicationID) throws Exception {
asyncServiceNew.updateTransactionImportCounterInDB(transactionImportID, publicationID, sender);
return ServiceRestResponse.createPositiveResponse();
}
}

View File

@@ -0,0 +1,35 @@
package it.integry.ems.async.dto;
public class SyncConfigDTO
{
private String endpoint;
private String profileDb;
private String username;
public String getEndpoint() {
return endpoint;
}
public SyncConfigDTO setEndpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
public String getProfileDb() {
return profileDb;
}
public SyncConfigDTO setProfileDb(String profileDb) {
this.profileDb = profileDb;
return this;
}
public String getUsername() {
return username;
}
public SyncConfigDTO setUsername(String username) {
this.username = username;
return this;
}
}

View File

@@ -2,9 +2,9 @@ package it.integry.ems.async.service;
import com.annimon.stream.Stream;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import it.integry.common.var.CommonConstants;
import it.integry.ems.async.dto.SubscriptionDTO;
import it.integry.ems.async.dto.SyncConfigDTO;
import it.integry.ems.async.dto.TransactionDTO;
import it.integry.ems.javabeans.RequestDataDTO;
import it.integry.ems.json.JSONObjectMapper;
@@ -61,21 +61,23 @@ public class AsyncServiceNew {
private SetupGest setupGest;
public void startSync(String subscriptionName) throws Exception {
String jsonConfigurationString = setupGest.getSetup(multiDBTransactionManager.getPrimaryConnection(), "SINCRONIZZAZIONI_OFFLINE", "SETUP", subscriptionName);
JsonNode jsonConfigurationList = jsonObjectMapper.readTree(jsonConfigurationString);
for (JsonNode jsonConfig : jsonConfigurationList) {
String endpoint = jsonConfig.get("endpoint").asText();
String username = jsonConfig.get("username").asText();
String profileDb = jsonConfig.get("profileDb").asText();
if(UtilityString.isNullOrEmpty(jsonConfigurationString))
throw new Exception("Nessuna configurazione trovata per la sincronizzazione: " + subscriptionName);
final List<SyncConfigDTO> syncConfigs = jsonObjectMapper.readValue(jsonConfigurationString, new TypeReference<List<SyncConfigDTO>>() {
});
String wsUrlEndpoint = endpoint + EmsRestConstants.PATH_ASYNC_BASE_ROUTE + EmsRestConstants.PATH_ASYNC_RETRIEVE_TRANSACTIONS;
for (SyncConfigDTO syncConfig : syncConfigs) {
String wsUrlEndpoint = syncConfig.getEndpoint() + EmsRestConstants.PATH_ASYNC_BASE_ROUTE + EmsRestConstants.PATH_ASYNC_RETRIEVE_TRANSACTIONS;
HashMap<String, String> queryParams = new HashMap<>();
queryParams.put("profileDb", profileDb);
queryParams.put("profileDb", syncConfig.getProfileDb());
boolean shouldStop = false;
@@ -84,7 +86,7 @@ public class AsyncServiceNew {
do {
StringBuilder responseBody = new StringBuilder();
int status = HttpRestWrapper.callGenericGet(wsUrlEndpoint, username, username, responseBody, queryParams);
int status = HttpRestWrapper.callGenericGet(wsUrlEndpoint, syncConfig.getUsername(), syncConfig.getUsername(), responseBody, queryParams);
if (status != 200)
throw new Exception("La richiesta \"" + wsUrlEndpoint + "\" ha generato status code: " + status + "<br />Body: " + responseBody);
@@ -99,21 +101,20 @@ public class AsyncServiceNew {
List<List<TransactionDTO>> transactions = jsonObjectMapper.readValue(dtoJson, new TypeReference<List<List<TransactionDTO>>>() {
});
if (transactions.size() == 0 || transactions.get(0).size() == 0) {
if (transactions.isEmpty() || transactions.get(0).isEmpty()) {
if (importedTransactionsCounter == 0) logger.debug("Nessuna entity da sincronizzare");
else logger.debug("Sincronizzazione OFFLINE terminata");
shouldStop = true;
} else {
importedTransactionsCounter += importTransactions(endpoint, profileDb, username, transactions);
importedTransactionsCounter +=
importTransactions(syncConfig.getEndpoint(), syncConfig.getProfileDb(), syncConfig.getUsername(), transactions);
}
} else {
throw new Exception("La richiesta \"" + wsUrlEndpoint + "\" ha generato un ESITO KO<br />Body: " + responseBody);
}
} while (!shouldStop);
}
}
@@ -124,18 +125,18 @@ public class AsyncServiceNew {
int importedEntityCounter = 0;
for (int i = 0; i < transactionList.size(); i++) {
final List<Integer> transactionsIDGroups = new ArrayList<Integer>();
for (int j = 0; j < transactionList.get(i).size(); j++) {
if (!transactionsIDGroups.contains(transactionList.get(i).get(j).transactionGroupId))
transactionsIDGroups.add(transactionList.get(i).get(j).transactionGroupId);
}
for (List<TransactionDTO> transactionDTOS : transactionList) {
final List<Integer> transactionsIDGroups = new ArrayList<>();
for (TransactionDTO dto : transactionDTOS) {
if (!transactionsIDGroups.contains(dto.transactionGroupId))
transactionsIDGroups.add(dto.transactionGroupId);
}
//Per ogni transaction group trovato mi prendo tutte le transactions
for (int j = 0; j < transactionsIDGroups.size(); j++) {
final int finalJ = j;
List<TransactionDTO> transactionsToImport = Stream.of(transactionList.get(i))
List<TransactionDTO> transactionsToImport = Stream.of(transactionDTOS)
.filter(transactionDTO -> transactionDTO.getTransactionGroupId() == transactionsIDGroups.get(finalJ))
.toList();
@@ -182,7 +183,7 @@ public class AsyncServiceNew {
//Lettura di tutte le sottoscrizioni attive (di tutte le entity)
List<HashMap<String, Object>> result = UtilityDB.executeSimpleQuery(multiDBTransactionManager.getPrimaryConnection(), sqlCheckActiveSubscriptions);
if (result.size() > 0) {
if (!result.isEmpty()) {
for (HashMap<String, Object> stringObjectHashMap : result) {
activeSubscriptions.add(new SubscriptionDTO()
.setPublicationId(UtilityHashMap.<String>getValueIfExists(stringObjectHashMap, "publication_id"))

View File

@@ -352,6 +352,12 @@ public abstract class BaseEntityExporter implements IEntityExporter {
case EMAIL:
if (UtilityString.isNullOrEmpty(wtbUserInfo.getEmail()) &&
UtilityString.isNullOrEmpty(wtbUserInfo.getEmailCc()) &&
UtilityString.isNullOrEmpty(wtbUserInfo.getEmailCcn())) {
break;
}
if (UtilityString.isNullOrEmpty(entityExportResponse.getMessageSubject())) {
entityExportResponse.setMessageSubject("INVIO " + type);
}

View File

@@ -1,6 +1,5 @@
package it.integry.ems.rules.completing;
import com.annimon.stream.Stream;
import it.integry.ems_model.entity.DtbDoct;
import it.integry.ems_model.entity.WdtbDoct;
import it.integry.ems_model.entity.common.DtbDocOrdT;
@@ -39,7 +38,7 @@ public class OrdWebRules extends QueryRules {
if (testata instanceof WdtbDoct || testata instanceof DtbDoct)
throw new Exception("Impossibile eseguire completeIdArtOrd su un documento");
if (testata.getApplicationName().equalsIgnoreCase("TEXTILES")) {
if (testata.getApplicationName().equalsIgnoreCase(ApplicationName.TEXTILES.toString())) {
String codMartOld = "";
String gruppoConsOld = "";
String noteRigaOld = "";

View File

@@ -301,7 +301,7 @@ public class OrderRules extends QueryRules {
public static Boolean checkExistOrdW(Connection conn, WdtbOrdt wdtbOrdt) throws Exception {
String sql = null;
if (wdtbOrdt.getApplicationName().equalsIgnoreCase("TEXTILES")) {
if (wdtbOrdt.getApplicationName().equalsIgnoreCase(ApplicationName.TEXTILES.toString())) {
String codFirtMart = wdtbOrdt.getWdtbOrdr().get(0).getCodMart();

View File

@@ -138,6 +138,7 @@ public class EntityProcessor {
entity.setEntityHolder(entityPropertyHolder);
entity.setUsername(username);
entity.setApplicationNameDB(mdb.getPrimaryDatasource().getProfile());
entity.setDbName(mdb.getPrimaryDatasource().getDbName());
entity.trimPK();
if (entity.getOperation() == null) {
entity.setOperation(OperationType.NO_OP);

View File

@@ -1,94 +1,132 @@
package it.integry.ems.sync;
import it.integry.annotations.PostContextConstruct;
import it.integry.common.var.CommonConstants;
import it.integry.ems.json.JSONObjectMapper;
import it.integry.ems.looper.service.LooperService;
import it.integry.ems.settings.Model.AvailableConnectionsModel;
import it.integry.ems.settings.Model.SettingsModel;
import it.integry.ems.settings.SettingsController;
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
import it.integry.ems.utility.UtilityDebug;
import it.integry.ems_model.base.EntityBase;
import it.integry.ems_model.entity.StbPublicationsDetail;
import it.integry.ems_model.utility.UtilityDB;
import it.integry.ems_model.utility.UtilityString;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.josql.Query;
import org.josql.QueryResults;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;
@Component
public class AsyncManager {
private static Logger logger = LogManager.getLogger();
private static final Logger logger = LogManager.getLogger();
public static String getPublicationIdIfExists(Connection connection, EntityBase entityBase) throws Exception {
String publicationId = null;
@Autowired
private LooperService looperService;
String tableName = entityBase.getTableName().toUpperCase();
String sqlExist =
"SELECT * FROM sys.objects " +
"WHERE object_id = OBJECT_ID(N'dbo.stb_publications_detail') AND type in (N'U')";
@Autowired
private SettingsModel settingsModel;
PreparedStatement psExist = connection.prepareStatement(sqlExist);
ResultSet rsExist = psExist.executeQuery();
if (rsExist.next()) {
// OFFLINE
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql =
"SELECT publication_id, where_cond_sql " +
"FROM stb_publications_detail " +
"WHERE entity_name='" + tableName + "' AND syncronize='R'";
ps = connection.prepareStatement(sql);
rs = ps.executeQuery();
String whereCondSql;
if (rs.next()) {
logger.debug("SYNC OFFLINE ABILITATA SU " + tableName);
publicationId = rs.getString("publication_id");
whereCondSql = rs.getString("where_cond_sql");
@Autowired
private SettingsController settingsController;
List<EntityBase> myObjs = new ArrayList<EntityBase>();
myObjs.add(entityBase);
private final static HashMap<String, List<StbPublicationsDetail>> cachedSetup = new HashMap<>();
String selectSql = "SELECT * FROM " + entityBase.getClass().getCanonicalName();
if (!UtilityString.isNullOrEmpty(whereCondSql)) {
selectSql = selectSql + " WHERE " + whereCondSql;
}
// Create a new Query.
Query q = new Query();
q.parse(selectSql);
@PostContextConstruct
public void init() {
if (!UtilityDebug.isDebugExecution() && !UtilityDebug.isIntegryServer()) {
looperService.add(this::internalCachePublicationsSetup, 5 * 60 * 1000, AsyncManager.class.getName());
}
}
QueryResults qr = q.execute(myObjs);
List res = qr.getResults();
if (res == null || res.size() == 0) {
publicationId = null;
}
}
} catch (Exception e) {
throw e;
} finally {
if (rs != null && !rs.isClosed()) {
rs.close();
}
if (ps != null && !ps.isClosed()) {
ps.close();
}
}
private void internalCachePublicationsSetup() {
String historyProfileDb = null;
try {
historyProfileDb = settingsController.getHistoryProfileDb();
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
rsExist.close();
psExist.close();
return publicationId;
String finalHistoryProfileDb = historyProfileDb;
Map<String, List<AvailableConnectionsModel>> databases = settingsModel.getAvailableConnections()
.stream()
.filter(AvailableConnectionsModel::getInternalDb)
.filter(x -> finalHistoryProfileDb != null && !finalHistoryProfileDb.equalsIgnoreCase(x.getProfileName()))
.collect(Collectors.groupingBy(AvailableConnectionsModel::getDbName));
cachedSetup.clear();
for (String dbName : databases.keySet()) {
try {
String profileName = databases.get(dbName).get(0).getProfileName();
cacheSetup(dbName, profileName);
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
}
}
private void cacheSetup(String dbName, String profileName) throws Exception {
MultiDBTransactionManager multiDBTransactionManager = new MultiDBTransactionManager(profileName, false);
try {
String sql = "SELECT * FROM " + StbPublicationsDetail.ENTITY + " WHERE syncronize = 'R'";
List<StbPublicationsDetail> publications = UtilityDB.executeSimpleQueryDTO(multiDBTransactionManager.getPrimaryConnection(), sql, StbPublicationsDetail.class);
cachedSetup.putIfAbsent(dbName, publications);
} finally {
multiDBTransactionManager.closeAll();
}
}
public static String getPublicationIdIfExists(String dbName, EntityBase entityBase) throws Exception {
if (!cachedSetup.containsKey(dbName) || cachedSetup.get(dbName) == null || cachedSetup.get(dbName).isEmpty())
return null;
String tableName = entityBase.getTableName().toUpperCase();
StbPublicationsDetail activePublication = cachedSetup.get(dbName).stream()
.filter(x -> x.getEntityName().equalsIgnoreCase(tableName))
.findFirst()
.orElse(null);
if (activePublication == null)
return null;
logger.debug("SYNC OFFLINE ABILITATA SU " + tableName);
List<EntityBase> myObjs = new ArrayList<>();
myObjs.add(entityBase);
String selectSql = "SELECT * FROM " + entityBase.getClass().getCanonicalName();
if (!UtilityString.isNullOrEmpty(activePublication.getWhereCondSql())) {
selectSql = selectSql + " WHERE " + activePublication.getWhereCondSql();
}
// Create a new Query.
Query q = new Query();
q.parse(selectSql);
QueryResults qr = q.execute(myObjs);
List<?> res = qr.getResults();
if (res == null || res.isEmpty())
return null;
return activePublication.getPublicationId();
}

View File

@@ -24,6 +24,7 @@ import it.integry.ems.rules.completing.ForeignKeyRules;
import it.integry.ems.rules.completing.UniqueKeyRules;
import it.integry.ems.rules.completing.dto.ForeignKeyDTO;
import it.integry.ems.settings.Model.SettingsModel;
import it.integry.ems.sync.AsyncManager;
import it.integry.ems.utility.UtilityDebug;
import it.integry.ems_model.annotation.*;
import it.integry.ems_model.config.EmsRestConstants;
@@ -93,7 +94,11 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
protected DroolsDataCompleting dataCompleting;
// USERNAME DI CHI STA ESEGUENDO L'OPERAZIONE
protected String username = "";
protected String applicationName = "";
private String dbName;
@JsonIgnore
protected String tableName;
private String whereCond;
@@ -280,10 +285,8 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
public String getTableName() {
Table t = getClass().getAnnotation(Table.class);
if (t != null)
return t.value();
else
return "";
if (t != null) return t.value();
else return "";
}
public Boolean getLoadedFromDb() {
@@ -299,8 +302,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
}
public void setUsername(String username) {
if (UtilityString.isNullOrEmpty(username))
username = "";
if (UtilityString.isNullOrEmpty(username)) username = "";
this.username = username;
}
@@ -317,6 +319,11 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
this.setApplicationName(emsDBConst.getConsts(profileDb).getApplicationDbName());
}
@Override
public void setDbName(String dbName) {
this.dbName = dbName;
}
public EntityPropertyHolder getEntityHolder() {
return entityHolder == null ? ContextLoader.getCurrentWebApplicationContext().getBean(EntityPropertyHolder.class) : entityHolder;
}
@@ -389,8 +396,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
}
public void setRecalcColumns(List<String> recalcColumns) throws Exception {
if (recalcColumns == null || recalcColumns.isEmpty())
this.recalcColumns = new ArrayList<String>();
if (recalcColumns == null || recalcColumns.isEmpty()) this.recalcColumns = new ArrayList<String>();
for (String sqlField : recalcColumns) {
recalcField(sqlField, "recalcColumns");
@@ -413,9 +419,6 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
this.exception = exception;
}
public void checkPreCond(Connection connection) throws Exception {
}
public Object select(Connection connection) throws Exception {
String query = "";
if (nativeSql != null) {
@@ -461,10 +464,8 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
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;
query = "SELECT " + columnList + ", '" + getTableName() + "' as type FROM " + getTableName() + " WHERE " + wherePK;
else return null;
}
return selectRawData(connection, query);
@@ -494,16 +495,14 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
String json = writer.toString();
JsonArray array = new JsonParser().parse(json).getAsJsonArray();
if (array.size() == 0)
return null;
if (array.size() == 0) return null;
return json;
}
private boolean checkPkValueNull(EntityBase entityBase) throws IllegalAccessException {
Field[] fields = entityBase.getClass().getDeclaredFields();
List<Field> fieldsPK = Stream.of(fields)
.filter(x -> x.isAnnotationPresent(PK.class)).toList();
List<Field> fieldsPK = Stream.of(fields).filter(x -> x.isAnnotationPresent(PK.class)).toList();
for (Field f : fieldsPK) {
f.setAccessible(true);
@@ -530,14 +529,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
where = " WHERE " + where;
}
String columnList = getEntityHolder().getColumnList(
entity.getClass(),
false,
entity.getTableName(),
entity.getOperation() != OperationType.UPDATE &&
entity.getOperation() != OperationType.INSERT_OR_UPDATE &&
entity.getOperation() != OperationType.SUBSTITUTE &&
entity.getOperation() != OperationType.DELETE_THEN_INSERT);
String columnList = getEntityHolder().getColumnList(entity.getClass(), false, entity.getTableName(), entity.getOperation() != OperationType.UPDATE && entity.getOperation() != OperationType.INSERT_OR_UPDATE && entity.getOperation() != OperationType.SUBSTITUTE && entity.getOperation() != OperationType.DELETE_THEN_INSERT);
String query = "SELECT " + columnList + " FROM " + entity.getTableName() + where;
@@ -547,8 +539,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<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;
@@ -587,12 +578,10 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
for (String pk : pks) {
Field field = getEntityHolder().getFieldBySql(this.getClass().getSimpleName(), pk);
field.setAccessible(true);
if (!field.get(this).equals(field.get(entityCmp)))
return false;
if (!field.get(this).equals(field.get(entityCmp))) return false;
}
return true;
} else
throw new Exception("Impossibile confrontare le entity");
} else throw new Exception("Impossibile confrontare le entity");
}
private EntityBase mergeEntityDBToObject(Connection connection, HashMap<String, Object> datiDb, EntityBase entity) throws IllegalAccessException, ConverterNotConfiguredException, SQLException, MinioException, XmlPullParserException, NoSuchAlgorithmException, IOException, InvalidKeyException, MergeEntityDBToObjectException {
@@ -633,10 +622,8 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
zlibContent = (byte[]) columnValue;
}
if (field.getType().equals(String.class))
columnValue = Base64.encodeBase64String(zlibContent);
else if (field.getType().equals(byte[].class))
columnValue = zlibContent;
if (field.getType().equals(String.class)) columnValue = Base64.encodeBase64String(zlibContent);
else if (field.getType().equals(byte[].class)) columnValue = zlibContent;
if (object == null) {
field.set(entity, columnValue);
@@ -666,10 +653,8 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
byte[] data = minIOService.downloadObject(refUUID, connection);
if (data != null) {
if (field.getType().equals(String.class))
columnValue = Base64.encodeBase64String(data);
else if (field.getType().equals(byte[].class))
columnValue = data;
if (field.getType().equals(String.class)) columnValue = Base64.encodeBase64String(data);
else if (field.getType().equals(byte[].class)) columnValue = data;
}
field.set(entity, columnValue);
@@ -685,14 +670,11 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
return entity;
} else {
if (entity.getOperation() == OperationType.SELECT_OBJECT)
return null;
else if (entity.getOperation() == OperationType.INSERT_OR_UPDATE)
return entity;
if (entity.getOperation() == OperationType.SELECT_OBJECT) return null;
else if (entity.getOperation() == OperationType.INSERT_OR_UPDATE) return entity;
else if (entity.getOperation() == OperationType.SUBSTITUTE || getOperation() == OperationType.DELETE_THEN_INSERT)
return entity;
else
throw new MergeEntityDBToObjectException(entity);
else throw new MergeEntityDBToObjectException(entity);
}
}
@@ -740,8 +722,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
if (field.getType().equals(String.class))
columnValue = Base64.encodeBase64String(zlibContent);
else if (field.getType().equals(byte[].class))
columnValue = zlibContent;
else if (field.getType().equals(byte[].class)) columnValue = zlibContent;
if (object == null) {
field.set(entity, columnValue);
@@ -773,8 +754,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
if (data != null) {
if (field.getType().equals(String.class))
columnValue = Base64.encodeBase64String(data);
else if (field.getType().equals(byte[].class))
columnValue = data;
else if (field.getType().equals(byte[].class)) columnValue = data;
}
field.set(entity, columnValue);
@@ -788,10 +768,8 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
}
return entity;
} else {
if (entity.getOperation() == OperationType.SELECT_OBJECT)
return null;
else if (entity.getOperation() == OperationType.INSERT_OR_UPDATE)
return entity;
if (entity.getOperation() == OperationType.SELECT_OBJECT) return null;
else if (entity.getOperation() == OperationType.INSERT_OR_UPDATE) return entity;
else if (entity.getOperation() == OperationType.SUBSTITUTE || getOperation() == OperationType.DELETE_THEN_INSERT)
return entity;
else
@@ -816,8 +794,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
f.setAccessible(true);
entity = f.get(this);
sqlField = split[1];
} else
entity = this.clone();
} else entity = this.clone();
if (entity instanceof List) {
List<EntityInterface> list = (List<EntityInterface>) entity;
@@ -864,8 +841,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
f.setAccessible(true);
entity = f.get(this);
sqlField = split[1];
} else
entity = this;
} else entity = this;
if (entity instanceof List) {
List<EntityInterface> list = (List<EntityInterface>) entity;
@@ -881,12 +857,10 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
Field f = entityInterface.getClass().getSuperclass().getDeclaredField(columnName);
if (f == null)
throw new Exception(
"Impossibile escludere: campo " + columnName + " non presente nella entity");
throw new Exception("Impossibile escludere: campo " + columnName + " non presente nella entity");
f.setAccessible(true);
Field fieldToSetRecalc = entityInterface.getClass()
.getDeclaredField(UtilityString.sqlToField(sqlField));
Field fieldToSetRecalc = entityInterface.getClass().getDeclaredField(UtilityString.sqlToField(sqlField));
if (fieldToSetRecalc != null) {
fieldToSetRecalc.setAccessible(true);
fieldToSetRecalc.set(entityInterface, null);
@@ -970,14 +944,15 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
}
execStoredProcedure();
managePriorityPost();
// if (this.getClass().getAnnotation(Master.class) != null) {
// String publicationId = AsyncManager.getPublicationIdIfExists(connection, this);
//
// if (publicationId != null) {
// if (transactionGroupId == null) transactionGroupId = AsyncManager.getNextTransactionGroupId(connection);
// AsyncManager.saveNewTransaction(connection, this, transactionGroupId);
// }
// }
if (this.getClass().getAnnotation(Master.class) != null) {
String publicationId = AsyncManager.getPublicationIdIfExists(dbName, this);
if (publicationId != null) {
if (transactionGroupId == null) transactionGroupId = AsyncManager.getNextTransactionGroupId(connection);
AsyncManager.saveNewTransaction(connection, this, transactionGroupId);
}
}
}
public void insert() throws Exception {
@@ -1002,9 +977,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
String sql = "SELECT CAST(count(*) as BIT) FROM " + this.getTableName();
sql = UtilityDB.addwhereCond(sql, wherePK, false);
boolean existEntity = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql);
return existEntity;
return UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql);
}
@@ -1026,8 +999,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
for (int i = 0; i < chain.size(); i++) {
EntityBase child = chain.get(i);
child.setUsername(this.username);
child.manageWithParentConnection(connection, child.getOperation(), getCompletingManager(),
entityHolder);
child.manageWithParentConnection(connection, child.getOperation(), getCompletingManager(), entityHolder);
}
} else {
EntityBase child = ((EntityBase) object);
@@ -1046,9 +1018,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
private void managePriorityPost() throws Exception {
Integer min = 101;
List<Field> fields = Stream.of(getEntityHolder().getFields(this.getClass())).filter(x -> x.isAnnotationPresent(Priority.class))
.sortBy(x -> x.getAnnotation(Priority.class).value())
.toList();
List<Field> fields = Stream.of(getEntityHolder().getFields(this.getClass())).filter(x -> x.isAnnotationPresent(Priority.class)).sortBy(x -> x.getAnnotation(Priority.class).value()).toList();
for (Field field : fields) {
@@ -1080,10 +1050,8 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
child.setEntityHolder(entityHolder);
child.setCompletingManager(dataCompleting);
if (copyPk)
child.setParentPKAndImportFromParent(this, false);
else
child.setImportFromParent(this, false);
if (copyPk) child.setParentPKAndImportFromParent(this, false);
else child.setImportFromParent(this, false);
///////////////////////////////////////
if (child.getOperation() == OperationType.INSERT && child.select(connection) != null) {
child.setOperation(OperationType.UPDATE);
@@ -1097,9 +1065,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
private void managePriorityPre() throws Exception {
Integer max = 99;
List<Field> fields = Stream.of(getEntityHolder().getFields(this.getClass())).filter(x -> x.isAnnotationPresent(Priority.class))
.sortBy(x -> x.getAnnotation(Priority.class).value())
.toList();
List<Field> fields = Stream.of(getEntityHolder().getFields(this.getClass())).filter(x -> x.isAnnotationPresent(Priority.class)).sortBy(x -> x.getAnnotation(Priority.class).value()).toList();
for (Field field : fields) {
Priority priority = field.getAnnotation(Priority.class);
@@ -1121,24 +1087,20 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
}
}
private void manageWithParentConnection(Connection connection, OperationType op,
DroolsDataCompleting dataCompleting) throws Exception {
private void manageWithParentConnection(Connection connection, OperationType op, DroolsDataCompleting dataCompleting) throws Exception {
this.connection = connection;
this.dataCompleting = dataCompleting;
if (getOperation() == null)
setOperation(op);
if (getOperation() == null) setOperation(op);
checkPreSave();
executeManage();
}
public void manageWithParentConnection(Connection connection, OperationType op, DroolsDataCompleting dataCompleting,
EntityPropertyHolder propertyHolder) throws Exception {
public void manageWithParentConnection(Connection connection, OperationType op, DroolsDataCompleting dataCompleting, EntityPropertyHolder propertyHolder) throws Exception {
this.entityHolder = propertyHolder;
manageWithParentConnection(connection, op, dataCompleting);
}
public void manageWithParentConnection(Connection connection, OperationType op, DroolsDataCompleting dataCompleting,
EntityPropertyHolder propertyHolder, String applicationName) throws Exception {
public void manageWithParentConnection(Connection connection, OperationType op, DroolsDataCompleting dataCompleting, EntityPropertyHolder propertyHolder, String applicationName) throws Exception {
this.entityHolder = propertyHolder;
this.applicationName = applicationName;
manageWithParentConnection(connection, op, dataCompleting);
@@ -1149,40 +1111,23 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
List<ForeignKeyDTO> listConstraintDTO = new ArrayList<ForeignKeyDTO>();
List<Field> fields = getEntityHolder().getFields(this.getClass());
List<Field> found = Stream.of(fields)
.withoutNulls()
.filter(value -> value.isAnnotationPresent(FK.class) || value.isAnnotationPresent(FKContainer.class))
.toList();
List<Field> found = Stream.of(fields).withoutNulls().filter(value -> value.isAnnotationPresent(FK.class) || value.isAnnotationPresent(FKContainer.class)).toList();
List<String> tableNames = new ArrayList<>();
List<String> finalTableNames = tableNames;
Stream.of(found).filter(x -> x.isAnnotationPresent(FK.class))
.forEach(x -> finalTableNames.add(x.getAnnotation(FK.class).tableName()));
Stream.of(found).filter(x -> x.isAnnotationPresent(FK.class)).forEach(x -> finalTableNames.add(x.getAnnotation(FK.class).tableName()));
Stream.of(found).filter(x -> x.isAnnotationPresent(FKContainer.class))
.forEach(x -> finalTableNames.addAll(
Stream.of(x.getAnnotation(FKContainer.class).value()).map(FK::tableName).toList()
));
Stream.of(found).filter(x -> x.isAnnotationPresent(FKContainer.class)).forEach(x -> finalTableNames.addAll(Stream.of(x.getAnnotation(FKContainer.class).value()).map(FK::tableName).toList()));
tableNames = Stream.of(tableNames)
.distinct()
.toList();
tableNames = Stream.of(tableNames).distinct().toList();
for (final String tableName : tableNames) {
final HashMap<String, Object> sqlFields = new HashMap<>();
final EntityBase entity = this;
List<Field> matchedFields = Stream.of(fields)
.filter(value ->
(value.isAnnotationPresent(FK.class) &&
value.getAnnotation(FK.class).tableName().equalsIgnoreCase(tableName)) ||
(value.isAnnotationPresent(FKContainer.class) &&
Stream.of(value.getAnnotation(FKContainer.class).value())
.anyMatch(y -> y.tableName().equalsIgnoreCase(tableName))
))
.toList();
List<Field> matchedFields = Stream.of(fields).filter(value -> (value.isAnnotationPresent(FK.class) && value.getAnnotation(FK.class).tableName().equalsIgnoreCase(tableName)) || (value.isAnnotationPresent(FKContainer.class) && Stream.of(value.getAnnotation(FKContainer.class).value()).anyMatch(y -> y.tableName().equalsIgnoreCase(tableName)))).toList();
for (Field field : matchedFields) {
try {
@@ -1193,10 +1138,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
if (field.isAnnotationPresent(FK.class)) {
fkVal = field.getAnnotation(FK.class);
} else if (field.isAnnotationPresent(FKContainer.class)) {
fkVal = Stream.of(field.getAnnotation(FKContainer.class).value())
.filter(x -> x.tableName().equalsIgnoreCase(tableName))
.toList()
.get(0);
fkVal = Stream.of(field.getAnnotation(FKContainer.class).value()).filter(x -> x.tableName().equalsIgnoreCase(tableName)).toList().get(0);
}
if (!UtilityString.isNullOrEmpty(fkVal.columnName())) {
@@ -1245,8 +1187,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
// NB: aiuta a rispettare la regola del default nel troncare la
// data anche se passata dall'esterno
if (object instanceof Date
&& (CommonConstants.SYSDATE.equals(format) || CommonConstants.SYSDATE.equals(defaultValue))) {
if (object instanceof Date && (CommonConstants.SYSDATE.equals(format) || CommonConstants.SYSDATE.equals(defaultValue))) {
field.set(this, DateUtils.truncate(object, Calendar.DAY_OF_MONTH));
}
@@ -1267,9 +1208,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
// controllo sui campi fired di testata
if (getOperation() == OperationType.NO_OP) {
executeRecalc = false;
} else if (getOperation() == OperationType.INSERT ||
getOperation() == OperationType.SUBSTITUTE ||
getOperation() == OperationType.DELETE_THEN_INSERT) {
} else if (getOperation() == OperationType.INSERT || getOperation() == OperationType.SUBSTITUTE || getOperation() == OperationType.DELETE_THEN_INSERT) {
executeRecalc = true;
} else if (fieldToFireRecalc != null && !fieldToFireRecalc.isEmpty()) {
//verificare se i arrivano in input
@@ -1287,14 +1226,11 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
selectAndMergeEntity(connection, this);
}
if (getNativeSql() == null)
getCompletingManager().complete(this, connection, username);
if (getNativeSql() == null) getCompletingManager().complete(this, connection, username);
getCompletingManager().invokeCheckRules(this, connection, username);
List<Field> fields = Stream.of(getEntityHolder().getFields(this.getClass()))
.filter(x -> x.isAnnotationPresent(EntityChild.class))
.toList();
List<Field> fields = Stream.of(getEntityHolder().getFields(this.getClass())).filter(x -> x.isAnnotationPresent(EntityChild.class)).toList();
for (Field field : fields) {
Boolean copyPk = field.getAnnotation(EntityChild.class).copyPk();
@@ -1333,8 +1269,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
private void selectChildFromDb(EntityBase child) throws IllegalAccessException {
// controllo sui campi fired di riga
if (getEntityHolder().getFieldToFireMap(child.getClass().getSimpleName()) != null
&& !getEntityHolder().getFieldToFireMap(child.getClass().getSimpleName()).isEmpty()) {
if (getEntityHolder().getFieldToFireMap(child.getClass().getSimpleName()) != null && !getEntityHolder().getFieldToFireMap(child.getClass().getSimpleName()).isEmpty()) {
if (child.getOperation() == OperationType.INSERT || child.getOperation() == OperationType.DELETE) {
executeRecalc = true;
} else if (child.getOperation() == OperationType.UPDATE || child.getOperation() == OperationType.INSERT_OR_UPDATE) {
@@ -1379,11 +1314,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
getCompletingManager().invokeCheckRules(child, connection, username);
} else {
if (child.getNativeSql() == null) {
if (child.getOperation() == OperationType.UPDATE ||
child.getOperation() == OperationType.SUBSTITUTE ||
child.getOperation() == OperationType.INSERT_OR_UPDATE ||
child.getOperation() == OperationType.DELETE_THEN_INSERT ||
((this.getOperation() == OperationType.SUBSTITUTE || this.getOperation() == OperationType.DELETE_THEN_INSERT) && !checkPkValueNull(child))) {
if (child.getOperation() == OperationType.UPDATE || child.getOperation() == OperationType.SUBSTITUTE || child.getOperation() == OperationType.INSERT_OR_UPDATE || child.getOperation() == OperationType.DELETE_THEN_INSERT || ((this.getOperation() == OperationType.SUBSTITUTE || this.getOperation() == OperationType.DELETE_THEN_INSERT) && !checkPkValueNull(child))) {
selectAndMergeEntity(connection, child);
}
child.setApplicationName(applicationName);
@@ -1439,8 +1370,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
Map<Integer, Object> mapLob = getFieldToQuery(fields, campi, valori);
if (campi.size() != 0) {
String sql = "INSERT INTO " + getTableName() + "(" + StringUtils.join(campi, ",") + ") " +
"VALUES (" + StringUtils.join(valori, ",") + ")";
String sql = "INSERT INTO " + getTableName() + "(" + StringUtils.join(campi, ",") + ") " + "VALUES (" + StringUtils.join(valori, ",") + ")";
boolean containsIdentity;
String identityFieldName = null;
@@ -1476,8 +1406,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
throw new EntityException(e, this, sql);
}
} else {
throw new Exception("Nessun campo valorizzato per la entity " + getTableName()
+ " (Controllare metodi get/set della entity)");
throw new Exception("Nessun campo valorizzato per la entity " + getTableName() + " (Controllare metodi get/set della entity)");
}
}
@@ -1487,13 +1416,11 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
if (val instanceof Clob) {
if (EmsRestConstants.NULL.equals(((Clob) val).getSubString(1L, (int) ((Clob) val).length())))
pstm.setNull(entry.getKey(), java.sql.Types.CLOB);
else
pstm.setClob(entry.getKey(), (Clob) val);
else pstm.setClob(entry.getKey(), (Clob) val);
} else if (val instanceof Blob) {
if (EmsRestConstants.NULL.equals(new String(((Blob) val).getBytes(1L, (int) ((Blob) val).length()))))
pstm.setNull(entry.getKey(), java.sql.Types.BLOB);
else
pstm.setBlob(entry.getKey(), (Blob) val);
else pstm.setBlob(entry.getKey(), (Blob) val);
}
}
}
@@ -1548,9 +1475,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
}
public void setParentPKAndImportFromParent(EntityBase parent, Boolean isChild) throws InvocationTargetException, IllegalAccessException {
List<Field> pkField = Stream.of(parent.getClass().getDeclaredFields())
.filter(x -> x.isAnnotationPresent(PK.class) && x.isAnnotationPresent(SqlField.class))
.toList();
List<Field> pkField = Stream.of(parent.getClass().getDeclaredFields()).filter(x -> x.isAnnotationPresent(PK.class) && x.isAnnotationPresent(SqlField.class)).toList();
for (Field field : pkField) {
field.setAccessible(true);
@@ -1558,8 +1483,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
if (obj != null) {
String mName = "set" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
Method m = ReflectionUtils.findMethod(getClass(), mName, obj.getClass());
if (m != null)
m.invoke(this, obj);
if (m != null) m.invoke(this, obj);
}
}
setImportFromParent(parent, isChild);
@@ -1568,9 +1492,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
private void updateChildrenForeignIdentity() throws IllegalAccessException {
List<Field> fields = getEntityHolder().getFields(this.getClass());
Optional<Field> identityOptionalField = Stream.of(fields)
.filter(x -> x.isAnnotationPresent(Identity.class))
.findFirst();
Optional<Field> identityOptionalField = Stream.of(fields).filter(x -> x.isAnnotationPresent(Identity.class)).findFirst();
if (identityOptionalField.isPresent()) {
Field identityField = identityOptionalField.get();
@@ -1578,9 +1500,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
SqlField sqlObject = identityField.getAnnotation(SqlField.class);
List<Field> entityChildFields = Stream.of(fields)
.filter(x -> x.isAnnotationPresent(EntityChild.class))
.toList();
List<Field> entityChildFields = Stream.of(fields).filter(x -> x.isAnnotationPresent(EntityChild.class)).toList();
for (Field entityChildField : entityChildFields) {
entityChildField.setAccessible(true);
@@ -1603,12 +1523,10 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
}
private void setParentIdentityIfExists(String parentIdentityFieldName, Long value) throws IllegalAccessException {
Optional<Field> importFromParentFieldOptional = Stream.of(getClass().getDeclaredFields())
.filter(x -> {
x.setAccessible(true);
return x.isAnnotationPresent(ImportFromParent.class) && x.getAnnotation(ImportFromParent.class).value().equals(parentIdentityFieldName);
})
.findFirst();
Optional<Field> importFromParentFieldOptional = Stream.of(getClass().getDeclaredFields()).filter(x -> {
x.setAccessible(true);
return x.isAnnotationPresent(ImportFromParent.class) && x.getAnnotation(ImportFromParent.class).value().equals(parentIdentityFieldName);
}).findFirst();
if (importFromParentFieldOptional.isPresent()) {
Field importFromParentField = importFromParentFieldOptional.get();
@@ -1638,8 +1556,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
this.setWhereCond((UtilityString.isNullOrEmpty(this.getWhereCond()) ? "" : this.whereCond + " AND ") + parent.getWhereCond());
}
List<Field> fields = Stream.of(getEntityHolder().getFields(this.getClass()))
.filter(x -> x.isAnnotationPresent(ImportFromParent.class)).toList();
List<Field> fields = Stream.of(getEntityHolder().getFields(this.getClass())).filter(x -> x.isAnnotationPresent(ImportFromParent.class)).toList();
for (Field field : fields) {
ImportFromParent ifp = field.getAnnotation(ImportFromParent.class);
@@ -1670,8 +1587,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
String mName = "set" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
if (obj != null) {
Method m = ReflectionUtils.findMethod(getClass(), mName, obj.getClass());
if (m != null)
m.invoke(this, obj);
if (m != null) m.invoke(this, obj);
}
} else {
logger.trace(fieldName + " non trovato in " + parent.getClass());
@@ -1679,8 +1595,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
}
if (getOperation() == null && !loadedFromDb)
setOperation(parent.getOperation());
if (getOperation() == null && !loadedFromDb) setOperation(parent.getOperation());
}
@@ -1751,9 +1666,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
private List<String> getPkWhereCond(Field[] fields, EntityBase parent) throws IllegalAccessException {
List<String> where = new ArrayList<String>();
List<Field> listPK = Stream.of(fields)
.filter(x -> x.isAnnotationPresent(SqlField.class) && x.isAnnotationPresent(PK.class))
.toList();
List<Field> listPK = Stream.of(fields).filter(x -> x.isAnnotationPresent(SqlField.class) && x.isAnnotationPresent(PK.class)).toList();
for (Field field : listPK) {
field.setAccessible(true);
@@ -1791,9 +1704,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
MinIOService minIOService = ContextLoader.getCurrentWebApplicationContext().getBean(MinIOService.class);
if (minIOService != null &&
minIOService.isEnabled() &&
!SettingsModel.getInstance().getMinioConfiguration().getExcludedEntities().contains(this.getTableName())) {
if (minIOService != null && minIOService.isEnabled() && !SettingsModel.getInstance().getMinioConfiguration().getExcludedEntities().contains(this.getTableName())) {
Field fieldRefUuid = null;
try {
@@ -1856,8 +1767,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
Iterator<Entry<String, Object>> iterator = map.iterator();
while (iterator.hasNext()) {
final String campo = iterator.next().getKey();
Optional<Field> fieldOptional =
Stream.of(fields).filter(field -> field.getName().equalsIgnoreCase(campo) && field.getAnnotation(SqlField.class) != null).findFirst();
Optional<Field> fieldOptional = Stream.of(fields).filter(field -> field.getName().equalsIgnoreCase(campo) && field.getAnnotation(SqlField.class) != null).findFirst();
if (fieldOptional.isEmpty()) {
throw new FieldMissingException(campo);
@@ -1886,8 +1796,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
return whereCondOldPk;
}
private Map<Integer, Object> getFieldToQuery(List<Field> fields, List<String> campi, List<String> valori)
throws Exception {
private Map<Integer, Object> getFieldToQuery(List<Field> fields, List<String> campi, List<String> valori) throws Exception {
Map<Integer, Object> map = new HashMap<Integer, Object>();
Integer counter = 1;
@@ -1903,9 +1812,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
MinIOService minIOService = ContextLoader.getCurrentWebApplicationContext().getBean(MinIOService.class);
if (minIOService != null &&
minIOService.isEnabled() &&
!SettingsModel.getInstance().getMinioConfiguration().getExcludedEntities().contains(this.getTableName())) {
if (minIOService != null && minIOService.isEnabled() && !SettingsModel.getInstance().getMinioConfiguration().getExcludedEntities().contains(this.getTableName())) {
String refUuid = null;
@@ -1919,8 +1826,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
valori.add(SqlFieldHolder.getSqlValueField(refUuid).toString());
}
if (!SettingsModel.getInstance().getMinioConfiguration().isEnableOldSave())
continue;
if (!SettingsModel.getInstance().getMinioConfiguration().isEnableOldSave()) continue;
}
}
@@ -1930,13 +1836,11 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
defaultVal = sqlField.defaultObjectValue();
SimpleDateFormat sdf = null;
if (CommonConstants.SYSDATE.equals(defaultVal))
sdf = new SimpleDateFormat("yyyy-MM-dd");
if (CommonConstants.SYSDATE.equals(defaultVal)) sdf = new SimpleDateFormat("yyyy-MM-dd");
else if (CommonConstants.TIMESTAMP.equals(defaultVal))
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (sdf != null)
defaultVal = sdf.format(new Date());
if (sdf != null) defaultVal = sdf.format(new Date());
maxValueLength = sqlField.maxLength();
nullableValue = sqlField.nullable();
@@ -1956,8 +1860,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
if ((obj != null || !UtilityString.isNullOrEmpty(defaultVal)) && (sqlField = field.getAnnotation(SqlField.class)) != null && !field.getName().startsWith("refUuid")) {
// esclusione colonne per sincronizzazione
if (excludedColumns != null
&& excludedColumns.contains(SqlFieldHolder.getSqlValue(sqlField.value(), field)))
if (excludedColumns != null && excludedColumns.contains(SqlFieldHolder.getSqlValue(sqlField.value(), field)))
continue;
if (field.getAnnotation(it.integry.ems_model.annotation.Clob.class) != null) {
setupClobData(counter, map, obj);
@@ -1975,9 +1878,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
String value = SqlFieldHolder.getSqlValueField(obj == null ? defaultVal : obj, sqlField.trimSpaces()).toString();
if (obj instanceof String) {
value = value
.replaceAll("\r", "' + CHAR(13) + '")
.replaceAll("\n", "' + CHAR(10) + '");
value = value.replaceAll("\r", "' + CHAR(13) + '").replaceAll("\n", "' + CHAR(10) + '");
if (maxValueLength >= 0 && !((String) obj).equalsIgnoreCase(EmsRestConstants.NULL) && ((String) obj).length() > maxValueLength)
throw new FieldLengthException(sqlField.value(), maxValueLength);
}
@@ -1990,8 +1891,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
return map;
}
private Map<Integer, Object> getFieldToUpdate(List<Field> fields, List<String> campi, List<String> where)
throws Exception {
private Map<Integer, Object> getFieldToUpdate(List<Field> fields, List<String> campi, List<String> where) throws Exception {
Integer counter = 1;
Map<Integer, Object> mapLob = new HashMap<>();
@@ -1999,19 +1899,15 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
field.setAccessible(true);
Object obj = field.get(this);
if (obj == null)
continue;
if (obj == null) continue;
if (field.isAnnotationPresent(SqlField.class) && field.isAnnotationPresent(Identity.class))
continue;
if (field.isAnnotationPresent(SqlField.class) && field.isAnnotationPresent(Identity.class)) continue;
if (field.isAnnotationPresent(ObjectStorage.class)) {
ObjectStorage objectStorage = field.getAnnotation(ObjectStorage.class);
MinIOService minIOService = ContextLoader.getCurrentWebApplicationContext().getBean(MinIOService.class);
if (minIOService != null &&
minIOService.isEnabled() &&
!SettingsModel.getInstance().getMinioConfiguration().getExcludedEntities().contains(this.getTableName())) {
if (minIOService != null && minIOService.isEnabled() && !SettingsModel.getInstance().getMinioConfiguration().getExcludedEntities().contains(this.getTableName())) {
String refUuid = null;
if (obj instanceof String)
@@ -2022,8 +1918,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
campi.add("ref_uuid" + (objectStorage.suffix() > 0 ? objectStorage.suffix() : "") + " = " + SqlFieldHolder.getSqlValueField(refUuid));
if (!SettingsModel.getInstance().getMinioConfiguration().isEnableOldSave())
continue;
if (!SettingsModel.getInstance().getMinioConfiguration().isEnableOldSave()) continue;
}
}
@@ -2040,8 +1935,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
if (getOperation() != OperationType.INSERT) {
// esclusione colonne per sincronizzazione
if (excludedColumns != null && (excludedColumns.contains(sqlField.value())
|| excludedColumns.contains(field.getName())))
if (excludedColumns != null && (excludedColumns.contains(sqlField.value()) || excludedColumns.contains(field.getName())))
continue;
}
@@ -2077,8 +1971,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
Blob blobData = connection.createBlob();
byte[] blob;
if (EmsRestConstants.NULL.equals(obj.toString()))
blob = obj.toString().getBytes();
if (EmsRestConstants.NULL.equals(obj.toString())) blob = obj.toString().getBytes();
else
// base64 conversion
blob = Base64.decodeBase64(obj.toString());
@@ -2092,8 +1985,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
Clob clobData = connection.createClob();
String clob;
if (EmsRestConstants.NULL.equals(obj.toString()))
clob = obj.toString();
if (EmsRestConstants.NULL.equals(obj.toString())) clob = obj.toString();
else
// base64 conversion
clob = new String(Base64.decodeBase64(obj.toString()));
@@ -2190,9 +2082,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
public void resetIdentiy(Connection connection) throws Exception {
Field[] fields = this.getClass().getDeclaredFields();
Optional<Field> identityField = Stream.of(fields)
.filter(x -> x.isAnnotationPresent(Identity.class) && x.isAnnotationPresent(SqlField.class))
.findFirst();
Optional<Field> identityField = Stream.of(fields).filter(x -> x.isAnnotationPresent(Identity.class) && x.isAnnotationPresent(SqlField.class)).findFirst();
if (identityField.isPresent()) {
String tableName = this.getTableName();

View File

@@ -13,8 +13,6 @@ public interface EntityInterface {
void checkPreSave() throws Exception;
void checkPreCond(Connection connection) throws Exception;
void insert() throws Exception;
void update() throws Exception;
@@ -41,6 +39,8 @@ public interface EntityInterface {
void setApplicationName(String applicationName);
void setDbName(String dbName);
@JsonIgnore
void setApplicationNameDB(String profileDB) throws Exception;

View File

@@ -60,7 +60,7 @@ public class CtbMovt extends EntityBase {
@SqlField(value = "cod_ireg", maxLength = 5, nullable = true)
private String codIreg;
@SqlField(value = "num_ireg", nullable = true)
@SqlField(value = "num_ireg", nullable = true, defaultObjectValue = "0")
private Integer numIreg;
@SqlField(value = "num_prot", nullable = true, defaultObjectValue = "0")

View File

@@ -7,6 +7,7 @@ import it.integry.ems_model.annotation.*;
import it.integry.ems_model.base.EntityBase;
import it.integry.ems_model.types.ApplicationName;
import org.kie.api.definition.type.PropertyReactive;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
@@ -708,7 +709,7 @@ public class GtbAnag extends EntityBase {
for (CtbPlafondIva ctbPlafondIva : getCtbPlafondIva()) {
ctbPlafondIva.manageWithParentConnection(connection, ctbPlafondIva.getOperation(), dataCompleting, entityHolder);
}
if (applicationName.compareTo(ApplicationName.TEXTILES.toString()) == 0) {
if (applicationName.equalsIgnoreCase(ApplicationName.TEXTILES.toString())) {
for (TtbClieLine ttbClieLine : getTtbClieLine()) {
ttbClieLine.manageWithParentConnection(connection, ttbClieLine.getOperation(), dataCompleting, entityHolder);
}
@@ -747,7 +748,7 @@ public class GtbAnag extends EntityBase {
vtbClieFido.deleteAllEntities(connection, this);
VtbDest vtbDest = new VtbDest();
vtbDest.deleteAllEntities(connection, this);
if (applicationName.compareTo(ApplicationName.TEXTILES.toString()) == 0) {
if (applicationName.equalsIgnoreCase(ApplicationName.TEXTILES.toString())) {
TtbClieLine ttbClieLine = new TtbClieLine();
ttbClieLine.deleteAllEntities(connection, this);
}

View File

@@ -6,8 +6,8 @@ import it.integry.common.var.CommonConstants;
import it.integry.ems_model.annotation.*;
import it.integry.ems_model.base.EntityBase;
import it.integry.ems_model.types.ApplicationName;
import it.integry.ems_model.utility.UtilityDB;
import org.kie.api.definition.type.PropertyReactive;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
@@ -689,7 +689,7 @@ public class MtbLisvData extends EntityBase {
@Override
protected void deleteChilds() throws Exception {
if (applicationName.compareTo(ApplicationName.TEXTILES.toString()) == 0) {
if (applicationName.equalsIgnoreCase(ApplicationName.TEXTILES.toString())) {
String query = "DELETE FROM ttb_lisv_taglie_data " + "WHERE cod_vlis = '" + getCodVlis() + "' AND " + "versione = " + getVersione() + " AND " + "cod_style = '" + getCodMart() + "' ";
connection.createStatement().executeUpdate(query);
}

View File

@@ -0,0 +1,84 @@
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.base.EntityBase;
import org.kie.api.definition.type.PropertyReactive;
@Master
@PropertyReactive
@Table(StbPublicationsDetail.ENTITY)
@JsonTypeName(StbPublicationsDetail.ENTITY)
public class StbPublicationsDetail extends EntityBase {
private static final long serialVersionUID = 1L;
public static final String ENTITY = "stb_publications_detail";
@PK
@SqlField(value = "entity_name")
private String entityName;
@PK
@SqlField(value = "publication_id")
private String publicationId;
@SqlField(value = "recalc_columns")
private String recalcColumns;
@SqlField(value = "syncronize", defaultObjectValue="S")
private String syncronize;
@SqlField(value = "where_cond_sql")
private String whereCondSql;
public String getEntityName() {
return entityName;
}
public StbPublicationsDetail setEntityName(String entityName) {
this.entityName = entityName;
return this;
}
public String getPublicationId() {
return publicationId;
}
public StbPublicationsDetail setPublicationId(String publicationId) {
this.publicationId = publicationId;
return this;
}
public String getRecalcColumnsField() {
return recalcColumns;
}
public StbPublicationsDetail setRecalcColumns(String recalcColumns) {
this.recalcColumns = recalcColumns;
return this;
}
public String getSyncronize() {
return syncronize;
}
public StbPublicationsDetail setSyncronize(String syncronize) {
this.syncronize = syncronize;
return this;
}
public String getWhereCondSql() {
return whereCondSql;
}
public StbPublicationsDetail setWhereCondSql(String whereCondSql) {
this.whereCondSql = whereCondSql;
return this;
}
@Override
public void checkPreSave() throws Exception {}
}

View File

@@ -1,12 +1,11 @@
package it.integry.ems_model.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import it.integry.ems_model.annotation.*;
import it.integry.ems_model.base.EntityBase;
import it.integry.ems_model.types.ApplicationName;
import org.kie.api.definition.type.PropertyReactive;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
@@ -1016,7 +1015,7 @@ public class VtbClie extends EntityBase {
@Override
protected void insertChilds() throws Exception {
if (applicationName.compareTo(ApplicationName.TEXTILES.toString()) == 0) {
if (applicationName.equalsIgnoreCase(ApplicationName.TEXTILES.toString())) {
for (TtbClieLine ttbClieLine : getTtbClieLine()) {
ttbClieLine.manageWithParentConnection(connection, ttbClieLine.getOperation(), dataCompleting, entityHolder);
}
@@ -1030,7 +1029,7 @@ public class VtbClie extends EntityBase {
@Override
protected void deleteChilds() throws Exception {
if (applicationName.compareTo(ApplicationName.TEXTILES.toString()) == 0) {
if (applicationName.equalsIgnoreCase(ApplicationName.TEXTILES.toString())) {
TtbClieLine ttbClieLine = new TtbClieLine();
ttbClieLine.deleteAllEntities(connection, this);
}

View File

@@ -1,7 +1,6 @@
package it.integry.ems_model.rulescompleting;
import it.integry.annotations.PostContextConstruct;
import it.integry.ems.object_storage.minio.sdk.messages.Rule;
import it.integry.ems.utility.UtilityDebug;
import it.integry.ems.utility.UtilityFile;
import it.integry.ems_model.base.EntityInterface;
@@ -21,8 +20,12 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PreDestroy;
import java.io.*;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.sql.Connection;
@Service
@@ -163,14 +166,14 @@ public class DroolsDataCompleting {
}
private <T> void serialize(T o, File outputFile) throws IOException {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(outputFile));
ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(outputFile.toPath()));
out.writeObject(o);
out.close();
}
private <T> T deserialize(Class<T> klass, File inputFile) throws IOException, ClassNotFoundException {
T t = null;
ObjectInputStream in = new ObjectInputStream(new FileInputStream(inputFile));
ObjectInputStream in = new ObjectInputStream(Files.newInputStream(inputFile.toPath()));
t = klass.cast(in.readObject());
in.close();
return t;

View File

@@ -32,6 +32,9 @@ public class FirebaseService {
private final Logger logger = LogManager.getLogger();
private boolean initialize() throws Exception {
boolean isDryRunCheckEnabled = !setupGest.getSetupBoolean("FIREBASE", "NOTIFICATION", "DISABLE_DRY_RUN_CHECK");
dryRun = UtilityDebug.isDebugExecution() && isDryRunCheckEnabled;
if (!FirebaseApp.getApps().isEmpty()) {
return true;
}
@@ -40,9 +43,6 @@ public class FirebaseService {
return false;
}
boolean isDryRunCheckEnabled = !setupGest.getSetupBoolean("FIREBASE", "NOTIFICATION", "DISABLE_DRY_RUN_CHECK");
dryRun = UtilityDebug.isDebugExecution() && isDryRunCheckEnabled;
InputStream refreshToken;
try {
URL url = new URL(this.getFirebaseEndpoint());

View File

@@ -1044,9 +1044,9 @@ public class ActivityService {
}
public List<ActivityProductsDTO> getProducts() throws Exception {
String sql = "SELECT cod_mart, descrizione, cod_mgrp, cod_msgr \n" +
String sql = "SELECT cod_mart, IsNull(descr_cassa, descrizione) as descrizione, cod_mgrp, cod_msgr \n" +
"FROM mtb_aart \n" +
"WHERE ((cod_mgrp = '04' and cod_msgr = '0401') OR (cod_mgrp = '02' AND cod_msgr = '0202')) and flag_stato = 'A' \n" +
"WHERE cod_mtip is not null and flag_stato = 'A' \n" +
"ORDER BY descrizione";
return UtilityDB.executeSimpleQueryDTO(multiDBTransactionManager.getPrimaryConnection(), sql, ActivityProductsDTO.class);

View File

@@ -37,7 +37,6 @@ public class DistribuzioneColliService {
MultiDBTransactionManager multiDBTransactionManager = ContextLoader.getCurrentWebApplicationContext().getBean(MultiDBTransactionManager.class);
EntityProcessor entityProcessor = ContextLoader.getCurrentWebApplicationContext().getBean(EntityProcessor.class);
ProductServices productServices = ContextLoader.getCurrentWebApplicationContext().getBean(ProductServices.class);
LogisticService logisticService = ContextLoader.getCurrentWebApplicationContext().getBean(LogisticService.class);
SetupGest setupGest = ContextLoader.getCurrentWebApplicationContext().getBean(SetupGest.class);
String flagRaggXQtaCnf = setupGest.getSetup(multiDBTransactionManager.getPrimaryConnection(), "PICKING", "SETUP", "DISTRIBUISCI_X_QTA_CNF");
@@ -101,7 +100,8 @@ public class DistribuzioneColliService {
mtbColtData.add(mtbColtDataHash);
String sqlSelectMtbColrs = "SELECT mtb_colr.*, mtb_aart.flag_qta_cnf_fissa as flagQtaCnfFissa FROM mtb_colr, mtb_aart WHERE mtb_colr.cod_mart = mtb_aart.cod_mart AND " + UtilityQuery.concatFieldListInWhereCond(mtbColtData);
String sqlSelectMtbColrs = "SELECT mtb_colr.*, mtb_aart.flag_qta_cnf_fissa as flagQtaCnfFissa " +
"FROM mtb_colr, mtb_aart WHERE mtb_colr.cod_mart = mtb_aart.cod_mart AND " + UtilityQuery.concatFieldListInWhereCond(mtbColtData);
PreparedStatement psMtbColr = multiDBTransactionManager.prepareStatement(sqlSelectMtbColrs);
psMtbColr.setQueryTimeout(30);

View File

@@ -82,28 +82,30 @@ public class ProductionOrderDataHandlerService {
}
private void loadOrdiniProfile(boolean onlyInevasi, String dbName, String profileName, HashMap<String, HashMap<String, List<OrdineLavorazioneDTO>>> orderList) throws Exception {
MultiDBTransactionManager multiDBTransactionManager = new MultiDBTransactionManager(profileName, false);
Date startDate = new Date();
//Verifichiamo se la gestione del MES è abilitata
boolean gestioneAbilitata = isMESEnabled(multiDBTransactionManager);
if (gestioneAbilitata) {
try {
Date startDate = new Date();
//Verifichiamo se la gestione del MES è abilitata
boolean gestioneAbilitata = isMESEnabled(multiDBTransactionManager);
List<OrdineLavorazioneDTO> ordiniLav = getOrdiniLavorazione(multiDBTransactionManager, onlyInevasi ? "I" : null, null, null, null, null);
HashMap<String, List<OrdineLavorazioneDTO>> section = getSectionByDBName(orderList, dbName);
section.clear();
if (ordiniLav != null)
Stream.of(ordiniLav).groupBy(OrdineLavorazioneDTO::getCodJfas)
.forEach(x -> {
List<OrdineLavorazioneDTO> listToUpdate = getListByCodJfas(section, x.getKey());
listToUpdate.addAll(x.getValue());
});
if (gestioneAbilitata) {
List<OrdineLavorazioneDTO> ordiniLav = getOrdiniLavorazione(multiDBTransactionManager, onlyInevasi ? "I" : null, null, null, null, null);
HashMap<String, List<OrdineLavorazioneDTO>> section = getSectionByDBName(orderList, dbName);
section.clear();
if (ordiniLav != null)
Stream.of(ordiniLav).groupBy(OrdineLavorazioneDTO::getCodJfas)
.forEach(x -> {
List<OrdineLavorazioneDTO> listToUpdate = getListByCodJfas(section, x.getKey());
listToUpdate.addAll(x.getValue());
});
logger.trace(ProductionOrderDataHandlerService.class.getSimpleName() + ": Timing " + ((new Date().getTime() - startDate.getTime()) / 1000) + " secs");
logger.trace(ProductionOrderDataHandlerService.class.getSimpleName() + ": Timing " + ((new Date().getTime() - startDate.getTime()) / 1000) + " secs");
}
} finally {
multiDBTransactionManager.closeAll();
}
multiDBTransactionManager.closeAll();
}

View File

@@ -8,6 +8,7 @@ import it.integry.ems.utility.UtilityEntity;
import it.integry.ems_model.base.EntityBase;
import it.integry.ems_model.db.ResultSetMapper;
import it.integry.ems_model.entity.CarelliGiacenzaProg;
import it.integry.ems_model.entity.MtbColt;
import it.integry.ems_model.entity.MtbInvenr;
import it.integry.ems_model.service.SetupGest;
import it.integry.ems_model.types.OperationType;
@@ -86,13 +87,12 @@ public class GiacenzaService {
"WHERE carelli_giacenza_prog.cod_mdep = %s", codMdep);
List<String> articoliSalvati = UtilityDB.executeSimpleQueryOnlyFirstColumn(multiDBTransactionManager.getPrimaryConnection(), sql);
nuoviInserimenti(codMdep, queryArt);
logger.debug(String.format(GiacenzaService.class.getSimpleName() + " - Deposito %s - Popolamento da griglia: Timing " + ((new Date().getTime() - startDate.getTime()) / 1000) + " secs", codMdep));
popolaQtaCarInventario(codMdep, queryArt, articoliSalvati, codDtipRett);
logger.debug(String.format(GiacenzaService.class.getSimpleName() + " - Deposito %s - Popolamento da inventario: Timing " + ((new Date().getTime() - startDate.getTime()) / 1000) + " secs", codMdep));
popolaQtaMovimenti(codMdep, queryArt, articoliSalvati);
logger.debug(String.format(GiacenzaService.class.getSimpleName() + " - Deposito %s - Popolamento da movimenti: Timing " + ((new Date().getTime() - startDate.getTime()) / 1000) + " secs", codMdep));
nuoviInserimenti(codMdep, queryArt);
logger.debug(String.format(GiacenzaService.class.getSimpleName() + " - Deposito %s - Popolamento da griglia: Timing " + ((new Date().getTime() - startDate.getTime()) / 1000) + " secs", codMdep));
}
private void nuoviInserimenti(String codMdep, String queryArt) throws Exception {
@@ -174,8 +174,7 @@ public class GiacenzaService {
" IsNull(giac.qta_iniz, 0) as qta_iniz,\n" +
" isNull(SUM(movimenti.qta_car * art.qta_std) , 0) + IsNull(giac.qta_iniz, 0) as qta_car,\n" +
" isNull(SUM(movimenti.qta_scar * art.qta_std), 0) as qta_scar,\n" +
" getdate() as data_ins,\n" +
" max(movimenti.tipo_car) as tipo_car\n" +
" getdate() as data_ins\n" +
"FROM movimenti\n" +
" INNER JOIN art ON movimenti.cod_mart = art.cod_mart\n" +
" LEFT OUTER JOIN carelli_giacenza_prog giac ON giac.cod_mdep = movimenti.cod_mdep AND giac.cod_mart = art.cod_mart_mov\n" +
@@ -204,19 +203,17 @@ public class GiacenzaService {
private void popolaQtaCarInventario(String codMdep, String queryArt, List<String> articoliSalvati, String codDtipRett) throws Exception {
String sql =
Query.format("SELECT min(data_reg) from carelli_giacenza_prog WHERE cod_mdep = %s and id_inventario is not null", codMdep);
Query.format("SELECT min(id_inventario) from carelli_giacenza_prog WHERE cod_mdep = %s and id_inventario is not null", codMdep);
Date dataIniz = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(multiDBTransactionManager.getPrimaryConnection(), sql);
Integer maxIdInv = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(multiDBTransactionManager.getPrimaryConnection(), sql);
if (dataIniz == null) {
String dataParm = setupGest.getSetupDepo(multiDBTransactionManager.getPrimaryConnection(), "DATI_AZIENDA", "GIACENZA_DA_INV", "DATA_INIZ", codMdep);
if (!UtilityString.isNullOrEmpty(dataParm))
dataIniz = UtilityString.parseDate(dataParm);
else
throw new Exception(String.format("Data inizio popolamento non valorizzata per il depostio %s", codMdep));
}
String dataParm = setupGest.getSetupDepo(multiDBTransactionManager.getPrimaryConnection(), "DATI_AZIENDA", "GIACENZA_DA_INV", "DATA_INIZ", codMdep);
Date dataIniz ;
if (!UtilityString.isNullOrEmpty(dataParm))
dataIniz = UtilityString.parseDate(dataParm);
else
throw new Exception(String.format("Data inizio popolamento non valorizzata per il depostio %s", codMdep));
sql =
Query.format(
@@ -227,7 +224,9 @@ public class GiacenzaService {
"FROM mtb_invent\n " +
"WHERE cod_mdep = %s AND \n" +
"data_inventario >= %s AND\n " +
(maxIdInv!=null?"id_inventario>"+maxIdInv + " AND \n":"") +
"flag_stato <> 2 \n " +
"AND EXISTS(SELECT * FROM mtb_invenr WHERE mtb_invent.id_inventario = mtb_invenr.id_inventario and mtb_invent.cod_mdep = mtb_invenr.cod_mdep ) " +
"AND NOT EXISTS(SELECT * FROM carelli_giacenza_prog WHERE mtb_invent.id_inventario = carelli_giacenza_prog.id_inventario AND mtb_invent.cod_mdep = carelli_giacenza_prog.cod_mdep )",
codMdep, dataIniz);
@@ -335,6 +334,7 @@ public class GiacenzaService {
" INNER JOIN (" + queryArt + ") art on mtb_colr.cod_mart = art.cod_mart\n" +
"WHERE mtb_colt.cod_dtip_provv = %s\n" +
" AND mtb_colt.data_collo > %s\n" +
" AND mtb_colt.cod_dtip is null \n" +
" AND mtb_colt.cod_mdep = %s\n" +
"GROUP BY art.cod_mart_mov, mtb_colt.data_collo",
codDtipRett, dataIniz, codMdep);
@@ -344,9 +344,10 @@ public class GiacenzaService {
List<CarelliGiacenzaProg> carelliGiacenzaProgs = new ArrayList<>();
for (HashMap<String, Object> doc : datiDoc) {
BigDecimal qtaCol = UtilityHashMap.getValueIfExists(doc, "qta_col");
String codMart = UtilityHashMap.getValueIfExists(doc, "cod_mart");
CarelliGiacenzaProg c = new CarelliGiacenzaProg()
.setCodMart(codMdep)
.setCodMart(UtilityHashMap.getValueIfExists(doc, "cod_mart"))
.setCodMdep(codMdep)
.setCodMart(codMart)
.setQtaCar(qtaCol)
.setQtaIniz(qtaCol)
.setQtaScar(BigDecimal.ZERO)
@@ -354,13 +355,34 @@ public class GiacenzaService {
.setTipoCar("C")
.setDataIns(new Date());
c.setOperation(OperationType.INSERT_OR_UPDATE);
if (articoliSalvati.contains(codMart))
c.setOperation(OperationType.UPDATE);
else {
c.setOperation(OperationType.INSERT);
articoliSalvati.add(codMart);
}
carelliGiacenzaProgs.add(c);
}
saveEntity(carelliGiacenzaProgs);
sql =
Query.format(
"SELECT gestione, data_collo, ser_collo, num_collo FROM mtb_colt " +
"WHERE mtb_colt.cod_dtip_provv = %s\n" +
" AND mtb_colt.data_collo > %s\n" +
" AND mtb_colt.cod_mdep = %s\n" +
" AND mtb_colt.cod_dtip is null \n",
codDtipRett, dataIniz, codMdep);
List<MtbColt> mtbColts = UtilityDB.executeSimpleQueryDTO(multiDBTransactionManager.getPrimaryConnection(), sql, MtbColt.class);
if (mtbColts != null){
for (MtbColt collo : mtbColts) {
collo.setCodDtip(codDtipRett);
collo.setOperation(OperationType.UPDATE);
entityProcessor.processEntity(collo, false, true, "", multiDBTransactionManager, false);
}
}
}
}
private void saveEntity(List<? extends EntityBase> entityBases) throws SQLException, IOException {

View File

@@ -9,6 +9,8 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Joiner;
import com.google.firebase.messaging.FirebaseMessagingException;
import com.google.firebase.messaging.MessagingErrorCode;
import it.integry.common.var.CommonConstants;
import it.integry.ems.datasource.DataSource;
import it.integry.ems.javabeans.RequestDataDTO;
@@ -2451,6 +2453,7 @@ public class PvmService {
if (mtbColt != null) {
List<HashMap<String, Object>> mtbPartitaMagListHashMap = Stream.of(mtbColt.getMtbColr())
.filter(x -> !UtilityString.isNullOrEmpty(x.getPartitaMag()))
.map(mtbColr -> {
MtbPartitaMag mtbPartitaMag = new MtbPartitaMag();
mtbPartitaMag.setCodMart(mtbColr.getCodMart());
@@ -2751,12 +2754,12 @@ public class PvmService {
continue;
}
if (UtilityDate.DaysAfter(dataScad, UtilityDate.getTodayWithoutTime())>0 && codDtip.equalsIgnoreCase("DDTEC")) {
if (UtilityDate.DaysAfter(dataScad, UtilityDate.getTodayWithoutTime()) > 0 && codDtip.equalsIgnoreCase("DDTEC")) {
anomalieResiDTO.add(setAnomalia(anomalieResiDTO, codMart, dataScad, "Impossibile effetture un reso di in articolo già scaduto."));
continue;
}
if (UtilityDate.DaysAfter(dataScad, UtilityDate.getTodayWithoutTime())>15) {
if (UtilityDate.DaysAfter(dataScad, UtilityDate.getTodayWithoutTime()) > 15) {
anomalieResiDTO.add(setAnomalia(anomalieResiDTO, codMart, dataScad, "Impossibile effetture un reso dopo più di 15gg dalla scadenza."));
continue;
}
@@ -3668,21 +3671,31 @@ public class PvmService {
data.put("type", "modal");
data.put("style", "warning");
data.put("title", "Attenzione note modificate");
data.put("body", "Sono state modificate le note dell'ordine di lavorazione n. " + numOrdLav + " del " + dataOrdLav + "<br><span class='text-info'>" + note + "</span>");
data.put("body", "Sono state modificate le note dell'ordine di lavorazione n. " + numOrdLav + " del " + dataOrdLav + " " + note);
data.put("bodyHTML", "Sono state modificate le note dell'ordine di lavorazione n. " + numOrdLav + " del " + dataOrdLav + "<br><span class='text-info'>" + note + "</span>");
data.put("icon", "sticky-note");
WebpushNotificationDTO webpushNotificationDTO = new WebpushNotificationDTO();
webpushNotificationDTO.setRequireInteraction(true);
WebpushConfigDTO webpushConfigDTO = new WebpushConfigDTO();
webpushConfigDTO.setNotification(webpushNotificationDTO);
for (String codJfas : codJfasArray) {
String topic = dbName + "_" + codJfas;
List<String> topics = Stream.of(codJfasArray).map(codJfas -> dbName + "_" + codJfas).toList();
for (HashMap<String, Object> topicDeviceToken : notificationService.getTopicDeviceTokens(topics)) {
String deviceToken = UtilityHashMap.getValueIfExists(topicDeviceToken, "device_token");
MessageDTO message = new MessageDTO();
message.setTopic(topic);
message.setToken(deviceToken);
message.setData(data);
message.setWebpush(webpushConfigDTO);
firebaseService.sendMessage(message.toBuilder().build());
try {
firebaseService.sendMessage(message.toBuilder().build());
} catch (FirebaseMessagingException fireEx) {
if (fireEx.getMessagingErrorCode() == MessagingErrorCode.UNREGISTERED) {
// deviceTokenService.removeDeviceToken(deviceToken);
}
}
}
}
}

View File

@@ -148,6 +148,7 @@ public class WMSLavorazioneService {
//TODO: Assegnare l'ordine o l'id lotto al collo appena creato
//Se non trovo niente allora eccezione
}