Search in sources :

Example 6 with IParameterService

use of org.cerberus.crud.service.IParameterService in project cerberus-source by cerberustesting.

the class UpdateParameter method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request  servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException      if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding();
    ILogEventService logEventService;
    String id = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("id"), "", charset);
    String value = ParameterParserUtil.parseStringParam(request.getParameter("value"), "");
    String system = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("system"), "", charset);
    String system1value = ParameterParserUtil.parseStringParam(request.getParameter("system1Value"), null);
    String system1 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("system1"), null, charset);
    boolean userHasPermissions = request.isUserInRole("Administrator");
    // Prepare the final answer.
    MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
    Answer finalAnswer = new Answer(msg1);
    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(id) || StringUtil.isNullOrEmpty(system1)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Parameter").replace("%OPERATION%", "Update").replace("%REASON%", "Parameter id or system1 is missing!"));
        finalAnswer.setResultMessage(msg);
    } else if (!userHasPermissions) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Parameter").replace("%OPERATION%", "Update").replace("%REASON%", "You don't have the right to do that"));
        finalAnswer.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IParameterService parameterService = appContext.getBean(IParameterService.class);
        FactoryParameter factoryparameter = appContext.getBean(FactoryParameter.class);
        Parameter para = factoryparameter.create(system, id, value, "");
        ans = parameterService.save(para);
        if (!ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && !ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED.getCode())) {
            /**
             * Object could not be found. We stop here and report the error.
             */
            finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
        } else {
            if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                logEventService = appContext.getBean(LogEventService.class);
                logEventService.createForPrivateCalls("/UpdateParameter", "UPDATE", "Update Parameter : ['" + id + "','" + system + "']", request);
            }
            if (system1 != null && system1value != null) {
                Parameter para1 = factoryparameter.create(system1, id, system1value, "");
                ans = parameterService.save(para1);
                if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    /**
                     * Object updated. Adding Log entry.
                     */
                    logEventService = appContext.getBean(LogEventService.class);
                    logEventService.createForPrivateCalls("/UpdateParameter", "UPDATE", "Update Parameter : ['" + id + "','" + system1 + "']", request);
                }
            }
        }
    }
    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());
    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
Also used : FactoryParameter(org.cerberus.crud.factory.impl.FactoryParameter) Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) JSONObject(org.json.JSONObject) PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) ILogEventService(org.cerberus.crud.service.ILogEventService) Parameter(org.cerberus.crud.entity.Parameter) FactoryParameter(org.cerberus.crud.factory.impl.FactoryParameter) IParameterService(org.cerberus.crud.service.IParameterService)

Example 7 with IParameterService

use of org.cerberus.crud.service.IParameterService in project cerberus-source by cerberustesting.

the class ForgotPassword method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IUserService userService = appContext.getBean(UserService.class);
        IEmailService emailService = appContext.getBean(IEmailService.class);
        IParameterService parameterService = appContext.getBean(ParameterService.class);
        String system = "";
        JSONObject jsonResponse = new JSONObject();
        String login = ParameterParserUtil.parseStringParam(request.getParameter("login"), "");
        /**
         * Check if notification parameter is set to Y. If not, return an
         * error
         */
        String sendNotification = parameterService.findParameterByKey("cerberus_notification_accountcreation_activatenotification", system).getValue();
        if (!sendNotification.equalsIgnoreCase("Y")) {
            jsonResponse.put("messageType", "Error");
            jsonResponse.put("message", "This functionality is not activated. Please contact your Cerberus Administrator.");
            response.getWriter().print(jsonResponse);
            response.getWriter().flush();
            return;
        }
        /**
         * If email not found in database, send error message
         */
        AnswerItem ai = userService.readByKey(login);
        User user = (User) ai.getItem();
        if (user == null) {
            jsonResponse.put("messageType", "Error");
            jsonResponse.put("message", "Login submitted is unknown !");
            response.getWriter().print(jsonResponse);
            response.getWriter().flush();
            return;
        }
        /**
         * Update user setting a new value in requestresetpassword
         */
        userService.requestResetPassword(user);
        /**
         * Send an email with the hash as a parameter
         */
        Answer mailSent = new Answer(emailService.generateAndSendForgotPasswordEmail(user));
        if (!mailSent.isCodeStringEquals("OK")) {
            jsonResponse.put("messageType", "Error");
            jsonResponse.put("message", "An error occured sending the notification. Detail : " + mailSent.getMessageDescription());
            response.getWriter().print(jsonResponse);
            response.getWriter().flush();
            return;
        }
        /**
         * Adding Log entry.
         */
        ILogEventService logEventService = appContext.getBean(ILogEventService.class);
        logEventService.createForPrivateCalls("/ForgotPassword", "CREATE", "User : " + login + " asked for password recovery", request);
        /**
         * Build Response Message
         */
        jsonResponse.put("messageType", "OK");
        jsonResponse.put("message", "An e-mail has been sent to the mailbox " + user.getEmail() + ".");
        response.getWriter().print(jsonResponse);
        response.getWriter().flush();
    } catch (CerberusException myexception) {
        response.getWriter().print(myexception.getMessageError().getDescription());
    } catch (JSONException ex) {
        LOG.warn(ex);
        response.setContentType("application/json");
        response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
    }
}
Also used : CerberusException(org.cerberus.exception.CerberusException) User(org.cerberus.crud.entity.User) JSONException(org.json.JSONException) IParameterService(org.cerberus.crud.service.IParameterService) AnswerItem(org.cerberus.util.answer.AnswerItem) Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) JSONObject(org.json.JSONObject) IUserService(org.cerberus.crud.service.IUserService) ILogEventService(org.cerberus.crud.service.ILogEventService) IEmailService(org.cerberus.service.email.IEmailService) PrintWriter(java.io.PrintWriter)

