Search in sources :

Example 11 with AppServiceHeader

use of org.cerberus.crud.entity.AppServiceHeader in project cerberus-source by cerberustesting.

the class ServiceService method callService.

@Override
public AnswerItem<AppService> callService(String service, String database, String request, String servicePathParam, String operation, TestCaseExecution tCExecution) {
    MessageEvent message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
    String decodedRequest;
    String decodedServicePath = null;
    String decodedOperation;
    String decodedAttachement;
    AnswerItem result = new AnswerItem();
    String system = tCExecution.getApplicationObj().getSystem();
    String country = tCExecution.getCountry();
    String environment = tCExecution.getEnvironment();
    LOG.debug("Starting callService : " + service + " with database : " + database);
    try {
        AppService appService;
        // If Service information is not defined, we create it from request, servicePath and operation parameters forcing in SOAP mode.
        if (StringUtil.isNullOrEmpty(service)) {
            LOG.debug("Creating AppService from parameters.");
            appService = factoryAppService.create("null", AppService.TYPE_SOAP, "", "", "", request, "Automatically created Service from datalib.", servicePathParam, "", operation, null, null, null, null);
            service = "null";
        } else {
            // If Service information is defined, we get it from database.
            LOG.debug("Getting AppService from service : " + service);
            appService = appServiceService.convert(appServiceService.readByKeyWithDependency(service, "Y"));
        }
        String servicePath;
        if (appService == null) {
            message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
            message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Service does not exist !!"));
        } else if (StringUtil.isNullOrEmpty(appService.getServicePath())) {
            message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE).resolveDescription("DESCRIPTION", "Service path is not defined");
        } else {
            // We start by calculating the servicePath and decode it.
            servicePath = appService.getServicePath();
            if (!(StringUtil.isURL(servicePath))) {
                if (StringUtil.isNullOrEmpty(database)) {
                    // We reformat servicePath in order to add the context from the application execution.
                    servicePath = StringUtil.getURLFromString(tCExecution.getCountryEnvironmentParameters().getIp(), tCExecution.getCountryEnvironmentParameters().getUrl(), appService.getServicePath(), "http://");
                } else {
                    // We reformat servicePath in order to add the context from the databaseUrl definition and corresponding from the country and environment of the execution.
                    try {
                        CountryEnvironmentDatabase countryEnvironmentDatabase;
                        countryEnvironmentDatabase = countryEnvironmentDatabaseService.convert(this.countryEnvironmentDatabaseService.readByKey(system, country, environment, database));
                        if (countryEnvironmentDatabase == null) {
                            message = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SERVICE_URLKOANDDATABASESOAPURLNOTEXIST);
                            message.setDescription(message.getDescription().replace("%SERVICEURL%", appService.getServicePath()).replace("%SYSTEM%", system).replace("%COUNTRY%", country).replace("%ENV%", environment).replace("%DATABASE%", database));
                            result.setResultMessage(message);
                            return result;
                        } else {
                            String soapURL = countryEnvironmentDatabase.getSoapUrl();
                            if (StringUtil.isNullOrEmpty(soapURL)) {
                                message = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SERVICE_URLKOANDDATABASESOAPURLEMPTY);
                                message.setDescription(message.getDescription().replace("%SERVICEURL%", appService.getServicePath()).replace("%SYSTEM%", system).replace("%COUNTRY%", country).replace("%ENV%", environment).replace("%DATABASE%", database));
                                result.setResultMessage(message);
                                return result;
                            }
                            // soapURL from database is not empty so we prefix the Service URL with it.
                            servicePath = StringUtil.getURLFromString(soapURL, "", servicePath, "");
                            if (!StringUtil.isURL(servicePath)) {
                                message = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SERVICE_URLKO);
                                message.setDescription(message.getDescription().replace("%SERVICEURL%", servicePath).replace("%SOAPURL%", soapURL).replace("%SERVICEPATH%", appService.getServicePath()));
                                result.setResultMessage(message);
                                return result;
                            }
                        }
                    } catch (CerberusException ex) {
                        message = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SERVICE_URLKOANDDATABASESOAPURLNOTEXIST);
                        message.setDescription(message.getDescription().replace("%SERVICEURL%", servicePath).replace("%SYSTEM%", system).replace("%COUNTRY%", country).replace("%ENV%", environment).replace("%DATABASE%", database));
                        result.setResultMessage(message);
                        return result;
                    }
                }
            }
            // appService object and target servicePath is now clean. We can start to decode.
            decodedServicePath = servicePath;
            decodedRequest = appService.getServiceRequest();
            LOG.debug("AppService with correct path is  now OK : " + servicePath);
            AnswerItem<String> answerDecode = new AnswerItem();
            try {
                // Decode Service Path
                answerDecode = variableService.decodeStringCompletly(decodedServicePath, tCExecution, null, false);
                decodedServicePath = (String) answerDecode.getItem();
                if (!(answerDecode.isCodeStringEquals("OK"))) {
                    // If anything wrong with the decode --> we stop here with decode message in the action result.
                    message = answerDecode.getResultMessage().resolveDescription("FIELD", "Service Path");
                    LOG.debug("Property interupted due to decode 'Service Path'.");
                    result.setResultMessage(message);
                    return result;
                }
                // Decode Request
                answerDecode = variableService.decodeStringCompletly(decodedRequest, tCExecution, null, false);
                decodedRequest = (String) answerDecode.getItem();
                if (!(answerDecode.isCodeStringEquals("OK"))) {
                    // If anything wrong with the decode --> we stop here with decode message in the action result.
                    message = answerDecode.getResultMessage().resolveDescription("FIELD", "Service Request");
                    LOG.debug("Property interupted due to decode 'Service Request'.");
                    result.setResultMessage(message);
                    return result;
                }
                // Decode Header List
                List<AppServiceHeader> objectResponseHeaderList = new ArrayList<>();
                for (AppServiceHeader object : appService.getHeaderList()) {
                    answerDecode = variableService.decodeStringCompletly(object.getKey(), tCExecution, null, false);
                    object.setKey((String) answerDecode.getItem());
                    if (!(answerDecode.isCodeStringEquals("OK"))) {
                        // If anything wrong with the decode --> we stop here with decode message in the action result.
                        String field = "Header Key " + object.getKey();
                        message = answerDecode.getResultMessage().resolveDescription("FIELD", field);
                        LOG.debug("Property interupted due to decode '" + field + "'.");
                        result.setResultMessage(message);
                        return result;
                    }
                    answerDecode = variableService.decodeStringCompletly(object.getValue(), tCExecution, null, false);
                    object.setValue((String) answerDecode.getItem());
                    if (!(answerDecode.isCodeStringEquals("OK"))) {
                        // If anything wrong with the decode --> we stop here with decode message in the action result.
                        String field = "Header Value " + object.getKey();
                        message = answerDecode.getResultMessage().resolveDescription("FIELD", field);
                        LOG.debug("Property interupted due to decode '" + field + "'.");
                        result.setResultMessage(message);
                        return result;
                    }
                    objectResponseHeaderList.add(object);
                }
                // Decode ContentDetail List
                appService.setResponseHeaderList(objectResponseHeaderList);
                List<AppServiceContent> objectResponseContentList = new ArrayList<>();
                for (AppServiceContent object : appService.getContentList()) {
                    answerDecode = variableService.decodeStringCompletly(object.getKey(), tCExecution, null, false);
                    object.setKey((String) answerDecode.getItem());
                    if (!(answerDecode.isCodeStringEquals("OK"))) {
                        // If anything wrong with the decode --> we stop here with decode message in the action result.
                        String field = "Content Key " + object.getKey();
                        message = answerDecode.getResultMessage().resolveDescription("FIELD", field);
                        LOG.debug("Property interupted due to decode '" + field + "'.");
                        result.setResultMessage(message);
                        return result;
                    }
                    answerDecode = variableService.decodeStringCompletly(object.getValue(), tCExecution, null, false);
                    object.setValue((String) answerDecode.getItem());
                    if (!(answerDecode.isCodeStringEquals("OK"))) {
                        // If anything wrong with the decode --> we stop here with decode message in the action result.
                        String field = "Content Value " + object.getKey();
                        message = answerDecode.getResultMessage().resolveDescription("FIELD", field);
                        LOG.debug("Property interupted due to decode '" + field + "'.");
                        result.setResultMessage(message);
                        return result;
                    }
                    objectResponseContentList.add(object);
                }
                appService.setContentList(objectResponseContentList);
            } catch (CerberusEventException cee) {
                message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICEWITHPATH);
                message.setDescription(message.getDescription().replace("%SERVICENAME%", service));
                message.setDescription(message.getDescription().replace("%SERVICEPATH%", decodedServicePath));
                message.setDescription(message.getDescription().replace("%DESCRIPTION%", cee.getMessageError().getDescription()));
                result.setResultMessage(message);
                return result;
            }
            // Get from parameter whether we define a token or not (in order to trace the cerberus calls in http header)
            String token = null;
            if (parameterService.getParameterBooleanByKey("cerberus_callservice_enablehttpheadertoken", system, true)) {
                token = String.valueOf(tCExecution.getId());
            }
            // Get from parameter the call timeout to be used.
            int timeOutMs = parameterService.getParameterIntegerByKey("cerberus_callservice_timeoutms", system, 60000);
            // The rest of the data will be prepared depending on the TYPE and METHOD used.
            switch(appService.getType()) {
                case AppService.TYPE_SOAP:
                    LOG.debug("This is a SOAP Service");
                    /**
                     * SOAP. Decode Envelope and Operation replacing
                     * properties encapsulated with %
                     */
                    decodedOperation = appService.getOperation();
                    decodedAttachement = appService.getAttachementURL();
                    try {
                        answerDecode = variableService.decodeStringCompletly(decodedOperation, tCExecution, null, false);
                        decodedOperation = (String) answerDecode.getItem();
                        if (!(answerDecode.isCodeStringEquals("OK"))) {
                            // If anything wrong with the decode --> we stop here with decode message in the action result.
                            String field = "Operation";
                            message = answerDecode.getResultMessage().resolveDescription("FIELD", field);
                            LOG.debug("Property interupted due to decode '" + field + "'.");
                            result.setResultMessage(message);
                            return result;
                        }
                        answerDecode = variableService.decodeStringCompletly(decodedAttachement, tCExecution, null, false);
                        decodedAttachement = (String) answerDecode.getItem();
                        if (!(answerDecode.isCodeStringEquals("OK"))) {
                            // If anything wrong with the decode --> we stop here with decode message in the action result.
                            String field = "Attachement URL";
                            message = answerDecode.getResultMessage().resolveDescription("FIELD", field);
                            LOG.debug("Property interupted due to decode '" + field + "'.");
                            result.setResultMessage(message);
                            return result;
                        }
                    } catch (CerberusEventException cee) {
                        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSOAP);
                        message.setDescription(message.getDescription().replace("%SERVICENAME%", service));
                        message.setDescription(message.getDescription().replace("%SERVICEPATH%", decodedServicePath));
                        message.setDescription(message.getDescription().replace("%DESCRIPTION%", cee.getMessageError().getDescription()));
                        result.setResultMessage(message);
                        return result;
                    }
                    /**
                     * Call SOAP and store it into the execution.
                     */
                    result = soapService.callSOAP(decodedRequest, decodedServicePath, decodedOperation, decodedAttachement, appService.getHeaderList(), token, timeOutMs, system);
                    LOG.debug("SOAP Called done.");
                    LOG.debug("Result message." + result.getResultMessage());
                    message = result.getResultMessage();
                    break;
                case AppService.TYPE_REST:
                    /**
                     * REST.
                     */
                    switch(appService.getMethod()) {
                        case AppService.METHOD_HTTPGET:
                        case AppService.METHOD_HTTPPOST:
                            /**
                             * Call REST and store it into the execution.
                             */
                            result = restService.callREST(decodedServicePath, decodedRequest, appService.getMethod(), appService.getHeaderList(), appService.getContentList(), token, timeOutMs, system);
                            message = result.getResultMessage();
                            break;
                        case AppService.METHOD_HTTPDELETE:
                            result = restService.callREST(decodedServicePath, decodedRequest, appService.getMethod(), appService.getHeaderList(), appService.getContentList(), token, timeOutMs, system);
                            message = result.getResultMessage();
                            break;
                        case AppService.METHOD_HTTPPUT:
                            result = restService.callREST(decodedServicePath, decodedRequest, appService.getMethod(), appService.getHeaderList(), appService.getContentList(), token, timeOutMs, system);
                            message = result.getResultMessage();
                            break;
                        case AppService.METHOD_HTTPPATCH:
                            result = restService.callREST(decodedServicePath, decodedRequest, appService.getMethod(), appService.getHeaderList(), appService.getContentList(), token, timeOutMs, system);
                            message = result.getResultMessage();
                            break;
                        default:
                            message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
                            message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Method : '" + appService.getMethod() + "' for REST Service is not supported by the engine."));
                            result.setResultMessage(message);
                    }
                    break;
                default:
                    message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
                    message.setDescription(message.getDescription().replace("%SERVICE%", service));
                    message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Service Type : '" + appService.getType() + "' is not supported by the engine."));
                    result.setResultMessage(message);
            }
        }
    } catch (CerberusException ex) {
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
        message.setDescription(message.getDescription().replace("%SERVICENAME%", service));
        message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Cerberus exception on CallService : " + ex.getMessageError().getDescription()));
        result.setResultMessage(message);
        return result;
    } catch (Exception ex) {
        LOG.error("Exception when performing CallService Action. " + ex.toString());
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
        message.setDescription(message.getDescription().replace("%SERVICENAME%", service));
        message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Cerberus exception on CallService : " + ex.toString()));
        return result;
    }
    message.setDescription(message.getDescription().replace("%SERVICENAME%", service));
    result.setResultMessage(message);
    LOG.debug("Ended callService : " + service + " with database : " + database + " Result : " + message.getDescription());
    return result;
}
Also used : CerberusEventException(org.cerberus.exception.CerberusEventException) AppService(org.cerberus.crud.entity.AppService) IFactoryAppService(org.cerberus.crud.factory.IFactoryAppService) CerberusException(org.cerberus.exception.CerberusException) MessageEvent(org.cerberus.engine.entity.MessageEvent) AppServiceContent(org.cerberus.crud.entity.AppServiceContent) AppServiceHeader(org.cerberus.crud.entity.AppServiceHeader) ArrayList(java.util.ArrayList) List(java.util.List) AnswerItem(org.cerberus.util.answer.AnswerItem) CerberusEventException(org.cerberus.exception.CerberusEventException) CerberusException(org.cerberus.exception.CerberusException) CountryEnvironmentDatabase(org.cerberus.crud.entity.CountryEnvironmentDatabase)

