001package com.thed.zblast.parser;
002
003/**
004 * @author Mohan.Kumar
005 */
006
007import com.thed.model.AutomationJobDetail;
008import com.thed.model.AutomationScriptJobDTO;
009import com.thed.model.TestStep;
010import com.thed.model.TestStepDetail;
011import com.thed.util.ZeeConstants;
012import com.thed.zblast.parser.jaxb.junit.*;
013import com.thed.zblast.parser.model.TestcaseModel;
014import org.apache.commons.lang.StringUtils;
015import org.w3c.dom.*;
016
017import javax.xml.bind.JAXBContext;
018import javax.xml.bind.JAXBException;
019import javax.xml.bind.UnmarshalException;
020import javax.xml.bind.Unmarshaller;
021import javax.xml.parsers.DocumentBuilder;
022import javax.xml.parsers.DocumentBuilderFactory;
023import java.io.*;
024import java.net.URISyntaxException;
025import java.net.URLDecoder;
026import java.net.URLEncoder;
027import java.text.SimpleDateFormat;
028import java.util.*;
029import java.util.logging.Logger;
030import java.util.stream.Collectors;
031
032public class JUnitResultParser {
033
034    private static Logger logger = Logger.getLogger(JUnitResultParser.class.getName());
035
036        public static final String attachmentFileNamePrefix = "log_";
037        public static final String attachmentFileNamePassPrefix = "log_pass_";
038
039        private static final class XMLFilenameFilter implements FilenameFilter {
040                @Override
041                public boolean accept(File dir, String name) {
042                        if (name.endsWith(".xml") && !new File(name).isDirectory())
043                                return true;
044                        return false;
045                }
046        }
047
048        public static List<Testsuite> parseResults(String fileName) {
049                File file = new File(fileName);
050                List<Testsuite> testSuites = new ArrayList<>();
051                if (file.isDirectory()) {
052                        FilenameFilter nameFilter = new XMLFilenameFilter();
053                        String[] list = file.list(nameFilter);
054                        String absolutePath = file.getAbsolutePath();
055                        for (int i = 0; i < list.length; i++) {
056                                testSuites.addAll(getTestSuites(new File(absolutePath + File.separator + list[i])));
057                        }
058                } else {
059                        return getTestSuites(file);
060                }
061                return testSuites;
062        }
063
064        private static List<Testsuite> getTestSuites(File resultsfile) {
065                List<Testsuite> testsuiteList = new ArrayList<Testsuite>();
066                try {
067                        JAXBContext jaxbContext = JAXBContext.newInstance(Testsuites.class);
068                        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
069                        Object unmarshal = jaxbUnmarshaller.unmarshal(resultsfile);
070
071                        if (unmarshal instanceof Testsuite testsuite) {
072                                testsuite.setAttachmentFile(resultsfile.getAbsolutePath());
073                                testsuiteList.add(testsuite);
074
075                        } else if (unmarshal instanceof Testsuites testSuites) {
076                                for (Testsuite testsuite : testSuites.getTestsuite()) {
077                                        testsuite.setAttachmentFile(resultsfile.getAbsolutePath());
078                                }
079                                testsuiteList.addAll(testSuites.getTestsuite());
080                                testSuites.getTestsuite().size();
081                        } else {
082                                System.out.println("XML is not a valid report file");
083                        }
084                } catch (UnmarshalException e) {
085                        System.out.println(e.getMessage());
086                } catch (JAXBException e) {
087                        e.printStackTrace();
088                } catch (Exception e) {
089                        e.printStackTrace();
090                }
091
092                return testsuiteList;
093        }
094
095        public static List<TestcaseModel> getTestsFromTestSuiteList(List<Testsuite> testSuites,  AutomationJobDetail automationJob) throws Exception{
096                List<TestcaseModel> testcases=new LinkedList<>();
097        String eggPlantFramework = "eggplant";
098        String testNGFramework = "testng";
099        Boolean attachmentSuccessJunit  = true;
100                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
101                String date = sdf.format(new Date());
102        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
103        dbf.setValidating(false);
104        DocumentBuilder db = dbf.newDocumentBuilder();
105        Document doc = null;
106        NodeList testsuiteEntries =null;
107        // This index is for to map XML element with testsuite
108        int testSuiteIndex=0;
109        if (automationJob.getAutomationFramework().equalsIgnoreCase(eggPlantFramework)) {
110            attachmentSuccessJunit = false;
111        }
112        if (automationJob.getAutomationFramework().equalsIgnoreCase(testNGFramework)) {
113            attachmentSuccessJunit = false;
114        }
115        String xmlFilename ="";
116                for (Testsuite testsuite : testSuites) {
117            if(attachmentSuccessJunit){
118                if(!xmlFilename.equals(testsuite.getAttachmentFile())){
119                    testSuiteIndex =0;
120                }
121                doc = db.parse(new FileInputStream(testsuite.getAttachmentFile()));
122                if(doc!=null){
123                    testsuiteEntries = doc.getElementsByTagName("testsuite");
124                }
125            }
126            xmlFilename = testsuite.getAttachmentFile();
127            // This index is for to map XML element with Testcase for pass
128            int testCaseIndex=0;
129                        List<Testcase> testcaseList = testsuite.getTestcase();
130                        for (Testcase testcase : testcaseList) {
131
132                                List<File> attachments=new ArrayList<File>();
133                List<File> testCaseAttachments=new ArrayList<File>();
134                List<String> parsedRequirements=new ArrayList<String>();
135                                TestcaseModel tc = new TestcaseModel();
136                                boolean value = true;
137                                String failLog=null;
138                StringBuffer successLog=new StringBuffer();
139                                //sending package name alog with testcase name. TO be removed in next MVP
140                                String name = testcase.getName().substring(testcase.getName().lastIndexOf("\\")+1,testcase.getName().length());
141                                if(testcase.getClassname()!=null && !testcase.getClassname().isEmpty() && automationJob.getCreatePackage()){
142                                        tc.setPackageName(testcase.getClassname());
143                                        name=testcase.getClassname()+"."+name;
144                                }
145                                String status = testcase.getStatus();
146
147                                if (status == null) {
148                                        List<Failure> failureList = testcase.getFailure();
149                                        String errors=testcase.getErrors();
150                                        if ((failureList != null && failureList.size() > 0)
151                                                        || (errors!=null && Integer.parseInt(errors) >0)) {
152                                                status = "fail";
153                                                tc.setTestStatus("false");
154                                        } else {
155                                                status = "pass";
156                                                tc.setTestStatus("true");
157                                        }
158                                }else {
159                                        if (status.equalsIgnoreCase("pass")) {
160                                                status = "pass";
161                                                tc.setTestStatus("true");
162                                        } else {
163                                                status = "fail";
164                                                tc.setTestStatus("false");
165                                        }
166
167                                }
168
169
170                                tc.setClassName(testcase.getClassname());
171                                tc.setTcName(testcase.getName());
172
173                                if(((testcase.getSystemOut() !=null && !testcase.getSystemOut().isEmpty()) ||
174                                                (testcase.getSkipped()!=null && !testcase.getSkipped().isEmpty())  ||
175                                                testcase.getFailure()!=null && !testcase.getFailure().isEmpty()) &&
176                                                automationJob.getAutomationFramework().equalsIgnoreCase(ZeeConstants.CUCUMBER)) {
177                                        tc.setTestStep(getTestSteps(testcase));
178                                }
179
180                                tc.setTestcaseName(name);
181
182                                if((testcase.getFailure() != null && testcase.getFailure().size() > 0 )){
183                                        failLog=testcase.getFailure().get(0).getContent();
184                                        if(failLog==null || failLog.isEmpty()) {
185                                                failLog=testcase.getFailure().get(0).getContent();
186                                        }
187                                }else if(testcase.getError()!=null && testcase.getError().size()>0) {
188                                        failLog=testcase.getError().get(0).getMessage();
189                                        if(failLog==null || failLog.isEmpty()) {
190                                                failLog=testcase.getError().get(0).getContent();
191                                        }
192                                }
193                                if(automationJob.getAutomationFramework().equalsIgnoreCase(ZeeConstants.UFT)) {
194                                        failLog=failLog+testcase.getSystemOut().get(0);
195                                }
196
197                                if(failLog!=null && !failLog.isEmpty()) {
198                                if (status.equalsIgnoreCase("fail")) {
199                                        value = false;
200                                        File location = null;
201                                        try {
202                                                location = new File(JUnitResultParser.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile().getParentFile();
203                                        } catch (URISyntaxException e1) {
204                                                // TODO Auto-generated catch block
205                                                e1.printStackTrace();
206                                        }
207                                        File dir = new File(location+"\\attachments");
208                                        dir.mkdirs();
209                                        if(!failLog.isEmpty()) {
210                                                File tmp = new File(dir, attachmentFileNamePrefix+removeIllegalCharactersAndTrimLength(name)+"_"+testCaseIndex+"_"+date+".txt");
211
212                                                try {
213                                                        tmp.createNewFile();
214                                                        PrintWriter writer = new PrintWriter(tmp.getAbsoluteFile(), "UTF-8");
215                                                        writer.println(failLog);
216                                                        writer.close();
217                                                } catch (IOException e) {
218                                                        // TODO Auto-generated catch block
219                                                        e.printStackTrace();
220                                                }
221                                                attachments.add(tmp);
222                                                tc.setAttachement(attachments);
223                                        }
224                                }
225                                }
226                if (attachmentSuccessJunit){
227                    if (status.equalsIgnoreCase("pass")) {
228                        if(testsuiteEntries!=null){
229                            try {
230                                Element testCaseListNode = (Element) testsuiteEntries.item(testSuiteIndex);
231                                NodeList testcaseEntries = testCaseListNode.getElementsByTagName("testcase");
232                                Element testCaseNode = (Element) testcaseEntries.item(testCaseIndex);
233                                NamedNodeMap attributes = testCaseNode.getAttributes();
234                                int numAttrs = attributes.getLength();
235                                for (int k = 0; k < numAttrs; k++) {
236                                    Attr attr = (Attr) attributes.item(k);
237                                    successLog.append(attr.getNodeName() + ":" + attr.getNodeValue());
238                                    successLog.append(System.getProperty("line.separator"));
239                                }
240                            }catch (Exception ex) {
241                                ex.printStackTrace();
242                            }
243                            File location = null;
244                            try {
245                                location = new File(JUnitResultParser.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile().getParentFile();
246                            } catch (URISyntaxException e1) {
247                                // TODO Auto-generated catch block
248                                e1.printStackTrace();
249                            }
250                            File dir = new File(location+"\\attachments");
251                            dir.mkdirs();
252                            if(successLog.length()>0) {
253                                File tmp = new File(dir, attachmentFileNamePassPrefix+removeIllegalCharactersAndTrimLength(name)+"_"+testCaseIndex+"_"+date+".txt");
254
255                                try {
256                                    tmp.createNewFile();
257                                    PrintWriter writer = new PrintWriter(tmp.getAbsoluteFile(), "UTF-8");
258                                    writer.println(successLog);
259                                    writer.close();
260                                } catch (IOException e) {
261                                    // TODO Auto-generated catch block
262                                    e.printStackTrace();
263                                }
264                                attachments.add(tmp);
265                                tc.setAttachement(attachments);
266                            }
267                        }
268                    }
269                }
270        // Attachment for eggplant
271                                if (automationJob.getAutomationFramework().equalsIgnoreCase(eggPlantFramework)) {
272                                        String path = testsuite.getAttachmentFile();
273                                        File errorFile = new File(path);
274                                        File parentDir = errorFile.getParentFile();
275                                        if (parentDir.isDirectory()) {
276                                                File contents = Arrays.stream(parentDir.listFiles()).filter(f -> f.getName().endsWith(".png"))
277                                                                .findAny().orElse(null);
278                        if(contents!=null){
279                            attachments.add(contents);
280                        }
281                                                File logFile=Arrays.stream(parentDir.listFiles()).filter(f -> f.getName().equals("LogFile.txt"))
282                                                                .findAny().orElse(null);
283                        if(logFile!=null){
284                            attachments.add(logFile);
285                        }
286                                                tc.setAttachement(attachments);
287                                        }
288                                }
289                //For testcase attachment
290                if(testcase.getAttachments()!=null){
291                    for (Attachment testcaseAttachment : testcase.getAttachments().getAttachment()){
292                        File tmpTestCaseAttachment = new File(testcaseAttachment.getContent());
293                        testCaseAttachments.add(tmpTestCaseAttachment);
294                    }
295                }
296                tc.setTestcaseAttachement(testCaseAttachments);
297                //For testcase Requirements
298                if(testcase.getRequirements()!=null){
299                    for (Requirement requirement : testcase.getRequirements().getRequirement()){
300                        String parsedRequirement = requirement.getContent();
301                        parsedRequirements.add(parsedRequirement);
302                    }
303                }
304                tc.setRequirements(parsedRequirements);
305
306                testcases.add(tc);
307                testCaseIndex = testCaseIndex+1;
308                        }
309            testSuiteIndex = testSuiteIndex+1;
310                }
311                return testcases;
312        }
313
314        public static List<TestcaseModel> getTestsFromTestSuiteListFromGenericParser(List<Testsuite> testSuites,  AutomationJobDetail automationJob) throws Exception{
315                //Map<String,TestcaseModel> testcases=new LinkedHashMap<>();
316                List<TestcaseModel> testcases=new LinkedList<>();
317        String eggPlantFramework = "eggplant";
318        String testNGFramework = "testng";
319        Boolean attachmentSuccessJunit  = true;
320                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
321                String date = sdf.format(new Date());
322        int testSuiteIndex=0;
323        if (automationJob.getAutomationFramework().equalsIgnoreCase(eggPlantFramework)) {
324            attachmentSuccessJunit = false;
325        }
326        if (automationJob.getAutomationFramework().equalsIgnoreCase(testNGFramework)) {
327            attachmentSuccessJunit = false;
328        }
329                for (Testsuite testsuite : testSuites) {
330            // This index is for to map XML element with Testcase for pass
331            int testCaseIndex=0;
332                        List<Testcase> testcaseList = testsuite.getTestcase();
333                        for (Testcase testcase : testcaseList) {
334
335                                List<File> attachments=new ArrayList<File>();
336                List<File> testCaseAttachments=new ArrayList<File>();
337                List<String> parsedRequirements=new ArrayList<String>();
338                                TestcaseModel tc = new TestcaseModel();
339                                boolean value = true;
340                                String failLog=null;
341                StringBuffer successLog=new StringBuffer();
342                                //sending package name alog with testcase name. TO be removed in next MVP
343                                String name = testcase.getName();
344                                if(testcase.getClassname()!=null && !testcase.getClassname().isEmpty() && automationJob.getCreatePackage()){
345                                        tc.setPackageName(testcase.getClassname());
346                                }
347                if(name!=null && name.length() >= ZeeConstants.CYCLE_NAME_LIMIT) {
348                    name = name.substring(0, (ZeeConstants.CYCLE_NAME_LIMIT-1));
349                }
350
351                                String status = "";
352                                tc.setExecutionRequest(testcase.getExecutionRequest());
353
354                                tc.setClassName(testcase.getClassname());
355                                tc.setTcName(testcase.getName());
356
357                                if(((testcase.getSystemOut() !=null && !testcase.getSystemOut().isEmpty()) ||
358                                                (testcase.getSkipped()!=null && !testcase.getSkipped().isEmpty())  ||
359                                                testcase.getFailure()!=null && !testcase.getFailure().isEmpty())) {
360                                        tc.setTestStep(getTestStepsFromGenericParser(testcase));
361                                }
362
363                                tc.setTestcaseName(name);
364                                tc.setTestcaseTag(testcase.getTag());
365                                if(testcase.getStatusFailAttachment()!=null && !testcase.getStatusFailAttachment().isEmpty()){
366                                        failLog=testcase.getStatusFailAttachment();
367                                }
368
369                                if(StringUtils.isNotEmpty(testcase.getStatusAttachment())) {
370                                        File location = null;
371                                        try {
372                                                location = new File(JUnitResultParser.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile().getParentFile();
373                                        } catch (URISyntaxException e1) {
374                                                // TODO Auto-generated catch block
375                                                e1.printStackTrace();
376                                        }
377                                        File dir = new File(location+"\\attachments");
378                                        dir.mkdirs();
379
380                                        File tmp = new File(dir, attachmentFileNamePrefix+removeIllegalCharactersAndTrimLength(name)+"_"+testCaseIndex+"_"+date+".txt");
381
382                                        try {
383                                                tmp.createNewFile();
384                                                PrintWriter writer = new PrintWriter(tmp.getAbsoluteFile(), "UTF-8");
385                                                writer.println(testcase.getStatusAttachment());
386                                                writer.close();
387                                        } catch (IOException e) {
388                                                // TODO Auto-generated catch block
389                                                e.printStackTrace();
390                                        }
391                                        attachments.add(tmp);
392                                        tc.setAttachement(attachments);
393                                }
394
395                                if(failLog!=null && !failLog.isEmpty()) {
396                                if (status.equalsIgnoreCase("fail")) {
397                                        value = false;
398                                        File location = null;
399                                        try {
400                                                location = new File(JUnitResultParser.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile().getParentFile();
401                                        } catch (URISyntaxException e1) {
402                                                // TODO Auto-generated catch block
403                                                e1.printStackTrace();
404                                        }
405                                        File dir = new File(location+"\\attachments");
406                                        dir.mkdirs();
407                                        if(!failLog.isEmpty()) {
408                                                File tmp = new File(dir, attachmentFileNamePrefix+removeIllegalCharactersAndTrimLength(name)+"_"+testCaseIndex+"_"+date+".txt");
409
410                                                try {
411                                                        tmp.createNewFile();
412                                                        PrintWriter writer = new PrintWriter(tmp.getAbsoluteFile(), "UTF-8");
413                                                        writer.println(failLog);
414                                                        writer.close();
415                                                } catch (IOException e) {
416                                                        // TODO Auto-generated catch block
417                                                        e.printStackTrace();
418                                                }
419                                                attachments.add(tmp);
420                                                tc.setAttachement(attachments);
421                                        }
422                                }
423                                }
424                if (attachmentSuccessJunit){
425                    if (status.equalsIgnoreCase("pass")) {
426
427                            try {
428                                                                successLog.append(testcase.getStatusPassAttachment());
429                            }catch (Exception ex) {
430                                ex.printStackTrace();
431                            }
432                            File location = null;
433                            try {
434                                location = new File(JUnitResultParser.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile().getParentFile();
435                            } catch (URISyntaxException e1) {
436                                // TODO Auto-generated catch block
437                                e1.printStackTrace();
438                            }
439                            File dir = new File(location+File.separator+"attachments");
440                            if(!dir.exists()){
441                                                                dir.mkdirs();
442                                                        }
443                            if(successLog.length()>0) {
444                                String fileName= URLEncoder.encode(name, "utf-8");
445                                File tmp = new File(dir, attachmentFileNamePassPrefix+removeIllegalCharactersAndTrimLength(fileName)+"_"+testCaseIndex+"_"+date+".txt");
446
447                                try {
448                                    tmp.createNewFile();
449                                    PrintWriter writer = new PrintWriter(tmp.getAbsoluteFile(), "UTF-8");
450                                    writer.println(successLog);
451                                    writer.close();
452                                } catch (IOException e) {
453                                    // TODO Auto-generated catch block
454                                    e.printStackTrace();
455                                }
456                                attachments.add(tmp);
457                                tc.setAttachement(attachments);
458                            }
459                    }
460                }
461        // Attachment for eggplant
462                                if (automationJob.getAutomationFramework().equalsIgnoreCase(eggPlantFramework)) {
463                                        String path = testsuite.getAttachmentFile();
464                                        File errorFile = new File(path);
465                                        File parentDir = errorFile.getParentFile();
466                                        if (parentDir.isDirectory()) {
467                                                File contents = Arrays.stream(parentDir.listFiles()).filter(f -> f.getName().endsWith(".png"))
468                                                                .findAny().orElse(null);
469                        if(contents!=null){
470                            attachments.add(contents);
471                        }
472                                                File logFile=Arrays.stream(parentDir.listFiles()).filter(f -> f.getName().equals("LogFile.txt"))
473                                                                .findAny().orElse(null);
474                        if(logFile!=null){
475                            attachments.add(logFile);
476                        }
477                                                tc.setAttachement(attachments);
478                                        }
479                                }
480                //For testcase attachment
481
482                if(testcase.getAttachmentList()!=null && !testcase.getAttachmentList().isEmpty()){
483                    for (String testcaseAttachment : testcase.getAttachmentList()){
484                        File tmpTestCaseAttachment = new File(testcaseAttachment);
485                        testCaseAttachments.add(tmpTestCaseAttachment);
486                    }
487                }
488                tc.setTestcaseAttachement(testCaseAttachments);
489                //For testcase Requirements
490
491                if(testcase.getRequirementIds()!=null && !testcase.getRequirementIds().isEmpty()) {
492                                        for (String requirementId : testcase.getRequirementIds()) {
493                                                parsedRequirements.add(requirementId);
494                                        }
495                                }
496
497                tc.setRequirements(parsedRequirements);
498
499                testcases.add(tc);
500                testCaseIndex = testCaseIndex+1;
501                        }
502            testSuiteIndex = testSuiteIndex+1;
503                }
504                return testcases;
505        }
506
507
508    public static List<TestcaseModel> getTestsFromScriptJobTestSuiteList(List<Testsuite> testSuites,  AutomationScriptJobDTO automationScriptJobDTO) throws Exception{
509        List<TestcaseModel> testcases=new LinkedList<>();
510        String eggPlantFramework = "eggplant";
511        String testNGFramework = "testng";
512        Boolean attachmentSuccessJunit  = true;
513        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
514        String date = sdf.format(new Date());
515        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
516        dbf.setValidating(false);
517        DocumentBuilder db = dbf.newDocumentBuilder();
518        Document doc = null;
519        NodeList testsuiteEntries =null;
520        // This index is for to map XML element with testsuite
521        int testSuiteIndex=0;
522        if (automationScriptJobDTO.getAutomationFramework().equalsIgnoreCase(eggPlantFramework)) {
523            attachmentSuccessJunit = false;
524        }
525        if (automationScriptJobDTO.getAutomationFramework().equalsIgnoreCase(testNGFramework)) {
526            attachmentSuccessJunit = false;
527        }
528        String xmlFilename ="";
529        for (Testsuite testsuite : testSuites) {
530            if(attachmentSuccessJunit){
531                if(!xmlFilename.equals(testsuite.getAttachmentFile())){
532                    testSuiteIndex =0;
533                }
534                doc = db.parse(new FileInputStream(testsuite.getAttachmentFile()));
535                if(doc!=null){
536                    testsuiteEntries = doc.getElementsByTagName("testsuite");
537                }
538            }
539            xmlFilename = testsuite.getAttachmentFile();
540            // This index is for to map XML element with Testcase for pass
541            int testCaseIndex=0;
542            List<Testcase> testcaseList = testsuite.getTestcase();
543            for (Testcase testcase : testcaseList) {
544
545                List<File> attachments=new ArrayList<File>();
546                List<File> testCaseAttachments=new ArrayList<File>();
547                List<String> parsedRequirements=new ArrayList<String>();
548                TestcaseModel tc = new TestcaseModel();
549                boolean value = true;
550                String failLog=null;
551                StringBuffer successLog=new StringBuffer();
552                //sending package name alog with testcase name. TO be removed in next MVP
553                String name = testcase.getName().substring(testcase.getName().lastIndexOf("\\")+1,testcase.getName().length());
554                String status = testcase.getStatus();
555
556                if (status == null) {
557                    List<Failure> failureList = testcase.getFailure();
558                    String errors=testcase.getErrors();
559                    if ((failureList != null && failureList.size() > 0)
560                            || (errors!=null && Integer.parseInt(errors) >0)) {
561                        status = "fail";
562                        tc.setTestStatus("false");
563                    } else {
564                        status = "pass";
565                        tc.setTestStatus("true");
566                    }
567                }else {
568                    if (status.equalsIgnoreCase("pass")) {
569                        status = "pass";
570                        tc.setTestStatus("true");
571                    } else {
572                        status = "fail";
573                        tc.setTestStatus("false");
574                    }
575
576                }
577
578
579                tc.setClassName(testcase.getClassname());
580                tc.setTcName(testcase.getName());
581
582                if(((testcase.getSystemOut() !=null && !testcase.getSystemOut().isEmpty()) ||
583                        (testcase.getSkipped()!=null && !testcase.getSkipped().isEmpty())  ||
584                        testcase.getFailure()!=null && !testcase.getFailure().isEmpty()) &&
585                        automationScriptJobDTO.getAutomationFramework().equalsIgnoreCase(ZeeConstants.CUCUMBER)) {
586                    tc.setTestStep(getTestSteps(testcase));
587                }
588
589                tc.setTestcaseName(name);
590
591                if((testcase.getFailure() != null && testcase.getFailure().size() > 0 )){
592                    failLog=testcase.getFailure().get(0).getContent();
593                    if(failLog==null || failLog.isEmpty()) {
594                        failLog=testcase.getFailure().get(0).getContent();
595                    }
596                }else if(testcase.getError()!=null && testcase.getError().size()>0) {
597                    failLog=testcase.getError().get(0).getMessage();
598                    if(failLog==null || failLog.isEmpty()) {
599                        failLog=testcase.getError().get(0).getContent();
600                    }
601                }
602                if(automationScriptJobDTO.getAutomationFramework().equalsIgnoreCase(ZeeConstants.UFT)) {
603                    failLog=failLog+testcase.getSystemOut().get(0);
604                }
605
606                if(failLog!=null && !failLog.isEmpty()) {
607                    if (status.equalsIgnoreCase("fail")) {
608                        value = false;
609                        File location = null;
610                        try {
611                            location = new File(JUnitResultParser.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile().getParentFile();
612                        } catch (URISyntaxException e1) {
613                            // TODO Auto-generated catch block
614                            e1.printStackTrace();
615                        }
616                        File dir = new File(location+"\\attachments");
617                        dir.mkdirs();
618                        if(!failLog.isEmpty()) {
619                            File tmp = new File(dir, attachmentFileNamePrefix+removeIllegalCharactersAndTrimLength(name)+"_"+testCaseIndex+"_"+date+".txt");
620
621                            try {
622                                tmp.createNewFile();
623                                PrintWriter writer = new PrintWriter(tmp.getAbsoluteFile(), "UTF-8");
624                                writer.println(failLog);
625                                writer.close();
626                            } catch (IOException e) {
627                                // TODO Auto-generated catch block
628                                e.printStackTrace();
629                            }
630                            attachments.add(tmp);
631                            tc.setAttachement(attachments);
632                        }
633                    }
634                }
635                if (attachmentSuccessJunit){
636                    if (status.equalsIgnoreCase("pass")) {
637                        if(testsuiteEntries!=null){
638                            try {
639                                Element testCaseListNode = (Element) testsuiteEntries.item(testSuiteIndex);
640                                NodeList testcaseEntries = testCaseListNode.getElementsByTagName("testcase");
641                                Element testCaseNode = (Element) testcaseEntries.item(testCaseIndex);
642                                NamedNodeMap attributes = testCaseNode.getAttributes();
643                                int numAttrs = attributes.getLength();
644                                for (int k = 0; k < numAttrs; k++) {
645                                    Attr attr = (Attr) attributes.item(k);
646                                    successLog.append(attr.getNodeName() + ":" + attr.getNodeValue());
647                                    successLog.append(System.getProperty("line.separator"));
648                                }
649                            }catch (Exception ex) {
650                                ex.printStackTrace();
651                            }
652                            File location = null;
653                            try {
654                                location = new File(JUnitResultParser.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile().getParentFile();
655                            } catch (URISyntaxException e1) {
656                                // TODO Auto-generated catch block
657                                e1.printStackTrace();
658                            }
659                            File dir = new File(location+"\\attachments");
660                            dir.mkdirs();
661                            if(successLog.length()>0) {
662                                File tmp = new File(dir, attachmentFileNamePassPrefix+removeIllegalCharactersAndTrimLength(name)+"_"+testCaseIndex+"_"+date+".txt");
663
664                                try {
665                                    tmp.createNewFile();
666                                    PrintWriter writer = new PrintWriter(tmp.getAbsoluteFile(), "UTF-8");
667                                    writer.println(successLog);
668                                    writer.close();
669                                } catch (IOException e) {
670                                    // TODO Auto-generated catch block
671                                    e.printStackTrace();
672                                }
673                                attachments.add(tmp);
674                                tc.setAttachement(attachments);
675                            }
676                        }
677                    }
678                }
679                // Attachment for eggplant
680                if (automationScriptJobDTO.getAutomationFramework().equalsIgnoreCase(eggPlantFramework)) {
681                    String path = testsuite.getAttachmentFile();
682                    File errorFile = new File(path);
683                    File parentDir = errorFile.getParentFile();
684                    if (parentDir.isDirectory()) {
685                        File contents = Arrays.stream(parentDir.listFiles()).filter(f -> f.getName().endsWith(".png"))
686                                .findAny().orElse(null);
687                        if(contents!=null){
688                            attachments.add(contents);
689                        }
690                        File logFile=Arrays.stream(parentDir.listFiles()).filter(f -> f.getName().equals("LogFile.txt"))
691                                .findAny().orElse(null);
692                        if(logFile!=null){
693                            attachments.add(logFile);
694                        }
695                        tc.setAttachement(attachments);
696                    }
697                }
698                //For testcase attachment
699                if(testcase.getAttachments()!=null){
700                    for (Attachment testcaseAttachment : testcase.getAttachments().getAttachment()){
701                        File tmpTestCaseAttachment = new File(testcaseAttachment.getContent());
702                        testCaseAttachments.add(tmpTestCaseAttachment);
703                    }
704                }
705                tc.setTestcaseAttachement(testCaseAttachments);
706                //For testcase Requirements
707                if(testcase.getRequirements()!=null){
708                    for (Requirement requirement : testcase.getRequirements().getRequirement()){
709                        String parsedRequirement = requirement.getContent();
710                        parsedRequirements.add(parsedRequirement);
711                    }
712                }
713                tc.setRequirements(parsedRequirements);
714
715                testcases.add(tc);
716                testCaseIndex = testCaseIndex+1;
717            }
718            testSuiteIndex = testSuiteIndex+1;
719        }
720        return testcases;
721    }
722
723    public static List<TestcaseModel> getTestsFromTestSuiteListFromScriptJobGenericParser(List<Testsuite> testSuites,  AutomationScriptJobDTO automationScriptJobDTO) throws Exception{
724        List<TestcaseModel> testcases=new LinkedList<>();
725        String eggPlantFramework = "eggplant";
726        String testNGFramework = "testng";
727        Boolean attachmentSuccessJunit  = true;
728        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
729        String date = sdf.format(new Date());
730        int testSuiteIndex=0;
731        if (automationScriptJobDTO.getAutomationFramework().equalsIgnoreCase(eggPlantFramework)) {
732            attachmentSuccessJunit = false;
733        }
734        if (automationScriptJobDTO.getAutomationFramework().equalsIgnoreCase(testNGFramework)) {
735            attachmentSuccessJunit = false;
736        }
737        for (Testsuite testsuite : testSuites) {
738            // This index is for to map XML element with Testcase for pass
739            int testCaseIndex=0;
740            List<Testcase> testcaseList = testsuite.getTestcase();
741            for (Testcase testcase : testcaseList) {
742
743                List<File> attachments=new ArrayList<File>();
744                List<File> testCaseAttachments=new ArrayList<File>();
745                List<String> parsedRequirements=new ArrayList<String>();
746                TestcaseModel tc = new TestcaseModel();
747                boolean value = true;
748                String failLog=null;
749                StringBuffer successLog=new StringBuffer();
750                //sending package name alog with testcase name. TO be removed in next MVP
751                String name = testcase.getName().substring(testcase.getName().lastIndexOf("\\")+1,testcase.getName().length());
752                String status = "";
753                tc.setExecutionRequest(testcase.getExecutionRequest());
754
755                tc.setClassName(testcase.getClassname());
756                tc.setTcName(testcase.getName());
757
758                if(((testcase.getSystemOut() !=null && !testcase.getSystemOut().isEmpty()) ||
759                        (testcase.getSkipped()!=null && !testcase.getSkipped().isEmpty())  ||
760                        testcase.getFailure()!=null && !testcase.getFailure().isEmpty())) {
761                    tc.setTestStep(getTestStepsFromGenericParser(testcase));
762                }
763
764                tc.setTestcaseName(name);
765                tc.setTestcaseTag(testcase.getTag());
766                if(testcase.getStatusFailAttachment()!=null && !testcase.getStatusFailAttachment().isEmpty()){
767                    failLog=testcase.getStatusFailAttachment();
768                }
769
770                if(StringUtils.isNotEmpty(testcase.getStatusAttachment())) {
771                    File location = null;
772                    try {
773                        location = new File(JUnitResultParser.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile().getParentFile();
774                    } catch (URISyntaxException e1) {
775                        // TODO Auto-generated catch block
776                        e1.printStackTrace();
777                    }
778                    File dir = new File(location+"\\attachments");
779                    dir.mkdirs();
780
781                    File tmp = new File(dir, attachmentFileNamePrefix+removeIllegalCharactersAndTrimLength(name)+"_"+testCaseIndex+"_"+date+".txt");
782
783                    try {
784                        tmp.createNewFile();
785                        PrintWriter writer = new PrintWriter(tmp.getAbsoluteFile(), "UTF-8");
786                        writer.println(testcase.getStatusAttachment());
787                        writer.close();
788                    } catch (IOException e) {
789                        // TODO Auto-generated catch block
790                        e.printStackTrace();
791                    }
792                    attachments.add(tmp);
793                    tc.setAttachement(attachments);
794                }
795
796                if(failLog!=null && !failLog.isEmpty()) {
797                    if (status.equalsIgnoreCase("fail")) {
798                        value = false;
799                        File location = null;
800                        try {
801                            location = new File(JUnitResultParser.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile().getParentFile();
802                        } catch (URISyntaxException e1) {
803                            // TODO Auto-generated catch block
804                            e1.printStackTrace();
805                        }
806                        File dir = new File(location+"\\attachments");
807                        dir.mkdirs();
808                        if(!failLog.isEmpty()) {
809                            File tmp = new File(dir, attachmentFileNamePrefix+removeIllegalCharactersAndTrimLength(name)+"_"+testCaseIndex+"_"+date+".txt");
810
811                            try {
812                                tmp.createNewFile();
813                                PrintWriter writer = new PrintWriter(tmp.getAbsoluteFile(), "UTF-8");
814                                writer.println(failLog);
815                                writer.close();
816                            } catch (IOException e) {
817                                // TODO Auto-generated catch block
818                                e.printStackTrace();
819                            }
820                            attachments.add(tmp);
821                            tc.setAttachement(attachments);
822                        }
823                    }
824                }
825                if (attachmentSuccessJunit){
826                    if (status.equalsIgnoreCase("pass")) {
827
828                        try {
829                            successLog.append(testcase.getStatusPassAttachment());
830                        }catch (Exception ex) {
831                            ex.printStackTrace();
832                        }
833                        File location = null;
834                        try {
835                            location = new File(JUnitResultParser.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile().getParentFile();
836                        } catch (URISyntaxException e1) {
837                            // TODO Auto-generated catch block
838                            e1.printStackTrace();
839                        }
840                        File dir = new File(location+File.separator+"attachments");
841                        if(!dir.exists()){
842                            dir.mkdirs();
843                        }
844                        if(successLog.length()>0) {
845                            String fileName= URLEncoder.encode(name, "utf-8");
846                            File tmp = new File(dir, attachmentFileNamePassPrefix+removeIllegalCharactersAndTrimLength(fileName)+"_"+testCaseIndex+"_"+date+".txt");
847
848                            try {
849                                tmp.createNewFile();
850                                PrintWriter writer = new PrintWriter(tmp.getAbsoluteFile(), "UTF-8");
851                                writer.println(successLog);
852                                writer.close();
853                            } catch (IOException e) {
854                                // TODO Auto-generated catch block
855                                e.printStackTrace();
856                            }
857                            attachments.add(tmp);
858                            tc.setAttachement(attachments);
859                        }
860                    }
861                }
862                // Attachment for eggplant
863                if (automationScriptJobDTO.getAutomationFramework().equalsIgnoreCase(eggPlantFramework)) {
864                    String path = testsuite.getAttachmentFile();
865                    File errorFile = new File(path);
866                    File parentDir = errorFile.getParentFile();
867                    if (parentDir.isDirectory()) {
868                        File contents = Arrays.stream(parentDir.listFiles()).filter(f -> f.getName().endsWith(".png"))
869                                .findAny().orElse(null);
870                        if(contents!=null){
871                            attachments.add(contents);
872                        }
873                        File logFile=Arrays.stream(parentDir.listFiles()).filter(f -> f.getName().equals("LogFile.txt"))
874                                .findAny().orElse(null);
875                        if(logFile!=null){
876                            attachments.add(logFile);
877                        }
878                        tc.setAttachement(attachments);
879                    }
880                }
881                //For testcase attachment
882
883                if(testcase.getAttachmentList()!=null && !testcase.getAttachmentList().isEmpty()){
884                    for (String testcaseAttachment : testcase.getAttachmentList()){
885                        File tmpTestCaseAttachment = new File(testcaseAttachment);
886                        testCaseAttachments.add(tmpTestCaseAttachment);
887                    }
888                }
889                tc.setTestcaseAttachement(testCaseAttachments);
890                //For testcase Requirements
891
892                if(testcase.getRequirementIds()!=null && !testcase.getRequirementIds().isEmpty()) {
893                    for (String requirementId : testcase.getRequirementIds()) {
894                        parsedRequirements.add(requirementId);
895                    }
896                }
897
898                tc.setRequirements(parsedRequirements);
899
900                testcases.add(tc);
901                testCaseIndex = testCaseIndex+1;
902            }
903            testSuiteIndex = testSuiteIndex+1;
904        }
905        return testcases;
906    }
907        
908        private static TestStep getTestSteps(Testcase testcase) {
909                List<String> stepList=(testcase.getSystemOut().size()>0?testcase.getSystemOut():new ArrayList<>());
910                if(stepList.isEmpty()) {
911                        stepList.add(testcase.getSkipped()==null?testcase.getFailure().get(0).getContent():testcase.getSkipped());
912                }
913                TestStep testStep=getTestStpesFromTestcase(stepList);
914                return testStep;
915        }
916
917        private static TestStep getTestStepsFromGenericParser(Testcase testcase) {
918                String stepList=(testcase.getSystemOut().size()>0?testcase.getSystemOut().get(0):"");
919                TestStep testStep=getTestStpesFromTestcase(Arrays.asList(stepList));
920                return testStep;
921        }
922
923        private static TestStep getTestStpesFromTestcase(List<String> stepList) {
924                String[] keyWords={"And","Or","Given","When","Then"};
925                List<String> keywordsList= Arrays.stream(keyWords).collect(Collectors.toList());
926                TestStep testStep=null;
927                String status="";
928                for(String testSteps:stepList) {
929                        List<TestStepDetail> testSetpList=new ArrayList<TestStepDetail>();
930                        String[] steps=testSteps.split("\\r?\\n");
931                        Integer i=1;
932                        for(String step:steps) {
933                                step = step.trim();
934                                if(keywordsList.contains(step.split(" ", 2)[0])) {
935                                        testStep=new TestStep();
936                                        TestStepDetail stepDetails=new TestStepDetail();
937                                        stepDetails.setOrderId(i);
938                    int countMatches = StringUtils.countMatches(step, "..");
939                    if(countMatches == 0){
940                        String stepData = step.substring(0,step.lastIndexOf(".")).trim();
941                        stepDetails.setStep(stepData);
942                    }else {
943                                                stepDetails.setStep(step.substring(0, step.indexOf("..")));
944                                        }
945
946                                        String[] statusStringArr = step.split("\\.");
947                                        status = statusStringArr[statusStringArr.length-1].trim();
948
949                                        if(StringUtils.isNumeric(status.substring(0,1))) {
950                                                //first character is numeric, check item before this in array for status
951                                                status = statusStringArr[statusStringArr.length-2].trim();
952                                        }
953
954                                        if(status.startsWith("failed")) {
955                                                stepDetails.setExecutionStatus("false");
956                                        }else if(status.startsWith("skipped") || status.startsWith("undefined")) {
957                                                stepDetails.setExecutionStatus("skipped");
958                                        }else {
959                                                stepDetails.setExecutionStatus("true");
960                                        }
961                                        testSetpList.add(stepDetails);
962                                        testStep.setSteps(testSetpList);
963                                        i++;
964                                }
965
966                        }
967                }
968                return testStep;
969        }
970
971    public static String removeIllegalCharactersAndTrimLength(String name)  {
972        // remove illegal characters and replace with a more friendly char ;)
973        System.out.println("Filename before special character removal " + name);
974        String safe = name.trim();
975        try{
976            safe = URLDecoder.decode(name, "UTF-8");
977        }catch (Exception ex){
978        }
979        System.out.println("Filename after special character normalized " + safe);
980        // remove illegal characters
981        safe = safe.replaceAll("[\\/|\\\\|\\*|\\:|\\||\"|\'|\\<|\\>|\\{|\\}|\\?|\\%|\\@|\\#|\\$|\\!|\\~|\\(|\\)|\\+|\\=|\\`|\\;|\\^|\\[|\\]|,|\\n]","");
982        //safe = safe.replaceAll("[^a-zA-Z0-9]", "");
983        System.out.println("Filename after special character removal " + safe);
984        if (safe.length() > 70)
985        {
986            safe = safe.substring(0, 70);
987        }
988        return safe;
989    }
990
991
992}