Example 8 with IParameterService

use of org.cerberus.crud.service.IParameterService in project cerberus-source by cerberustesting.

the class CalculatePropertyForTestCase method doGet.

@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.BLOCKS);
    String type = policy.sanitize(httpServletRequest.getParameter("type"));
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    String result = null;
    String description = null;
    String system = "";
    String property = httpServletRequest.getParameter("property");
    String testName = policy.sanitize(httpServletRequest.getParameter("test"));
    String testCaseName = policy.sanitize(httpServletRequest.getParameter("testCase"));
    String country = policy.sanitize(httpServletRequest.getParameter("country"));
    String environment = policy.sanitize(httpServletRequest.getParameter("environment"));
    try {
        if (type.equals("executeSoapFromLib")) {
            IAppServiceService appServiceService = appContext.getBean(AppServiceService.class);
            ISoapService soapService = appContext.getBean(ISoapService.class);
            IXmlUnitService xmlUnitService = appContext.getBean(IXmlUnitService.class);
            AppService appService = appServiceService.findAppServiceByKey(property);
            if (appService != null) {
                ExecutionUUID executionUUIDObject = appContext.getBean(ExecutionUUID.class);
                UUID executionUUID = UUID.randomUUID();
                executionUUIDObject.setExecutionUUID(executionUUID.toString(), null);
                soapService.callSOAP(appService.getServiceRequest(), appService.getServicePath(), appService.getOperation(), appService.getAttachementURL(), null, null, 60000, system);
                result = xmlUnitService.getFromXml(executionUUID.toString(), appService.getAttachementURL());
                description = appService.getDescription();
                executionUUIDObject.removeExecutionUUID(executionUUID.toString());
                LOG.debug("Clean ExecutionUUID");
            }
        } else {
            try {
                ITestCaseService testCaseService = appContext.getBean(TestCaseService.class);
                IApplicationService applicationService = appContext.getBean(ApplicationService.class);
                TestCase testCase = testCaseService.findTestCaseByKey(testName, testCaseName);
                if (testCase != null) {
                    system = applicationService.convert(applicationService.readByKey(testCase.getApplication())).getSystem();
                } else {
                    throw new CerberusException(new MessageGeneral(MessageGeneralEnum.NO_DATA_FOUND));
                }
            } catch (CerberusException ex) {
                LOG.warn(ex);
            }
            if (system != null) {
                String database = policy.sanitize(httpServletRequest.getParameter("database"));
                ICountryEnvironmentDatabaseService countryEnvironmentDatabaseService = appContext.getBean(CountryEnvironmentDatabaseService.class);
                CountryEnvironmentDatabase countryEnvironmentDatabase;
                countryEnvironmentDatabase = countryEnvironmentDatabaseService.convert(countryEnvironmentDatabaseService.readByKey(system, country, environment, database));
                String connectionName = countryEnvironmentDatabase.getConnectionPoolName();
                if (type.equals("executeSqlFromLib")) {
                    ISqlLibraryService sqlLibraryService = appContext.getBean(SqlLibraryService.class);
                    SqlLibrary sl = sqlLibraryService.findSqlLibraryByKey(policy.sanitize(property));
                    property = sl.getScript();
                    if (!(StringUtil.isNullOrEmpty(connectionName)) && !(StringUtil.isNullOrEmpty(policy.sanitize(property)))) {
                        ISQLService sqlService = appContext.getBean(ISQLService.class);
                        IParameterService parameterService = appContext.getBean(IParameterService.class);
                        Integer sqlTimeout = parameterService.getParameterIntegerByKey("cerberus_propertyexternalsql_timeout", system, 60);
                        result = sqlService.queryDatabase(connectionName, policy.sanitize(property), 1, sqlTimeout).get(0);
                        description = sl.getDescription();
                    }
                }
            }
        }
    } catch (CerberusException ex) {
        LOG.warn(ex);
        result = ex.getMessageError().getDescription();
        description = ex.getMessageError().getDescription();
    } catch (CerberusEventException ex) {
        LOG.warn(ex);
        result = ex.getMessageError().getDescription();
        description = ex.getMessageError().getDescription();
    }
    if (result != null) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("resultList", result);
            jsonObject.put("description", description);
            httpServletResponse.setContentType("application/json");
            httpServletResponse.getWriter().print(jsonObject.toString());
        } catch (JSONException exception) {
            LOG.warn(exception.toString());
        }
    }
}
Also used : AppService(org.cerberus.crud.entity.AppService) CerberusException(org.cerberus.exception.CerberusException) PolicyFactory(org.owasp.html.PolicyFactory) ExecutionUUID(org.cerberus.engine.entity.ExecutionUUID) SqlLibrary(org.cerberus.crud.entity.SqlLibrary) JSONException(org.json.JSONException) IAppServiceService(org.cerberus.crud.service.IAppServiceService) IParameterService(org.cerberus.crud.service.IParameterService) CerberusEventException(org.cerberus.exception.CerberusEventException) ApplicationContext(org.springframework.context.ApplicationContext) ISQLService(org.cerberus.service.sql.ISQLService) MessageGeneral(org.cerberus.engine.entity.MessageGeneral) JSONObject(org.json.JSONObject) ISoapService(org.cerberus.service.soap.ISoapService) TestCase(org.cerberus.crud.entity.TestCase) ITestCaseService(org.cerberus.crud.service.ITestCaseService) ISqlLibraryService(org.cerberus.crud.service.ISqlLibraryService) ICountryEnvironmentDatabaseService(org.cerberus.crud.service.ICountryEnvironmentDatabaseService) UUID(java.util.UUID) ExecutionUUID(org.cerberus.engine.entity.ExecutionUUID) IXmlUnitService(org.cerberus.service.xmlunit.IXmlUnitService) IApplicationService(org.cerberus.crud.service.IApplicationService) CountryEnvironmentDatabase(org.cerberus.crud.entity.CountryEnvironmentDatabase)

