Best Cerberus-source code snippet using org.cerberus.servlet.crud.test.testcase.ImportTestCaseFromSIDE.processRequest
Source:ImportTestCaseFromSIDE.java
...86 * @param httpServletResponse87 * @throws ServletException if a servlet-specific error occurs88 * @throws IOException if an I/O error occurs89 */90 protected void processRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)91 throws ServletException, IOException {92 JSONObject jsonResponse = new JSONObject();93 try {94 try {95 ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());96 testcaseService = appContext.getBean(ITestCaseService.class);97 testcaseFactory = appContext.getBean(IFactoryTestCase.class);98 testcaseStepFactory = appContext.getBean(IFactoryTestCaseStep.class);99 testcaseStepActionFactory = appContext.getBean(IFactoryTestCaseStepAction.class);100 applicationService = appContext.getBean(IApplicationService.class);101 invariantService = appContext.getBean(IInvariantService.class);102 testcaseCountryFactory = appContext.getBean(IFactoryTestCaseCountry.class);103 countryEnvironmentParametersService = appContext.getBean(ICountryEnvironmentParametersService.class);104 Answer ans = new Answer();105 MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);106 msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));107 ans.setResultMessage(msg);108 ///Get files109// List<String> files = getFiles(httpServletRequest);110 HashMap<String, String> param = getParams(httpServletRequest);111 String userCreated = httpServletRequest.getUserPrincipal().getName();112 // Prepare the final answer.113 MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);114 Answer finalAnswer = new Answer(msg1);115 String targetFolder = param.get("test");116 String targetApplication = param.get("application");117 LOG.debug("Requested Test Folder : " + targetFolder);118 LOG.debug("Requested Test Application : " + targetApplication);119 List<Invariant> countries = invariantService.readByIdName("COUNTRY");120 Application app = applicationService.convert(applicationService.readByKey(targetApplication));121 List<CountryEnvironmentParameters> envParams = countryEnvironmentParametersService.convert(countryEnvironmentParametersService.readByVarious(null, null, null, targetApplication));122 List<String> urls = new ArrayList<>();123 for (CountryEnvironmentParameters envParam : envParams) {124 urls.add(envParam.getIp());125 }126 for (Map.Entry<String, String> entry : param.entrySet()) {127 String key = entry.getKey();128 String val = entry.getValue();129 if (key.startsWith("file")) {130 JSONObject json = new JSONObject(val);131 if (isCompatible(json)) {132 String masterSIDEURL = json.getString("url");133 JSONArray testList = new JSONArray();134 testList = json.getJSONArray("tests");135 for (int i = 0; i < testList.length(); i++) {136 JSONObject test = new JSONObject();137 test = testList.getJSONObject(i);138 LOG.debug("importing :" + i + " : " + test.toString());139 // Dynamically get a new testcase ID.140 String targetTestcase = testcaseService.getNextAvailableTestcaseId(targetFolder);141 TestCase newTC = testcaseFactory.create(targetFolder, targetTestcase, test.getString("name"));142 newTC.setComment("Imported from Selenium IDE. Test ID : " + test.getString("id"));143 newTC.setApplication(targetApplication);144 newTC.setType(TestCase.TESTCASE_TYPE_AUTOMATED);145 newTC.setConditionOperator("always");146 newTC.setOrigine(TestCase.TESTCASE_ORIGIN_SIDE);147 newTC.setRefOrigine(test.getString("id"));148 newTC.setStatus("WORKING");149 newTC.setUsrCreated(userCreated);150 countries.forEach(country -> {151 newTC.appendTestCaseCountries(testcaseCountryFactory.create(targetFolder, targetTestcase, country.getValue()));152 });153 // Step154 TestCaseStep newStep = testcaseStepFactory.create(targetFolder, targetTestcase, 1, 1, TestCaseStep.LOOP_ONCEIFCONDITIONTRUE, "always", "", "", "", new JSONArray(), "", false, null, null, 0, false, false, userCreated, null, null, null);155 // Action156 for (int j = 0; j < test.getJSONArray("commands").length(); j++) {157 JSONObject command = test.getJSONArray("commands").getJSONObject(j);158 TestCaseStepAction newA = getActionFromSIDE(command, (j + 1), masterSIDEURL, urls, targetFolder, targetTestcase);159 if (newA != null) {160 newStep.appendActions(newA);161 }162 }163 newTC.appendSteps(newStep);164 testcaseService.createTestcaseWithDependencies(newTC);165 }166 } else {167 msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);168 msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCase ")169 .replace("%OPERATION%", "Import")170 .replace("%REASON%", "The file you're trying to import is not supported or is not in a compatible version format."));171 ans.setResultMessage(msg);172 finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, ans);173 }174 }175 }176 jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());177 jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());178 } catch (Exception ex) {179 jsonResponse.put("messageType", MessageEventEnum.GENERIC_ERROR.getCodeString());180 jsonResponse.put("message", MessageEventEnum.GENERIC_ERROR.getDescription().replace("%REASON%", ex.toString()));181 LOG.error("General Exception during testcase import.", ex);182 }183 } catch (JSONException e) {184 LOG.error("JSONException during testcase import.", e);185 //returns a default error message with the json format that is able to be parsed by the client-side186 httpServletResponse.setContentType("application/json");187 httpServletResponse.getWriter().print(AnswerUtil.createGenericErrorAnswer());188 }189 httpServletResponse.getWriter().print(jsonResponse.toString());190 }191 private TestCaseStepAction getActionFromSIDE(JSONObject command, Integer i, String masterSIDEURL, List<String> applicationURLs, String targetFolder, String targetTestcase) {192 TestCaseStepAction newAction = null;193 try {194 String action = null;195 String value1 = "";196 String value2 = "";197 String description = command.getString("comment");198 String cond = TestCaseStepAction.CONDITIONOPERATOR_ALWAYS;199 String commandS = command.getString("command");200 if (commandS.startsWith("//")) {201 cond = TestCaseStepAction.CONDITIONOPERATOR_NEVER;202 commandS = commandS.substring(2);203 }204 switch (commandS) {205 case "setWindowSize":206 case "mouseOut":207 // Those commands are ignored.208 break;209 case "open":210 LOG.debug(masterSIDEURL);211 LOG.debug(applicationURLs);212 value1 = masterSIDEURL + command.getString("target");213 if (!isURLInApplication(value1, applicationURLs)) {214 action = TestCaseStepAction.ACTION_OPENURL;215 } else {216 action = TestCaseStepAction.ACTION_OPENURLWITHBASE;217 value1 = command.getString("target");218 }219 break;220 case "type":221 action = TestCaseStepAction.ACTION_TYPE;222 value1 = convertElement(command);223 value2 = command.getString("value");224 break;225 case "click":226 action = TestCaseStepAction.ACTION_CLICK;227 value1 = convertElement(command);228 break;229 case "mouseDown":230 action = TestCaseStepAction.ACTION_MOUSELEFTBUTTONPRESS;231 value1 = convertElement(command);232 break;233 case "sendKeys":234 action = TestCaseStepAction.ACTION_KEYPRESS;235 value1 = convertElement(command);236 value2 = mappKey(command.getString("value"));237 break;238 case "mouseUp":239 action = TestCaseStepAction.ACTION_MOUSELEFTBUTTONRELEASE;240 value1 = convertElement(command);241 break;242 case "mouseOver":243 action = TestCaseStepAction.ACTION_MOUSEOVER;244 value1 = convertElement(command);245 break;246 default:247 action = TestCaseStepAction.ACTION_DONOTHING;248 description = "Unknow Selenium IDE command '" + commandS + "'";249 if (!StringUtil.isNullOrEmpty(command.getString("target"))) {250 description += " on target '" + convertElement(command) + "'";251 }252 if (!StringUtil.isNullOrEmpty(command.getString("value"))) {253 description += " with value '" + command.getString("value") + "'";254 }255 if (!StringUtil.isNullOrEmpty(command.getString("comment"))) {256 description += " - " + command.getString("comment");257 }258 }259 if (action != null) {260 newAction = testcaseStepActionFactory.create(targetFolder, targetTestcase, 1, i, i, TestCaseStepAction.CONDITIONOPERATOR_ALWAYS, "", "", "", new JSONArray(), action, value1, value2, "", new JSONArray(), false, description, null);261 }262 } catch (JSONException ex) {263 LOG.error(ex, ex);264 }265 return newAction;266 }267 private static String convertElement(JSONObject command) throws JSONException {268 String target = command.getString("target");269 if (target.startsWith("name=") || target.startsWith("xpath=") || target.startsWith("id=")) {270 return target;271 }272 JSONArray targets = command.getJSONArray("targets");273 for (int i = 0; i < targets.length(); i++) {274 if (targets.getJSONArray(i).getString(0).startsWith("xpath=")) {275 return targets.getJSONArray(i).getString(0);276 }277 }278 return target;279 }280 private static String mappKey(String key) throws JSONException {281 switch (key) {282 case "${KEY_ENTER}":283 return "ENTER";284 default:285 return key;286 }287 }288 private static boolean isURLInApplication(String url, List<String> appURLs) throws JSONException {289 String cleanedUrl = StringUtil.addSuffixIfNotAlready(StringUtil.removeProtocolFromHostURL(url), "/");290 for (String appURL : appURLs) {291 appURL = StringUtil.addSuffixIfNotAlready(StringUtil.removeProtocolFromHostURL(appURL), "/");292 LOG.debug(appURL + " - " + cleanedUrl);293 if (appURL.equalsIgnoreCase(cleanedUrl)) {294 return true;295 }296 }297 return false;298 }299 public static JSONObject parseJSONFile(String filename) throws JSONException, IOException {300 String content = new String(Files.readAllBytes(Paths.get(filename)));301 return new JSONObject(content);302 }303 // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">304 /**305 * Handles the HTTP <code>GET</code> method.306 *307 * @param request servlet request308 * @param response servlet response309 * @throws ServletException if a servlet-specific error occurs310 * @throws IOException if an I/O error occurs311 */312 @Override313 protected void doGet(HttpServletRequest request, HttpServletResponse response)314 throws ServletException, IOException {315 processRequest(request, response);316 }317 /**318 * Handles the HTTP <code>POST</code> method.319 *320 * @param request servlet request321 * @param response servlet response322 * @throws ServletException if a servlet-specific error occurs323 * @throws IOException if an I/O error occurs324 */325 @Override326 protected void doPost(HttpServletRequest request, HttpServletResponse response)327 throws ServletException, IOException {328 processRequest(request, response);329 }330 /**331 * Returns a short description of the servlet.332 *333 * @return a String containing servlet description334 */335 @Override336 public String getServletInfo() {337 return "Short description";338 }// </editor-fold>339 private List<String> getFiles(HttpServletRequest httpServletRequest) {340 List<String> result = new ArrayList<>();341 try {342 if (ServletFileUpload.isMultipartContent(httpServletRequest)) {...
processRequest
Using AI Code Generation
1import org.cerberus.servlet.crud.test.testcase.ImportTestCaseFromSIDE;2import org.cerberus.servlet.crud.test.testcase.ImportTestCaseFromSIDE;3import javax.servlet.http.HttpServletRequest;4import javax.servlet.http.HttpServletResponse;5import java.io.IOException;6import java.util.logging.Level;7import java.util.logging.Logger;8public class ImportTestCaseFromSIDEServlet extends HttpServlet {9 private static final Logger LOG = Logger.getLogger(ImportTestCaseFromSIDEServlet.class.getName());10 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {11 try {12 ImportTestCaseFromSIDE.processRequest(request, response);13 } catch (Exception ex) {14 LOG.log(Level.SEVERE, null, ex);15 }16 }17}
processRequest
Using AI Code Generation
1import org.cerberus.servlet.crud.test.testcase.ImportTestCaseFromSIDE;2import org.cerberus.servlet.crud.test.testcase.ImportTestCaseFromSIDE.ProcessRequest;3import org.cerberus.util.StringUtil;4import org.cerberus.util.answer.AnswerItem;5import org.cerberus.util.answer.AnswerList;6import org.cerberus.util.answer.AnswerUtil;7import org.cerberus.crud.entity.TestCase;8import org.cerberus.crud.entity.Test;9import org.cerberus.crud.service.ITestService;10import org.cerberus.crud.service.ITestCaseService;11import org.cerberus.engine.entity.MessageEvent;12import org.cerberus.engine.entity.MessageGeneral;13import org.cerberus.engine.entity.MessageEventEnum;14import org.cerberus.util.spring.AppContextProvider;15import javax.servlet.http.HttpServletRequest;16import javax.servlet.http.HttpServletResponse;17import javax.servlet.ServletContext;18import org.json.JSONObject;19import org.json.JSONArray;20import java.util.ArrayList;21import java.util.HashMap;22import java.util.List;23import java.util.Map;24import org.apache.logging.log4j.LogManager;25import org.apache.logging.log4j.Logger;26import java.io.File;27import java.io.FileInputStream;28import java.io.InputStream;29import org.apache.commons.fileupload.FileItem;30import org.apache.commons.fileupload.FileItemFactory;31import org.apache.commons.fileupload.disk.DiskFileItemFactory;32import org.apache.commons.fileupload.servlet.ServletFileUpload;33import org.apache.commons.fileupload.FileUploadException;34import java.io.IOException;35import java.lang.Exception;36import java.util.zip.ZipEntry;37import java.util.zip.ZipInputStream;38import java.util.zip.ZipException;39import org.cerberus.util.FileUtil;40import org.apache.commons.io.IOUtils;
processRequest
Using AI Code Generation
1package org.cerberus.servlet.crud.test.testcase;2import java.io.IOException;3import java.sql.SQLException;4import java.util.logging.Level;5import java.util.logging.Logger;6import javax.servlet.ServletException;7import javax.servlet.http.HttpServlet;8import javax.servlet.http.HttpServletRequest;9import javax.servlet.http.HttpServletResponse;10import org.apache.commons.lang3.exception.ExceptionUtils;11import org.cerberus.crud.entity.TestCase;12import org.cerberus.crud.factory.IFactoryTestCase;13import org.cerberus.crud.service.ITestCaseService;14import org.cerberus.crud.service.impl.TestCaseService;15import org.cerberus.engine.entity.MessageEvent;16import org.cerberus.engine.entity.MessageGeneral;17import org.cerberus.enums.MessageEventEnum;18import org.cerberus.exception.CerberusException;19import org.cerberus.factory.impl.FactoryTestCase;20import org.cerberus.log.MyLogger;21import org.cerberus.service.json.JsonService;22import org.cerberus.service.json.impl.JsonServiceDefault;23import org.cerberus.servlet.api.IApiCallService;24import org.cerberus.servlet.api.impl.ApiCallService;25import org.cerberus.util.answer.Answer;26import org.cerberus.util.answer.AnswerItem;27import org.json.JSONArray;28import org.json.JSONException;29import org.json.JSONObject;30import org.springframework.context.ApplicationContext;31import org.springframework.web.context.support.WebApplicationContextUtils;
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!