Search in sources :

Example 11 with CountryEnvironmentDatabase

use of org.cerberus.crud.entity.CountryEnvironmentDatabase 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 CountryEnvironmentDatabase

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

the class DataLibService method getDataObjectList.

/**
 * Get the dataObject List depending on the type
 *
 * @param lib
 * @param columnList
 * @return
 */
private AnswerList<HashMap<String, String>> getDataObjectList(TestDataLib lib, HashMap<String, String> columnList, int rowLimit, TestCaseExecution tCExecution, TestCaseExecutionData testCaseExecutionData) {
    AnswerList result = new AnswerList();
    MessageEvent msg = new MessageEvent(MessageEventEnum.PROPERTY_SUCCESS);
    CountryEnvironmentDatabase countryEnvironmentDatabase;
    AnswerList responseList;
    String system = tCExecution.getApplicationObj().getSystem();
    String country = tCExecution.getCountry();
    String environment = tCExecution.getEnvironment();
    Pattern pattern;
    Matcher matcher;
    Parameter p;
    List<HashMap<String, String>> list;
    switch(lib.getType()) {
        case TestDataLib.TYPE_CSV:
            /**
             * Before making the call we check if the Service Path is
             * already a proper URL. If it is not, we prefix with the CsvUrl
             * defined from corresponding database. This is used to get the
             * data from the correct environment.
             */
            String servicePathCsv = lib.getCsvUrl();
            LOG.debug("Service Path (Csv) : " + lib.getCsvUrl());
            // Trying making an URL with database context path.
            if (!StringUtil.isURL(servicePathCsv)) {
                // Url is not valid, we try to get the corresponding DatabaseURL CsvURL to prefix.
                if (!(StringUtil.isNullOrEmpty(lib.getDatabaseCsv()))) {
                    try {
                        countryEnvironmentDatabase = countryEnvironmentDatabaseService.convert(this.countryEnvironmentDatabaseService.readByKey(system, country, environment, lib.getDatabaseCsv()));
                        if (countryEnvironmentDatabase == null) {
                            msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_CSV_URLKOANDDATABASECSVURLNOTEXIST);
                            msg.setDescription(msg.getDescription().replace("%SERVICEURL%", lib.getCsvUrl()).replace("%SYSTEM%", system).replace("%COUNTRY%", country).replace("%ENV%", environment).replace("%DATABASE%", lib.getDatabaseCsv()));
                            result.setResultMessage(msg);
                            return result;
                        } else {
                            String csvURL = countryEnvironmentDatabase.getCsvUrl();
                            if (StringUtil.isNullOrEmpty(csvURL)) {
                                msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_CSV_URLKOANDDATABASECSVURLEMPTY);
                                msg.setDescription(msg.getDescription().replace("%SERVICEURL%", lib.getCsvUrl()).replace("%SYSTEM%", system).replace("%COUNTRY%", country).replace("%ENV%", environment).replace("%DATABASE%", lib.getDatabaseCsv()));
                                result.setResultMessage(msg);
                                return result;
                            }
                            // soapURL from database is not empty so we prefix the Service URL with it.
                            servicePathCsv = csvURL + lib.getCsvUrl();
                            if (!StringUtil.isURL(servicePathCsv)) {
                                msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_CSV_URLKO);
                                msg.setDescription(msg.getDescription().replace("%SERVICEURL%", servicePathCsv).replace("%SOAPURL%", csvURL).replace("%SERVICEPATH%", lib.getCsvUrl()).replace("%ENTRY%", lib.getName()).replace("%ENTRYID%", lib.getTestDataLibID().toString()));
                                result.setResultMessage(msg);
                                return result;
                            }
                        }
                    } catch (CerberusException ex) {
                        msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_CSV_URLKOANDDATABASECSVURLNOTEXIST);
                        msg.setDescription(msg.getDescription().replace("%SERVICEURL%", lib.getCsvUrl()).replace("%SYSTEM%", system).replace("%COUNTRY%", country).replace("%ENV%", environment).replace("%DATABASE%", lib.getDatabaseCsv()));
                        result.setResultMessage(msg);
                        return result;
                    }
                }
            }
            // Trying make a valid path with csv parameter path.
            if (!StringUtil.isURL(servicePathCsv)) {
                // Url is still not valid. We try to add the path from csv parameter.
                String csv_path = parameterService.getParameterStringByKey("cerberus_testdatalibcsv_path", "", "");
                csv_path = StringUtil.addSuffixIfNotAlready(csv_path, File.separator);
                servicePathCsv = csv_path + servicePathCsv;
            }
            // CSV Call is made here.
            responseList = fileService.parseCSVFile(servicePathCsv, lib.getSeparator(), columnList);
            list = responseList.getDataList();
            // if the query returns sucess then we can get the data
            if (responseList.getResultMessage().getCode() == MessageEventEnum.PROPERTY_SUCCESS_CSV.getCode()) {
                if (list != null && !list.isEmpty()) {
                    result.setDataList(list);
                    msg = new MessageEvent(MessageEventEnum.PROPERTY_SUCCESS_GETFROMDATALIB_CSV);
                    msg.setDescription(msg.getDescription().replace("%NBROW%", String.valueOf(result.getDataList().size())).replace("%CSVURL%", servicePathCsv));
                } else {
                    msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_CSVDATABASENODATA);
                    msg.setDescription(msg.getDescription().replace("%CSVURL%", servicePathCsv));
                }
            } else {
                msg = responseList.getResultMessage();
            }
            result.setResultMessage(msg);
            break;
        case TestDataLib.TYPE_SQL:
            String connectionName;
            String db = lib.getDatabase();
            try {
                if (StringUtil.isNullOrEmpty(db)) {
                    msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SQLDATABASEEMPTY);
                } else {
                    countryEnvironmentDatabase = countryEnvironmentDatabaseService.convert(countryEnvironmentDatabaseService.readByKey(system, country, environment, db));
                    if (countryEnvironmentDatabase == null) {
                        msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SQLDATABASENOTCONFIGURED);
                        msg.setDescription(msg.getDescription().replace("%SYSTEM%", system).replace("%COUNTRY%", country).replace("%ENV%", environment).replace("%DATABASE%", db));
                    } else {
                        connectionName = countryEnvironmentDatabase.getConnectionPoolName();
                        if (!(StringUtil.isNullOrEmpty(connectionName))) {
                            Integer sqlTimeout = parameterService.getParameterIntegerByKey("cerberus_propertyexternalsql_timeout", system, 60);
                            // performs a query that returns several rows containing n columns
                            responseList = sqlService.queryDatabaseNColumns(connectionName, lib.getScript(), rowLimit, sqlTimeout, system, columnList);
                            // if the query returns sucess then we can get the data
                            if (responseList.getResultMessage().getCode() == MessageEventEnum.PROPERTY_SUCCESS_SQL.getCode()) {
                                list = responseList.getDataList();
                                if (list != null && !list.isEmpty()) {
                                    result.setDataList(list);
                                    msg = new MessageEvent(MessageEventEnum.PROPERTY_SUCCESS_GETFROMDATALIB_SQL);
                                    msg.setDescription(msg.getDescription().replace("%NBROW%", String.valueOf(result.getDataList().size())));
                                } else {
                                    msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SQLDATABASENODATA);
                                }
                            } else {
                                msg = responseList.getResultMessage();
                            }
                            msg.setDescription(msg.getDescription().replace("%DATABASE%", db));
                            msg.setDescription(msg.getDescription().replace("%SQL%", lib.getScript()));
                            msg.setDescription(msg.getDescription().replace("%JDBCPOOLNAME%", connectionName));
                        } else {
                            msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SQLDATABASEJDBCRESSOURCEMPTY);
                            msg.setDescription(msg.getDescription().replace("%SYSTEM%", system).replace("%COUNTRY%", country).replace("%ENV%", environment).replace("%DATABASE%", db));
                        }
                    }
                }
            } catch (CerberusException ex) {
                msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SQLDATABASENOTCONFIGURED);
                msg.setDescription(msg.getDescription().replace("%SYSTEM%", system).replace("%COUNTRY%", country).replace("%ENV%", environment).replace("%DATABASE%", db));
            }
            result.setResultMessage(msg);
            break;
        case TestDataLib.TYPE_SERVICE:
            AppService appService = new AppService();
            HashMap<String, String> resultHash = new HashMap<>();
            List<HashMap<String, String>> listResult = new ArrayList<HashMap<String, String>>();
            // Temporary list of string.
            List<String> listTemp1 = null;
            // String containing the XML
            String responseString = "";
            /**
             * Before making the call we check if the Service Path is
             * already a propper URL. If it is not, we prefix with the
             * SoapUrl defined from corresponding database. This is used to
             * get the data from the correct environment.
             */
            String servicePath = lib.getServicePath();
            LOG.debug("Service Path : " + lib.getServicePath());
            // Service Call is made here.
            AnswerItem ai = serviceService.callService(lib.getService(), lib.getDatabaseUrl(), lib.getEnvelope(), lib.getServicePath(), lib.getMethod(), tCExecution);
            msg = ai.getResultMessage();
            // if the call returns success then we can process the soap ressponse
            if (msg.getCode() == MessageEventEnum.ACTION_SUCCESS_CALLSERVICE.getCode()) {
                appService = (AppService) ai.getItem();
                // Record result in filessytem.
                // testCaseExecutionData.addFileList(recorderService.recordServiceCall(tCExecution, null, 0, testCaseExecutionData.getProperty(), appService));
                recorderService.recordServiceCall(tCExecution, null, 0, testCaseExecutionData.getProperty(), appService);
                // Call successful so we can start to parse the result and build RawData per columns from subdata entries.
                /**
                 * This Step will calculate hashTemp1 : Hash of List from
                 * the Service response.
                 */
                // Will contain the nb of row of the target list of Hash.
                int finalnbRow = 0;
                // Will contain the result of the XML parsing.
                HashMap<String, List<String>> hashTemp1 = new HashMap<>();
                if (columnList.isEmpty()) {
                    // No subdata could be found on the testdatalib.
                    msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SERVICE_NOSUBDATA);
                    msg.setDescription(msg.getDescription().replace("%ENTRY%", lib.getName()).replace("%ENTRYID%", lib.getTestDataLibID().toString()));
                } else {
                    switch(appService.getResponseHTTPBodyContentType()) {
                        case AppService.RESPONSEHTTPBODYCONTENTTYPE_XML:
                            Document xmlDocument = xmlUnitService.getXmlDocument(appService.getResponseHTTPBody());
                            // We get the content of the XML in order to report it log messages.
                            responseString = appService.getResponseHTTPBody();
                            for (Map.Entry<String, String> entry : columnList.entrySet()) {
                                // SubData
                                String subDataColumnToTreat = entry.getKey();
                                // Parsing Answer
                                String subDataParsingAnswer = entry.getValue();
                                listTemp1 = new ArrayList<>();
                                try {
                                    // We try to parse the XML with the subdata Parsing Answer.
                                    NodeList candidates = XmlUtil.evaluate(xmlDocument, subDataParsingAnswer);
                                    if (candidates.getLength() > 0) {
                                        for (int i = 0; i < candidates.getLength(); i++) {
                                            // Loop on all Values that match in XML.
                                            // We get the value from XML
                                            String value = candidates.item(i).getNodeValue();
                                            if (value == null) {
                                                // No value found.
                                                if (candidates.item(i) != null) {
                                                    msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SERVICE_CHECK_XPATH);
                                                    msg.setDescription(msg.getDescription().replace("%XPATH%", subDataParsingAnswer).replace("%SUBDATA%", subDataColumnToTreat).replace("%ENTRY%", lib.getName()).replace("%ENTRYID%", lib.getTestDataLibID().toString()));
                                                } else {
                                                    // no elements were returned by the XPATH expression
                                                    msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SERVICE_XML_NOTFOUND);
                                                    msg.setDescription(msg.getDescription().replace("%XPATH%", subDataParsingAnswer).replace("%SUBDATA%", subDataColumnToTreat).replace("%ENTRY%", lib.getName()).replace("%XMLCONTENT%", responseString).replace("%ENTRYID%", lib.getTestDataLibID().toString()));
                                                }
                                            } else {
                                                // Value were found we add it to the current list.
                                                listTemp1.add(value);
                                            }
                                        }
                                        // Add the Subdata with associated list in the HashMap.
                                        hashTemp1.put(subDataColumnToTreat, listTemp1);
                                        // Getting the nb of row of the final result. (Max of all the Subdata retrieved from the XML)
                                        if (listTemp1.size() > finalnbRow) {
                                            finalnbRow = listTemp1.size();
                                        }
                                    } else {
                                        // no elements were returned by the XPATH expression
                                        msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SERVICE_XML_NOTFOUND);
                                        msg.setDescription(msg.getDescription().replace("%XPATH%", subDataParsingAnswer).replace("%SUBDATA%", subDataColumnToTreat).replace("%ENTRY%", lib.getName()).replace("%XMLCONTENT%", responseString).replace("%ENTRYID%", lib.getTestDataLibID().toString()));
                                    }
                                } catch (XmlUtilException ex) {
                                    msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SERVICE_XMLEXCEPTION);
                                    msg.setDescription(msg.getDescription().replace("%XPATH%", subDataParsingAnswer).replace("%SUBDATA%", subDataColumnToTreat).replace("%ENTRY%", lib.getName()).replace("%ENTRYID%", lib.getTestDataLibID().toString()).replace("%REASON%", ex.toString() + " Detail answer " + responseString));
                                } catch (Exception ex) {
                                    msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SERVICE_XMLEXCEPTION);
                                    msg.setDescription(msg.getDescription().replace("%XPATH%", lib.getSubDataParsingAnswer()).replace("%SUBDATA%", "").replace("%REASON%", ex.toString()));
                                }
                            }
                            /**
                             * This Step will convert hashTemp1 (Hash of
                             * List) to target listResult (list of Hash).
                             */
                            if (msg.getCode() == MessageEventEnum.ACTION_SUCCESS_CALLSERVICE.getCode()) {
                                for (int i = 0; i < finalnbRow; i++) {
                                    // Loop on all Values that match in XML.
                                    resultHash = new HashMap<String, String>();
                                    for (Map.Entry<String, String> entry : columnList.entrySet()) {
                                        // Loop on all SubData of the TestDataLib.
                                        listTemp1 = hashTemp1.get(entry.getKey());
                                        if (listTemp1 != null) {
                                            if (i < listTemp1.size()) {
                                                resultHash.put(entry.getKey(), listTemp1.get(i));
                                            } else {
                                                resultHash.put(entry.getKey(), "");
                                            }
                                        }
                                    }
                                    listResult.add(resultHash);
                                }
                            }
                            /**
                             * This Step will pick the correct listResult
                             * (list of Hash) from the type of Property.
                             */
                            if (msg.getCode() == MessageEventEnum.ACTION_SUCCESS_CALLSERVICE.getCode()) {
                                result.setDataList(listResult);
                                msg = new MessageEvent(MessageEventEnum.PROPERTY_SUCCESS_GETFROMDATALIB_SOAP);
                                msg.setDescription(msg.getDescription().replace("%NBROW%", String.valueOf(result.getDataList().size())).replace("%URL%", servicePath).replace("%OPER%", lib.getMethod()));
                            }
                            break;
                        case AppService.RESPONSEHTTPBODYCONTENTTYPE_JSON:
                            // We get the content of the XML in order to report it log messages.
                            responseString = appService.getResponseHTTPBody();
                            for (Map.Entry<String, String> entry : columnList.entrySet()) {
                                // SubData
                                String subDataColumnToTreat = entry.getKey();
                                // Parsing Answer
                                String subDataParsingAnswer = entry.getValue();
                                listTemp1 = new ArrayList<>();
                                try {
                                    // We try to parse the XML with the subdata Parsing Answer.
                                    listTemp1 = jsonService.getFromJson(responseString, subDataParsingAnswer);
                                    if (listTemp1.size() > 0) {
                                        // Add the Subdata with associated list in the HashMap.
                                        hashTemp1.put(subDataColumnToTreat, listTemp1);
                                        // Getting the nb of row of the final result. (Max of all the Subdata retrieved from the XML)
                                        if (listTemp1.size() > finalnbRow) {
                                            finalnbRow = listTemp1.size();
                                        }
                                    } else {
                                        // no elements were returned by the XPATH expression
                                        msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SERVICE_JSON_NOTFOUND);
                                        msg.setDescription(msg.getDescription().replace("%XPATH%", subDataParsingAnswer).replace("%SUBDATA%", subDataColumnToTreat).replace("%ENTRY%", lib.getName()).replace("%XMLCONTENT%", responseString).replace("%ENTRYID%", lib.getTestDataLibID().toString()));
                                    }
                                } catch (Exception ex) {
                                    msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SERVICE_JSONEXCEPTION);
                                    msg.setDescription(msg.getDescription().replace("%XPATH%", lib.getSubDataParsingAnswer()).replace("%SUBDATA%", "").replace("%REASON%", ex.toString()));
                                }
                            }
                            /**
                             * This Step will convert hashTemp1 (Hash of
                             * List) to target listResult (list of Hash).
                             */
                            if (msg.getCode() == MessageEventEnum.ACTION_SUCCESS_CALLSERVICE.getCode()) {
                                for (int i = 0; i < finalnbRow; i++) {
                                    // Loop on all Values that match in XML.
                                    resultHash = new HashMap<String, String>();
                                    for (Map.Entry<String, String> entry : columnList.entrySet()) {
                                        // Loop on all SubData of the TestDataLib.
                                        listTemp1 = hashTemp1.get(entry.getKey());
                                        if (listTemp1 != null) {
                                            if (i < listTemp1.size()) {
                                                resultHash.put(entry.getKey(), listTemp1.get(i));
                                            } else {
                                                resultHash.put(entry.getKey(), "");
                                            }
                                        }
                                    }
                                    listResult.add(resultHash);
                                }
                            }
                            /**
                             * This Step will pick the correct listResult
                             * (list of Hash) from the type of Property.
                             */
                            if (msg.getCode() == MessageEventEnum.ACTION_SUCCESS_CALLSERVICE.getCode()) {
                                result.setDataList(listResult);
                                msg = new MessageEvent(MessageEventEnum.PROPERTY_SUCCESS_GETFROMDATALIB_SOAP);
                                msg.setDescription(msg.getDescription().replace("%NBROW%", String.valueOf(result.getDataList().size())).replace("%URL%", servicePath).replace("%OPER%", lib.getMethod()));
                            }
                            break;
                        default:
                            msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_NOTSUPPORTEDSERVICERESULT);
                            msg.setDescription(msg.getDescription().replace("%FORMAT%", appService.getResponseHTTPBodyContentType()));
                    }
                }
            } else {
                String soapError = msg.getDescription();
                msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SERVICE_SOAPCALLFAILED);
                msg.setDescription(msg.getDescription().replace("%SOAPERROR%", soapError));
            }
            msg.setDescription(msg.getDescription().replace("%SERVICE%", servicePath).replace("%OPERATION%", lib.getMethod()));
            result.setResultMessage(msg);
            break;
        case TestDataLib.TYPE_INTERNAL:
            result = testDataLibService.readINTERNALWithSubdataByCriteria(lib.getName(), lib.getSystem(), lib.getCountry(), lib.getEnvironment(), rowLimit, system);
            // if the sql service returns a success message then we can process it
            if ((result.getResultMessage().getCode() == MessageEventEnum.DATA_OPERATION_OK.getCode()) && !result.getDataList().isEmpty()) {
                msg = new MessageEvent(MessageEventEnum.PROPERTY_SUCCESS_GETFROMDATALIB_INTERNAL);
                msg.setDescription(msg.getDescription().replace("%NBROW%", String.valueOf(result.getDataList().size())));
                result.setResultMessage(msg);
            } else if ((result.getResultMessage().getCode() == MessageEventEnum.DATA_OPERATION_OK.getCode()) && result.getDataList().isEmpty()) {
                msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_INTERNALNODATA);
                msg.setDescription(msg.getDescription().replace("%SYSTEM%", lib.getSystem()).replace("%ENV%", lib.getEnvironment()).replace("%COUNTRY%", lib.getCountry()));
                result.setResultMessage(msg);
            } else {
                msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_INTERNAL);
                msg.setDescription(msg.getDescription().replace("%SYSTEM%", lib.getSystem()).replace("%ENV%", lib.getEnvironment()).replace("%COUNTRY%", lib.getCountry()));
                result.setResultMessage(msg);
            }
            break;
    }
    return result;
}
Also used : Matcher(java.util.regex.Matcher) HashMap(java.util.HashMap) MessageEvent(org.cerberus.engine.entity.MessageEvent) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) AnswerList(org.cerberus.util.answer.AnswerList) List(java.util.List) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) XmlUtilException(org.cerberus.util.XmlUtilException) Pattern(java.util.regex.Pattern) AnswerList(org.cerberus.util.answer.AnswerList) CerberusException(org.cerberus.exception.CerberusException) IFactoryAppService(org.cerberus.crud.factory.IFactoryAppService) AppService(org.cerberus.crud.entity.AppService) NodeList(org.w3c.dom.NodeList) AnswerItem(org.cerberus.util.answer.AnswerItem) JSONException(org.json.JSONException) CerberusEventException(org.cerberus.exception.CerberusEventException) CerberusException(org.cerberus.exception.CerberusException) XmlUtilException(org.cerberus.util.XmlUtilException) Parameter(org.cerberus.crud.entity.Parameter) Map(java.util.Map) HashMap(java.util.HashMap) CountryEnvironmentDatabase(org.cerberus.crud.entity.CountryEnvironmentDatabase)