Example 9 with IParameterService

use of org.cerberus.crud.service.IParameterService in project cerberus-source by cerberustesting.

the class ReadTestCaseExecutionMedia method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 * @throws CerberusException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException {
    String charset = request.getCharacterEncoding();
    boolean auto = ParameterParserUtil.parseBooleanParam(request.getParameter("auto"), true);
    String type = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("type"), "", charset);
    String test = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("test"), "", charset);
    String testcase = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("testcase"), "", charset);
    String fileName = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("filename"), "", charset);
    String fileType = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("filetype"), "", charset);
    String fileDesc = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("filedesc"), "", charset);
    int step = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("step"), 0, charset);
    int index = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("index"), 1, charset);
    int sequence = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("sequence"), 0, charset);
    int sequenceControl = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("sequenceControl"), 0, charset);
    int iterator = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("iterator"), 0, charset);
    boolean autoContentType = ParameterParserUtil.parseBooleanParam(request.getParameter("autoContentType"), true);
    long id = ParameterParserUtil.parseLongParamAndDecode(request.getParameter("id"), 0, charset);
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    IParameterService parameterService = appContext.getBean(IParameterService.class);
    BufferedImage b = null;
    AnswerList al = new AnswerList<>(new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED));
    TestCaseExecutionFile tceFile = null;
    if (!(fileName.equals(""))) {
        IFactoryTestCaseExecutionFile factoryTestCaseExecutionFile = appContext.getBean(IFactoryTestCaseExecutionFile.class);
        tceFile = factoryTestCaseExecutionFile.create(0, 0, "", fileDesc, fileName, fileType, "", null, "", null);
    } else {
        ITestCaseExecutionFileService testCaseExecutionFileService = appContext.getBean(ITestCaseExecutionFileService.class);
        String levelFile = "";
        if (type.equals("action")) {
            levelFile = test + "-" + testcase + "-" + step + "-" + index + "-" + sequence;
        } else if (type.equals("control")) {
            levelFile = test + "-" + testcase + "-" + step + "-" + index + "-" + sequence + "-" + sequenceControl;
        }
        al = testCaseExecutionFileService.readByVarious(id, levelFile);
        if (al.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && !al.getDataList().isEmpty()) {
            Iterator i = al.getDataList().iterator();
            int indexIterator = -1;
            while (i.hasNext() && indexIterator != iterator) {
                indexIterator++;
                TestCaseExecutionFile tctemp = (TestCaseExecutionFile) i.next();
                if (indexIterator == iterator) {
                    tceFile = tctemp;
                }
            }
        } else {
            // If previous read failed we try without index. (that can be removed few moths after step index has been introduced in Jan 2017)
            if (type.equals("action")) {
                levelFile = test + "-" + testcase + "-" + step + "-" + sequence;
            } else if (type.equals("control")) {
                levelFile = test + "-" + testcase + "-" + step + "-" + sequence + "-" + sequenceControl;
            }
            al = testCaseExecutionFileService.readByVarious(id, levelFile);
            if (al.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && !al.getDataList().isEmpty()) {
                Iterator i = al.getDataList().iterator();
                int indexIterator = -1;
                while (i.hasNext() && indexIterator != iterator) {
                    indexIterator++;
                    TestCaseExecutionFile tctemp = (TestCaseExecutionFile) i.next();
                    if (indexIterator == iterator) {
                        tceFile = tctemp;
                    }
                }
            }
        }
    }
    if (tceFile != null) {
        String pathString = "";
        if (auto) {
            pathString = parameterService.getParameterStringByKey("cerberus_exeautomedia_path", "", "");
        } else {
            pathString = parameterService.getParameterStringByKey("cerberus_exemanualmedia_path", "", "");
        }
        switch(tceFile.getFileType()) {
            case "JPG":
            case "JPEG":
                if (autoContentType) {
                    response.setContentType("image/jpeg");
                }
                returnImage(request, response, tceFile, pathString);
                break;
            case "PNG":
                if (autoContentType) {
                    response.setContentType("image/png");
                }
                returnImage(request, response, tceFile, pathString);
                break;
            case "GIF":
                if (autoContentType) {
                    response.setContentType("image/gif");
                }
                returnImage(request, response, tceFile, pathString);
                break;
            case "HTML":
                if (autoContentType) {
                    response.setContentType("text/html");
                }
                returnFile(request, response, tceFile, pathString);
                break;
            case "XML":
                if (autoContentType) {
                    response.setContentType("application/xml");
                }
                returnFile(request, response, tceFile, pathString);
                break;
            case "JSON":
                if (autoContentType) {
                    response.setContentType("application/json");
                }
                returnFile(request, response, tceFile, pathString);
                break;
            case "TXT":
                returnFile(request, response, tceFile, pathString);
                break;
            case "PDF":
                returnPDF(request, response, tceFile, pathString);
            default:
                returnNotSupported(request, response, tceFile, pathString);
        }
    }
}
Also used : AnswerList(org.cerberus.util.answer.AnswerList) MessageEvent(org.cerberus.engine.entity.MessageEvent) IFactoryTestCaseExecutionFile(org.cerberus.crud.factory.IFactoryTestCaseExecutionFile) ITestCaseExecutionFileService(org.cerberus.crud.service.ITestCaseExecutionFileService) IParameterService(org.cerberus.crud.service.IParameterService) BufferedImage(java.awt.image.BufferedImage) ApplicationContext(org.springframework.context.ApplicationContext) IFactoryTestCaseExecutionFile(org.cerberus.crud.factory.IFactoryTestCaseExecutionFile) TestCaseExecutionFile(org.cerberus.crud.entity.TestCaseExecutionFile)