Example 12 with AppServiceHeader

use of org.cerberus.crud.entity.AppServiceHeader in project cerberus-source by cerberustesting.

the class AppServiceHeaderDAO method readByVariousByCriteria.

@Override
public AnswerList<AppServiceHeader> readByVariousByCriteria(String service, String active, int start, int amount, String column, String dir, String searchTerm, Map<String, List<String>> individualSearch) {
    AnswerList response = new AnswerList();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    List<AppServiceHeader> objectList = new ArrayList<AppServiceHeader>();
    StringBuilder searchSQL = new StringBuilder();
    List<String> individalColumnSearchValues = new ArrayList<String>();
    StringBuilder query = new StringBuilder();
    // SQL_CALC_FOUND_ROWS allows to retrieve the total number of columns by disrearding the limit clauses that
    // were applied -- used for pagination p
    query.append("SELECT SQL_CALC_FOUND_ROWS * FROM appserviceheader srh ");
    searchSQL.append(" where 1=1 ");
    if (!StringUtil.isNullOrEmpty(searchTerm)) {
        searchSQL.append(" and (srh.`service` like ?");
        searchSQL.append(" or srh.`key` like ?");
        searchSQL.append(" or srh.`value` like ?");
        searchSQL.append(" or srh.`sort` like ?");
        searchSQL.append(" or srh.`active` like ?");
        searchSQL.append(" or srh.`usrCreated` like ?");
        searchSQL.append(" or srh.`usrModif` like ?");
        searchSQL.append(" or srh.`dateCreated` like ?");
        searchSQL.append(" or srh.`dateModif` like ?");
        searchSQL.append(" or srh.`description` like ?)");
    }
    if (individualSearch != null && !individualSearch.isEmpty()) {
        searchSQL.append(" and ( 1=1 ");
        for (Map.Entry<String, List<String>> entry : individualSearch.entrySet()) {
            searchSQL.append(" and ");
            searchSQL.append(SqlUtil.getInSQLClauseForPreparedStatement(entry.getKey(), entry.getValue()));
            individalColumnSearchValues.addAll(entry.getValue());
        }
        searchSQL.append(" )");
    }
    if (!StringUtil.isNullOrEmpty(service)) {
        searchSQL.append(" and (srh.`service` = ? )");
    }
    if (!StringUtil.isNullOrEmpty(active)) {
        searchSQL.append(" and (srh.`active` = ? )");
    }
    query.append(searchSQL);
    if (!StringUtil.isNullOrEmpty(column)) {
        query.append(" order by `").append(column).append("` ").append(dir);
    }
    if ((amount <= 0) || (amount >= MAX_ROW_SELECTED)) {
        query.append(" limit ").append(start).append(" , ").append(MAX_ROW_SELECTED);
    } else {
        query.append(" limit ").append(start).append(" , ").append(amount);
    }
    // Debug message on SQL.
    if (LOG.isDebugEnabled()) {
        LOG.debug("SQL : " + query.toString());
    }
    Connection connection = this.databaseSpring.connect();
    try {
        PreparedStatement preStat = connection.prepareStatement(query.toString());
        try {
            int i = 1;
            if (!StringUtil.isNullOrEmpty(searchTerm)) {
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
            }
            for (String individualColumnSearchValue : individalColumnSearchValues) {
                preStat.setString(i++, individualColumnSearchValue);
            }
            if (!StringUtil.isNullOrEmpty(service)) {
                preStat.setString(i++, service);
            }
            if (!StringUtil.isNullOrEmpty(active)) {
                preStat.setString(i++, active);
            }
            ResultSet resultSet = preStat.executeQuery();
            try {
                // gets the data
                while (resultSet.next()) {
                    objectList.add(this.loadFromResultSet(resultSet));
                }
                // get the total number of rows
                resultSet = preStat.executeQuery("SELECT FOUND_ROWS()");
                int nrTotalRows = 0;
                if (resultSet != null && resultSet.next()) {
                    nrTotalRows = resultSet.getInt(1);
                }
                if (objectList.size() >= MAX_ROW_SELECTED) {
                    // Result of SQl was limited by MAX_ROW_SELECTED constrain. That means that we may miss some lines in the resultList.
                    LOG.error("Partial Result in the query.");
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_WARNING_PARTIAL_RESULT);
                    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", "Maximum row reached : " + MAX_ROW_SELECTED));
                    response = new AnswerList(objectList, nrTotalRows);
                } else if (objectList.size() <= 0) {
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_NO_DATA_FOUND);
                    response = new AnswerList(objectList, nrTotalRows);
                } else {
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
                    msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "SELECT"));
                    response = new AnswerList(objectList, nrTotalRows);
                }
            } catch (SQLException exception) {
                LOG.error("Unable to execute query : " + exception.toString());
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
                msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString()));
            } finally {
                if (resultSet != null) {
                    resultSet.close();
                }
            }
        } catch (SQLException exception) {
            LOG.error("Unable to execute query : " + exception.toString());
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
            msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString()));
        } finally {
            if (preStat != null) {
                preStat.close();
            }
        }
    } catch (SQLException exception) {
        LOG.error("Unable to execute query : " + exception.toString());
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
        msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString()));
    } finally {
        try {
            if (!this.databaseSpring.isOnTransaction()) {
                if (connection != null) {
                    connection.close();
                }
            }
        } catch (SQLException exception) {
            LOG.warn("Unable to close connection : " + exception.toString());
        }
    }
    response.setResultMessage(msg);
    response.setDataList(objectList);
    return response;
}
Also used : AnswerList(org.cerberus.util.answer.AnswerList) SQLException(java.sql.SQLException) MessageEvent(org.cerberus.engine.entity.MessageEvent) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) FactoryAppServiceHeader(org.cerberus.crud.factory.impl.FactoryAppServiceHeader) IFactoryAppServiceHeader(org.cerberus.crud.factory.IFactoryAppServiceHeader) AppServiceHeader(org.cerberus.crud.entity.AppServiceHeader) PreparedStatement(java.sql.PreparedStatement) ResultSet(java.sql.ResultSet) AnswerList(org.cerberus.util.answer.AnswerList) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map)

Example 13 with AppServiceHeader

use of org.cerberus.crud.entity.AppServiceHeader in project cerberus-source by cerberustesting.

the class AppServiceService method readByKeyWithDependency.

@Override
public AnswerItem readByKeyWithDependency(String key, String activedetail) {
    AnswerItem answerAppService = this.readByKey(key);
    AppService appService = (AppService) answerAppService.getItem();
    try {
        AnswerList content = appServiceContentService.readByVarious(key, activedetail);
        appService.setContentList((List<AppServiceContent>) content.getDataList());
        AnswerList header = appServiceHeaderService.readByVarious(key, activedetail);
        appService.setHeaderList((List<AppServiceHeader>) header.getDataList());
        answerAppService.setItem(appService);
    } catch (Exception e) {
        LOG.error(e);
    }
    return answerAppService;
}
Also used : AppService(org.cerberus.crud.entity.AppService) AnswerList(org.cerberus.util.answer.AnswerList) AppServiceContent(org.cerberus.crud.entity.AppServiceContent) AppServiceHeader(org.cerberus.crud.entity.AppServiceHeader) AnswerItem(org.cerberus.util.answer.AnswerItem) CerberusException(org.cerberus.exception.CerberusException)

Example 14 with AppServiceHeader

use of org.cerberus.crud.entity.AppServiceHeader in project cerberus-source by cerberustesting.