Example 13 with CountryEnvironmentDatabase

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

the class CountryEnvironmentDatabaseService method compareListAndUpdateInsertDeleteElements.

@Override
public Answer compareListAndUpdateInsertDeleteElements(String system, String country, String environement, List<CountryEnvironmentDatabase> newList) {
    Answer ans = new Answer(null);
    MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
    Answer finalAnswer = new Answer(msg1);
    List<CountryEnvironmentDatabase> oldList = new ArrayList();
    try {
        oldList = this.convert(this.readByVarious(system, country, environement));
    } catch (CerberusException ex) {
        LOG.error(ex);
    }
    /**
     * Iterate on (TestCaseStep From Page - TestCaseStep From Database) If
     * TestCaseStep in Database has same key : Update and remove from the
     * list. If TestCaseStep in database does ot exist : Insert it.
     */
    List<CountryEnvironmentDatabase> listToUpdateOrInsert = new ArrayList(newList);
    listToUpdateOrInsert.removeAll(oldList);
    List<CountryEnvironmentDatabase> listToUpdateOrInsertToIterate = new ArrayList(listToUpdateOrInsert);
    for (CountryEnvironmentDatabase objectDifference : listToUpdateOrInsertToIterate) {
        for (CountryEnvironmentDatabase objectInDatabase : oldList) {
            if (objectDifference.hasSameKey(objectInDatabase)) {
                ans = this.update(objectDifference);
                finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                listToUpdateOrInsert.remove(objectDifference);
            }
        }
    }
    /**
     * Iterate on (TestCaseStep From Database - TestCaseStep From Page). If
     * TestCaseStep in Page has same key : remove from the list. Then delete
     * the list of TestCaseStep
     */
    List<CountryEnvironmentDatabase> listToDelete = new ArrayList(oldList);
    listToDelete.removeAll(newList);
    List<CountryEnvironmentDatabase> listToDeleteToIterate = new ArrayList(listToDelete);
    for (CountryEnvironmentDatabase objectDifference : listToDeleteToIterate) {
        for (CountryEnvironmentDatabase objectInPage : newList) {
            if (objectDifference.hasSameKey(objectInPage)) {
                listToDelete.remove(objectDifference);
            }
        }
    }
    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) CountryEnvironmentDatabase(org.cerberus.crud.entity.CountryEnvironmentDatabase)