Example 10 with IParameterService

use of org.cerberus.crud.service.IParameterService in project cerberus-source by cerberustesting.

the class CreateTestDataLib method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    IFactoryTestDataLibData tdldFactory = appContext.getBean(IFactoryTestDataLibData.class);
    ITestDataLibDataService tdldService = appContext.getBean(ITestDataLibDataService.class);
    IParameterService parameterService = appContext.getBean(IParameterService.class);
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    AnswerItem ansItem = new AnswerItem();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding();
    response.setContentType("application/json");
    Map<String, String> fileData = new HashMap<String, String>();
    FileItem file = null;
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        List<FileItem> fields = upload.parseRequest(request);
        Iterator<FileItem> it = fields.iterator();
        if (!it.hasNext()) {
            return;
        }
        while (it.hasNext()) {
            FileItem fileItem = it.next();
            boolean isFormField = fileItem.isFormField();
            if (isFormField) {
                fileData.put(fileItem.getFieldName(), ParameterParserUtil.parseStringParamAndDecode(fileItem.getString("UTF-8"), "", charset));
            } else {
                file = fileItem;
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
    try {
        /**
         * Parsing and securing all required parameters.
         */
        // Parameter that are already controled by GUI (no need to decode) --> We SECURE them
        String type = policy.sanitize(fileData.get("type"));
        String system = policy.sanitize(fileData.get("system"));
        String environment = policy.sanitize(fileData.get("environment"));
        String country = policy.sanitize(fileData.get("country"));
        String database = policy.sanitize(fileData.get("database"));
        String databaseUrl = policy.sanitize(fileData.get("databaseUrl"));
        String databaseCsv = policy.sanitize(fileData.get("databaseCsv"));
        // Parameter that needs to be secured --> We SECURE+DECODE them
        // this is mandatory
        String name = fileData.get("name");
        String group = fileData.get("group");
        String description = fileData.get("libdescription");
        String service = fileData.get("service");
        // Parameter that we cannot secure as we need the html --> We DECODE them
        String script = fileData.get("script");
        String servicePath = fileData.get("servicepath");
        String method = fileData.get("method");
        String envelope = fileData.get("envelope");
        String csvUrl = fileData.get("csvUrl");
        String separator = fileData.get("separator");
        String test = fileData.get("subdataCheck");
        /**
         * Checking all constrains before calling the services.
         */
        // Prepare the final answer.
        MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
        Answer finalAnswer = new Answer(msg1);
        if (StringUtil.isNullOrEmpty(name)) {
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Test Data Library").replace("%OPERATION%", "Create").replace("%REASON%", "Test data library name is missing! "));
            finalAnswer.setResultMessage(msg);
        } else {
            /**
             * All data seems cleans so we can call the services.
             */
            ITestDataLibService libService = appContext.getBean(ITestDataLibService.class);
            IFactoryTestDataLib factoryLibService = appContext.getBean(IFactoryTestDataLib.class);
            TestDataLib lib = factoryLibService.create(0, name, system, environment, country, group, type, database, script, databaseUrl, service, servicePath, method, envelope, databaseCsv, csvUrl, separator, description, request.getRemoteUser(), null, "", null, null, null, null, null);
            // Creates the entries and the subdata list
            ansItem = libService.create(lib);
            finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ansItem);
            /**
             * Object created. Adding Log entry.
             */
            if (ansItem.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                ILogEventService logEventService = appContext.getBean(LogEventService.class);
                logEventService.createForPrivateCalls("/CreateTestDataLib", "CREATE", "Create TestDataLib  : " + request.getParameter("name"), request);
            }
            List<TestDataLibData> tdldList = new ArrayList();
            TestDataLib dataLibWithUploadedFile = (TestDataLib) ansItem.getItem();
            if (file != null) {
                ans = libService.uploadFile(dataLibWithUploadedFile.getTestDataLibID(), file);
                if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    dataLibWithUploadedFile.setCsvUrl(File.separator + dataLibWithUploadedFile.getTestDataLibID() + File.separator + file.getName());
                    libService.update(dataLibWithUploadedFile);
                }
            }
            // Getting list of SubData from JSON Call
            if (fileData.get("subDataList") != null) {
                JSONArray objSubDataArray = new JSONArray(fileData.get("subDataList"));
                tdldList = getSubDataFromParameter(request, appContext, dataLibWithUploadedFile.getTestDataLibID(), objSubDataArray);
            }
            if (file != null && test.equals("1")) {
                String firstLine = "";
                String secondLine = "";
                try (BufferedReader reader = new BufferedReader(new FileReader(parameterService.getParameterStringByKey("cerberus_testdatalibCSV_path", "", null) + lib.getCsvUrl()))) {
                    firstLine = reader.readLine();
                    secondLine = reader.readLine();
                    String[] firstLineSubData = (!dataLibWithUploadedFile.getSeparator().isEmpty()) ? firstLine.split(dataLibWithUploadedFile.getSeparator()) : firstLine.split(",");
                    String[] secondLineSubData = (!dataLibWithUploadedFile.getSeparator().isEmpty()) ? secondLine.split(dataLibWithUploadedFile.getSeparator()) : secondLine.split(",");
                    int i = 0;
                    int y = 1;
                    TestDataLibData firstLineLibData = tdldList.get(0);
                    tdldList = new ArrayList();
                    if (StringUtil.isNullOrEmpty(firstLineLibData.getColumnPosition())) {
                        firstLineLibData.setColumnPosition("1");
                    }
                    if (StringUtil.isNullOrEmpty(firstLineLibData.getValue())) {
                        firstLineLibData.setValue(secondLineSubData[0]);
                    }
                    if (StringUtil.isNullOrEmpty(firstLineLibData.getColumn())) {
                        firstLineLibData.setColumn(firstLineSubData[0]);
                    }
                    tdldList.add(firstLineLibData);
                    for (String item : firstLineSubData) {
                        TestDataLibData tdld = tdldFactory.create(null, dataLibWithUploadedFile.getTestDataLibID(), item + "_" + y, secondLineSubData[i], item, null, Integer.toString(y), null);
                        tdldList.add(tdld);
                        i++;
                        y++;
                    }
                // Update the Database with the new list.
                } finally {
                    try {
                        file.getInputStream().close();
                    } catch (Throwable ignore) {
                    }
                }
            }
            ans = tdldService.compareListAndUpdateInsertDeleteElements(dataLibWithUploadedFile.getTestDataLibID(), tdldList);
            finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
        }
        /**
         * Formating and returning the json result.
         */
        // sets the message returned by the operations
        jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
        jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());
        response.getWriter().print(jsonResponse);
        response.getWriter().flush();
    } catch (JSONException ex) {
        LOG.warn(ex);
        response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
        response.getWriter().flush();
    }
}
Also used : PolicyFactory(org.owasp.html.PolicyFactory) HashMap(java.util.HashMap) MessageEvent(org.cerberus.engine.entity.MessageEvent) IFactoryTestDataLibData(org.cerberus.crud.factory.IFactoryTestDataLibData) ArrayList(java.util.ArrayList) IParameterService(org.cerberus.crud.service.IParameterService) ITestDataLibDataService(org.cerberus.crud.service.ITestDataLibDataService) ApplicationContext(org.springframework.context.ApplicationContext) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ILogEventService(org.cerberus.crud.service.ILogEventService) FileReader(java.io.FileReader) TestDataLib(org.cerberus.crud.entity.TestDataLib) IFactoryTestDataLib(org.cerberus.crud.factory.IFactoryTestDataLib) IFactoryTestDataLib(org.cerberus.crud.factory.IFactoryTestDataLib) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) AnswerItem(org.cerberus.util.answer.AnswerItem) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) Answer(org.cerberus.util.answer.Answer) FileItem(org.apache.commons.fileupload.FileItem) JSONObject(org.json.JSONObject) BufferedReader(java.io.BufferedReader) ITestDataLibService(org.cerberus.crud.service.ITestDataLibService) FileUploadException(org.apache.commons.fileupload.FileUploadException) IFactoryTestDataLibData(org.cerberus.crud.factory.IFactoryTestDataLibData) TestDataLibData(org.cerberus.crud.entity.TestDataLibData)

Aggregations

IParameterService (org.cerberus.crud.service.IParameterService)19 ApplicationContext (org.springframework.context.ApplicationContext)19 ILogEventService (org.cerberus.crud.service.ILogEventService)13 JSONObject (org.json.JSONObject)12 MessageEvent (org.cerberus.engine.entity.MessageEvent)9 JSONException (org.json.JSONException)9 PolicyFactory (org.owasp.html.PolicyFactory)9 PrintWriter (java.io.PrintWriter)8 Answer (org.cerberus.util.answer.Answer)8 CerberusException (org.cerberus.exception.CerberusException)7 AnswerItem (org.cerberus.util.answer.AnswerItem)7 IOException (java.io.IOException)5 ServletException (javax.servlet.ServletException)5 IEmailService (org.cerberus.service.email.IEmailService)4 BufferedReader (java.io.BufferedReader)3 Timestamp (java.sql.Timestamp)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 FileItem (org.apache.commons.fileupload.FileItem)3 FileUploadException (org.apache.commons.fileupload.FileUploadException)3