the class AppServiceHeaderService method compareListAndUpdateInsertDeleteElements.

@Override
public Answer compareListAndUpdateInsertDeleteElements(String service, List<AppServiceHeader> newList) {
    Answer ans = new Answer(null);
    MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
    Answer finalAnswer = new Answer(msg1);
    List<AppServiceHeader> oldList = new ArrayList();
    try {
        oldList = this.convert(this.readByVarious(service, null));
    } catch (CerberusException ex) {
        LOG.error(ex);
    }
    /**
     * Update and Create all objects database Objects from newList
     */
    List<AppServiceHeader> listToUpdateOrInsert = new ArrayList(newList);
    listToUpdateOrInsert.removeAll(oldList);
    List<AppServiceHeader> listToUpdateOrInsertToIterate = new ArrayList(listToUpdateOrInsert);
    for (AppServiceHeader objectDifference : listToUpdateOrInsertToIterate) {
        for (AppServiceHeader objectInDatabase : oldList) {
            if (objectDifference.hasSameKey(objectInDatabase)) {
                ans = this.update(objectDifference.getService(), objectDifference.getKey(), objectDifference);
                finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                listToUpdateOrInsert.remove(objectDifference);
            }
        }
    }
    /**
     * Delete all objects database Objects that do not exist from newList
     */
    List<AppServiceHeader> listToDelete = new ArrayList(oldList);
    listToDelete.removeAll(newList);
    List<AppServiceHeader> listToDeleteToIterate = new ArrayList(listToDelete);
    for (AppServiceHeader tcsDifference : listToDeleteToIterate) {
        for (AppServiceHeader tcsInPage : newList) {
            if (tcsDifference.hasSameKey(tcsInPage)) {
                listToDelete.remove(tcsDifference);
            }
        }
    }
    if (!listToDelete.isEmpty()) {
        ans = this.deleteList(listToDelete);
        finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
    }
    // We insert only at the end (after deletion of all potencial enreg - linked with #1281)
    if (!listToUpdateOrInsert.isEmpty()) {
        ans = this.createList(listToUpdateOrInsert);
        finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
    }
    return finalAnswer;
}
Also used : Answer(org.cerberus.util.answer.Answer) CerberusException(org.cerberus.exception.CerberusException) MessageEvent(org.cerberus.engine.entity.MessageEvent) ArrayList(java.util.ArrayList) AppServiceHeader(org.cerberus.crud.entity.AppServiceHeader)

Aggregations

AppServiceHeader (org.cerberus.crud.entity.AppServiceHeader)14 IFactoryAppServiceHeader (org.cerberus.crud.factory.IFactoryAppServiceHeader)10 ArrayList (java.util.ArrayList)9 MessageEvent (org.cerberus.engine.entity.MessageEvent)7 AppService (org.cerberus.crud.entity.AppService)6 AppServiceContent (org.cerberus.crud.entity.AppServiceContent)6 AnswerItem (org.cerberus.util.answer.AnswerItem)5 IFactoryAppService (org.cerberus.crud.factory.IFactoryAppService)4 JSONObject (org.json.JSONObject)4 CerberusException (org.cerberus.exception.CerberusException)3 Answer (org.cerberus.util.answer.Answer)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 InputStream (java.io.InputStream)2 Connection (java.sql.Connection)2 PreparedStatement (java.sql.PreparedStatement)2 ResultSet (java.sql.ResultSet)2 SQLException (java.sql.SQLException)2 List (java.util.List)2 AnswerList (org.cerberus.util.answer.AnswerList)2 IOException (java.io.IOException)1