Aggregations

CountryEnvironmentDatabase (org.cerberus.crud.entity.CountryEnvironmentDatabase)13 MessageEvent (org.cerberus.engine.entity.MessageEvent)9 CerberusException (org.cerberus.exception.CerberusException)7 ArrayList (java.util.ArrayList)5 IFactoryCountryEnvironmentDatabase (org.cerberus.crud.factory.IFactoryCountryEnvironmentDatabase)5 AnswerItem (org.cerberus.util.answer.AnswerItem)5 Connection (java.sql.Connection)4 SQLException (java.sql.SQLException)4 CerberusEventException (org.cerberus.exception.CerberusEventException)4 JSONObject (org.json.JSONObject)4 PreparedStatement (java.sql.PreparedStatement)3 List (java.util.List)3 AppService (org.cerberus.crud.entity.AppService)3 ICountryEnvironmentDatabaseService (org.cerberus.crud.service.ICountryEnvironmentDatabaseService)3 ResultSet (java.sql.ResultSet)2 SQLTimeoutException (java.sql.SQLTimeoutException)2 IFactoryAppService (org.cerberus.crud.factory.IFactoryAppService)2 AnswerList (org.cerberus.util.answer.AnswerList)2 PolicyFactory (org.owasp.html.PolicyFactory)2 ApplicationContext (org.springframework.context.ApplicationContext)2