How to use getParams method of org.cerberus.servlet.crud.test.testcase.ImportTestCaseFromSIDE class

Best Cerberus-source code snippet using org.cerberus.servlet.crud.test.testcase.ImportTestCaseFromSIDE.getParams

Source:ImportTestCaseFromSIDE.java Github

copy

Full Screen

...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)) {343 DiskFileItemFactory factory = new DiskFileItemFactory();344 ServletContext servletContext = this.getServletConfig().getServletContext();345 File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");346 factory.setRepository(repository);347 ServletFileUpload upload = new ServletFileUpload(factory);348 List<FileItem> formItems = upload.parseRequest(httpServletRequest);349 if (formItems != null) {350 LOG.debug("Nb of Files to import : " + formItems.size());351 if (formItems.size() > 0) {352 int i = 1;353 for (FileItem item : formItems) {354 LOG.debug("File to import (" + i++ + ") : " + item.toString() + " FieldName : " + item.getFieldName() + " ContentType : " + item.getContentType());355 if (!item.isFormField()) {356 result.add(item.getString());357 }358 }359 }360 }361 }362 } catch (FileUploadException ex) {363 java.util.logging.Logger.getLogger(ImportTestCaseFromSIDE.class.getName()).log(Level.SEVERE, null, ex);364 }365 LOG.debug("result : " + result.size());366 return result;367 }368 private HashMap<String, String> getParams(HttpServletRequest httpServletRequest) {369 HashMap<String, String> result = new HashMap<>();370 try {371 if (ServletFileUpload.isMultipartContent(httpServletRequest)) {372 DiskFileItemFactory factory = new DiskFileItemFactory();373 ServletContext servletContext = this.getServletConfig().getServletContext();374 File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");375 factory.setRepository(repository);376 ServletFileUpload upload = new ServletFileUpload(factory);377 List<FileItem> formItems = upload.parseRequest(httpServletRequest);378 if (formItems != null) {379 LOG.debug("Nb of Param to import : " + formItems.size());380 if (formItems.size() > 0) {381 int i = 1;382 for (FileItem item : formItems) {...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Cerberus-source automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful