Search in sources :

Example 1 with JpaAmpNewTx

use of org.meveo.jpa.JpaAmpNewTx in project meveo by meveo-org.

the class UnitReportExtractJobBean method execute.

@JpaAmpNewTx
@Interceptors({ JobLoggingInterceptor.class, PerformanceInterceptor.class })
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void execute(JobExecutionResultImpl result, Long id, Date startDate, Date endDate) {
    try {
        ReportExtract entity = reportExtractService.findById(id);
        if (startDate != null) {
            entity.getParams().put(ReportExtractScript.START_DATE, DateUtils.formatDateWithPattern(startDate, paramBean.getDateFormat()));
        }
        if (endDate != null) {
            entity.getParams().put(ReportExtractScript.END_DATE, DateUtils.formatDateWithPattern(endDate, paramBean.getDateFormat()));
        }
        reportExtractService.runReport(entity);
        result.registerSucces();
    } catch (Exception e) {
        log.error("Failed to generate acount operations", e);
        result.registerError(e.getMessage());
    }
}
Also used : ReportExtract(org.meveo.model.finance.ReportExtract) JpaAmpNewTx(org.meveo.jpa.JpaAmpNewTx) Interceptors(javax.interceptor.Interceptors) TransactionAttribute(javax.ejb.TransactionAttribute)

Example 2 with JpaAmpNewTx

use of org.meveo.jpa.JpaAmpNewTx in project meveo by meveo-org.

the class DWHQueryBean method executeQuery.

@JpaAmpNewTx
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Interceptors({ JobLoggingInterceptor.class, PerformanceInterceptor.class })
void executeQuery(JobExecutionResultImpl result, String parameter) {
    String measurableQuantityCode = parameter;
    Date toDate = new Date();
    if (!StringUtils.isBlank(parameter)) {
        if (parameter.indexOf("to=") > 0) {
            String s = parameter.substring(parameter.indexOf("to=") + 3);
            if (s.indexOf(";") > 0) {
                measurableQuantityCode = parameter.substring(parameter.indexOf(";") + 1);
                Date parsedDate = org.meveo.model.shared.DateUtils.guessDate(s.substring(0, s.indexOf(";")), "yyyy-MM-dd");
                if (parsedDate != null) {
                    toDate = parsedDate;
                }
            } else {
                if (parameter.indexOf(";") > 0) {
                    measurableQuantityCode = parameter.substring(0, parameter.indexOf(";"));
                } else {
                    measurableQuantityCode = null;
                }
            }
        }
    }
    log.debug("measurableQuantityCode={}, toDate={}", measurableQuantityCode, toDate);
    List<MeasurableQuantity> mqList = new ArrayList<>();
    if (StringUtils.isBlank(measurableQuantityCode)) {
        mqList = mqService.listToBeExecuted(new Date());
    } else {
        MeasurableQuantity mq = mqService.findByCode(measurableQuantityCode);
        if (mq == null) {
            result.registerError("Cannot find measurable quantity with code " + measurableQuantityCode);
            return;
        }
        mqList.add(mq);
    }
    result.setNbItemsToProcess(mqList.size());
    for (MeasurableQuantity mq : mqList) {
        if (!jobExecutionService.isJobRunningOnThis(result.getJobInstance().getId())) {
            break;
        }
        if (StringUtils.isBlank(mq.getSqlQuery())) {
            result.registerError("Measurable quantity with code " + measurableQuantityCode + " has no SQL query set.");
            log.info("Measurable quantity with code {} has no SQL query set.", measurableQuantityCode);
            continue;
        }
        mq.increaseMeasureDate();
        result.registerSucces();
        try {
            for (MeasuredValue measuredValue : getMeasuredValues(mq, toDate)) {
                if (measuredValue.getId() == null) {
                    mvService.create(measuredValue);
                } else {
                    mvService.update(measuredValue);
                }
            }
        } catch (Exception e) {
            result.registerError("Measurable quantity with code " + measurableQuantityCode + " contain invalid SQL query: " + e.getMessage());
        }
    }
}
Also used : MeasurableQuantity(org.meveo.model.dwh.MeasurableQuantity) ArrayList(java.util.ArrayList) Date(java.util.Date) MeasuredValue(org.meveo.model.dwh.MeasuredValue) BusinessException(org.meveo.admin.exception.BusinessException) JpaAmpNewTx(org.meveo.jpa.JpaAmpNewTx) Interceptors(javax.interceptor.Interceptors) TransactionAttribute(javax.ejb.TransactionAttribute)

Example 3 with JpaAmpNewTx

use of org.meveo.jpa.JpaAmpNewTx in project meveo by meveo-org.

the class FileProcessingJobBean method execute.

/**
 * Execute.
 *
 * @param result the result
 * @param inputDir the input dir
 * @param file the file
 * @param scriptInstanceFlowCode the script instance flow code
 * @param context the context
 */
@JpaAmpNewTx
@Interceptors({ JobLoggingInterceptor.class, PerformanceInterceptor.class })
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void execute(JobExecutionResultImpl result, String inputDir, String archDir, String rejDir, File file, String scriptInstanceFlowCode, Map<String, Object> context) {
    log.debug("Running for inputDir={}, scriptInstanceFlowCode={},formatTransfo={}", inputDir, scriptInstanceFlowCode);
    rejectDir = rejDir != null ? rejDir : inputDir + File.separator + "reject";
    archiveDir = archDir != null ? archDir : inputDir + File.separator + "archive";
    File f = new File(rejectDir);
    if (!f.exists()) {
        log.debug("rejectDir {} not exist", rejectDir);
        f.mkdirs();
        log.debug("rejectDir {} creation ok", rejectDir);
    }
    f = new File(archiveDir);
    if (!f.exists()) {
        log.debug("saveDir {} not exist", archiveDir);
        f.mkdirs();
        log.debug("saveDir {} creation ok", archiveDir);
    }
    report = "";
    if (file != null) {
        fileName = file.getName();
        ScriptInterface script = null;
        try {
            log.info("InputFile job {} in progress...", file.getAbsolutePath());
            script = scriptInstanceService.getScriptInstance(scriptInstanceFlowCode);
            script.init(context);
            Map<String, Object> executeParams = new HashMap<String, Object>();
            executeParams.put("file", file);
            executeParams.put(Script.CONTEXT_CURRENT_USER, currentUser);
            executeParams.put(Script.CONTEXT_APP_PROVIDER, appProvider);
            executeParams.put("archiveDir", archiveDir);
            script.execute(executeParams);
            FileUtils.moveFile(archiveDir, file, fileName);
            result.addNbItemsCorrectlyProcessed(1);
        } catch (Exception e) {
            report += "\r\n " + e.getMessage();
            FileUtils.moveFile(rejectDir, file, fileName);
            result.addNbItemsProcessedWithError(1);
        } finally {
            try {
                if (script != null) {
                    script.finalize(context);
                }
            } catch (Exception e) {
                report += "\r\n error in script finailzation : " + e.getMessage();
            }
            try {
                if (file != null) {
                    // Move current CSV file to save directory, else PDF file was deleted.
                    file.delete();
                }
            } catch (Exception e) {
                report += "\r\n cannot move file to save directory " + fileName;
            }
        }
        result.addReport(report);
    } else {
        log.info("no file to process");
    }
}
Also used : ScriptInterface(org.meveo.service.script.ScriptInterface) HashMap(java.util.HashMap) File(java.io.File) JpaAmpNewTx(org.meveo.jpa.JpaAmpNewTx) Interceptors(javax.interceptor.Interceptors) TransactionAttribute(javax.ejb.TransactionAttribute)

Example 4 with JpaAmpNewTx

use of org.meveo.jpa.JpaAmpNewTx in project meveo by meveo-org.

the class InternalNotificationJobBean method execute.

/**
 * Execute.
 *
 * @param filterCode the filter code
 * @param notificationCode the notification code
 * @param result the result
 */
@SuppressWarnings("rawtypes")
@JpaAmpNewTx
@Interceptors({ JobLoggingInterceptor.class, PerformanceInterceptor.class })
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void execute(String filterCode, String notificationCode, JobExecutionResultImpl result) {
    log.debug("Running with filterCode={}", filterCode);
    if (StringUtils.isBlank(filterCode)) {
        result.registerError("filterCode has no SQL query set.");
        return;
    }
    Notification notification = notificationService.findByCode(notificationCode);
    if (notification == null) {
        result.registerError("no notification found for " + notificationCode);
        return;
    }
    try {
        String queryStr = filterCode.replaceAll("#\\{date\\}", df.format(new Date()));
        queryStr = queryStr.replaceAll("#\\{dateTime\\}", tf.format(new Date()));
        log.debug("execute query:{}", queryStr);
        Query query = emWrapper.getEntityManager().createNativeQuery(queryStr);
        @SuppressWarnings("unchecked") List<Object> results = query.getResultList();
        result.setNbItemsToProcess(results.size());
        for (Object res : results) {
            if (!jobExecutionService.isJobRunningOnThis(result.getJobInstance().getId())) {
                break;
            }
            Map<Object, Object> userMap = new HashMap<Object, Object>();
            userMap.put("event", res);
            userMap.put("manager", manager);
            if (!StringUtils.isBlank(notification.getElFilter())) {
                Object o = MeveoValueExpressionWrapper.evaluateExpression(notification.getElFilter(), userMap, Boolean.class);
                try {
                    if (!(Boolean) o) {
                        result.registerSucces();
                        continue;
                    }
                } catch (Exception e) {
                    throw new BusinessException("Expression " + notification.getElFilter() + " do not evaluate to boolean but " + res);
                }
            }
            try {
                if (notification.getFunction() != null) {
                    Map<String, Object> paramsEvaluated = new HashMap<String, Object>();
                    for (Map.Entry entry : notification.getParams().entrySet()) {
                        paramsEvaluated.put((String) entry.getKey(), MeveoValueExpressionWrapper.evaluateExpression((String) entry.getValue(), userMap, String.class));
                    }
                    scriptInstanceService.execute(notification.getFunction().getCode(), paramsEvaluated);
                    result.registerSucces();
                } else {
                    log.debug("No script instance on this Notification");
                }
            } catch (Exception e) {
                result.registerError("Error execution " + notification.getFunction() + " on " + res);
                throw new BusinessException("Expression " + notification.getElFilter() + " do not evaluate to boolean but " + res);
            }
        }
    } catch (Exception e) {
        result.registerError("filterCode contain invalid SQL query: " + e.getMessage());
    }
}
Also used : Query(javax.persistence.Query) HashMap(java.util.HashMap) Notification(org.meveo.model.notification.Notification) Date(java.util.Date) BusinessException(org.meveo.admin.exception.BusinessException) BusinessException(org.meveo.admin.exception.BusinessException) HashMap(java.util.HashMap) Map(java.util.Map) JpaAmpNewTx(org.meveo.jpa.JpaAmpNewTx) Interceptors(javax.interceptor.Interceptors) TransactionAttribute(javax.ejb.TransactionAttribute)

Example 5 with JpaAmpNewTx

use of org.meveo.jpa.JpaAmpNewTx in project meveo by meveo-org.

the class JobService method getJobSchedulerInfo.

@JpaAmpNewTx
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@SuppressWarnings("unchecked")
public Map<String, Integer> getJobSchedulerInfo(int jobRepositoryId) {
    Query query = getEntityManager().createNativeQuery(SELECT_JOB_INFO);
    query.setParameter("id", jobRepositoryId);
    List<Object> list = query.getResultList();
    Map<String, Integer> valuesMap = new HashMap<String, Integer>();
    BigDecimal temp = null;
    for (Object oRow : list) {
        Object[] row = (Object[]) oRow;
        temp = (BigDecimal) row[1];
        if (row[0].equals(SCHEDULER_TYPE_STRING)) {
            valuesMap.put(SCHEDULER_TYPE_STRING, temp.intValue());
        }
        if (row[0].equals(INTERVAL_SECONDS_STRING)) {
            valuesMap.put(INTERVAL_SECONDS_STRING, temp.intValue());
        }
        if (row[0].equals(INTERVAL_MINUTES_STRING)) {
            valuesMap.put(INTERVAL_MINUTES_STRING, temp.intValue());
        }
        if (row[0].equals(HOUR_STRING)) {
            valuesMap.put(HOUR_STRING, temp.intValue());
        }
        if (row[0].equals(MINUTES_STRING)) {
            valuesMap.put(MINUTES_STRING, temp.intValue());
        }
        if (row[0].equals(WEEK_DAY_STRING)) {
            valuesMap.put(WEEK_DAY_STRING, temp.intValue());
        }
        if (row[0].equals(DAY_OF_MONTH_STRING)) {
            valuesMap.put(DAY_OF_MONTH_STRING, temp.intValue());
        }
    }
    return valuesMap;
}
Also used : Query(javax.persistence.Query) HashMap(java.util.HashMap) BigDecimal(java.math.BigDecimal) JpaAmpNewTx(org.meveo.jpa.JpaAmpNewTx) TransactionAttribute(javax.ejb.TransactionAttribute)

Aggregations

JpaAmpNewTx (org.meveo.jpa.JpaAmpNewTx)22 TransactionAttribute (javax.ejb.TransactionAttribute)21 BusinessException (org.meveo.admin.exception.BusinessException)8 IOException (java.io.IOException)6 HashMap (java.util.HashMap)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 Interceptors (javax.interceptor.Interceptors)4 Query (javax.persistence.Query)4 ElementNotFoundException (org.meveo.admin.exception.ElementNotFoundException)4 BigDecimal (java.math.BigDecimal)3 Date (java.util.Date)3 HashSet (java.util.HashSet)3 Map (java.util.Map)3 NoResultException (javax.persistence.NoResultException)3 CustomFieldTemplate (org.meveo.model.crm.CustomFieldTemplate)3 CustomRelationshipTemplate (org.meveo.model.customEntities.CustomRelationshipTemplate)3 PersistenceActionResult (org.meveo.persistence.PersistenceActionResult)3 XStream (com.thoughtworks.xstream.XStream)2 MapperWrapper (com.thoughtworks.xstream.mapper.MapperWrapper)2