Best Testng code snippet using org.testng.xml.internal.Parser.setPostProcessor
Source:Parser.java  
...66  private void init(String fileName, InputStream is) {67    m_fileName = fileName != null ? fileName : DEFAULT_FILENAME;68    m_inputStream = is;69  }70  public void setPostProcessor(IPostProcessor processor) {71    m_postProcessor = processor;72  }73  /** @param loadClasses If false, don't try to load the classes during the parsing. */74  public void setLoadClasses(boolean loadClasses) {75    m_loadClasses = loadClasses;76  }77  private static IFileParser getParser(String fileName) {78    for (ISuiteParser parser : PARSERS) {79      if (parser.accept(fileName)) {80        return parser;81      }82    }83    return DEFAULT_FILE_PARSER;84  }85  /**86   * Parses the TestNG test suite and returns the corresponding XmlSuite, and possibly, other87   * XmlSuite that are pointed to by <code><suite-files></code> tags.88   *89   * @return the parsed TestNG test suite.90   * @throws IOException if an I/O error occurs while parsing the test suite file or if the default91   *     testng.xml file is not found.92   */93  public Collection<XmlSuite> parse() throws IOException {94    // Each suite found is put in this list, using their canonical95    // path to make sure we don't add a same file twice96    // (e.g. "testng.xml" and "./testng.xml")97    List<String> processedSuites = Lists.newArrayList();98    XmlSuite resultSuite = null;99    List<String> toBeParsed = Lists.newArrayList();100    List<String> toBeAdded = Lists.newArrayList();101    List<String> toBeRemoved = Lists.newArrayList();102    if (m_fileName != null) {103      URI uri = constructURI(m_fileName);104      if (uri == null || uri.getScheme() == null) {105        uri = new File(m_fileName).toURI();106      }107      if ("file".equalsIgnoreCase(uri.getScheme())) {108        File mainFile = new File(uri);109        toBeParsed.add(mainFile.getCanonicalPath());110      } else {111        toBeParsed.add(uri.toString());112      }113    }114    /*115     * Keeps a track of parent XmlSuite for each child suite116     */117    Map<String, Queue<XmlSuite>> childToParentMap = Maps.newHashMap();118    while (!toBeParsed.isEmpty()) {119      for (String currentFile : toBeParsed) {120        File parentFile = null;121        InputStream inputStream = null;122        if (hasFileScheme(currentFile)) {123          File currFile = new File(currentFile);124          parentFile = currFile.getParentFile();125          inputStream = m_inputStream != null ? m_inputStream : new FileInputStream(currFile);126        }127        IFileParser<XmlSuite> fileParser = getParser(currentFile);128        XmlSuite currentXmlSuite = fileParser.parse(currentFile, inputStream, m_loadClasses);129        currentXmlSuite.setParsed(true);130        processedSuites.add(currentFile);131        toBeRemoved.add(currentFile);132        if (childToParentMap.containsKey(currentFile)) {133          XmlSuite parentSuite = childToParentMap.get(currentFile).remove();134          // Set parent135          currentXmlSuite.setParentSuite(parentSuite);136          // append children137          parentSuite.getChildSuites().add(currentXmlSuite);138        }139        if (null == resultSuite) {140          resultSuite = currentXmlSuite;141        }142        List<String> suiteFiles = currentXmlSuite.getSuiteFiles();143        if (!suiteFiles.isEmpty()) {144          for (String path : suiteFiles) {145            String canonicalPath = path;146            if (hasFileScheme(path)) {147              if (parentFile != null && new File(parentFile, path).exists()) {148                canonicalPath = new File(parentFile, path).getCanonicalPath();149              } else {150                canonicalPath = new File(path).getCanonicalPath();151              }152            }153            if (!processedSuites.contains(canonicalPath)) {154              toBeAdded.add(canonicalPath);155              if (childToParentMap.containsKey(canonicalPath)) {156                childToParentMap.get(canonicalPath).add(currentXmlSuite);157              } else {158                Queue<XmlSuite> parentQueue = new ArrayDeque<>();159                parentQueue.add(currentXmlSuite);160                childToParentMap.put(canonicalPath, parentQueue);161              }162            }163          }164        }165      }166      //167      // Add and remove files from toBeParsed before we loop168      //169      toBeParsed.removeAll(toBeRemoved);170      toBeRemoved = Lists.newArrayList();171      toBeParsed.addAll(toBeAdded);172      toBeAdded = Lists.newArrayList();173    }174    // returning a list of single suite to keep changes minimum175    List<XmlSuite> resultList = Lists.newArrayList();176    resultList.add(resultSuite);177    if (m_postProcessor != null) {178      return m_postProcessor.process(resultList);179    } else {180      return resultList;181    }182  }183  /**184   * @param uri - The uri to be verified.185   * @return - <code>true</code> if the uri has "file:" as its scheme.186   */187  public static boolean hasFileScheme(String uri) {188    URI constructedURI = constructURI(uri);189    if (constructedURI == null) {190      // There were difficulties in constructing the URI. Falling back to considering the URI as a191      // file.192      return true;193    }194    String scheme = constructedURI.getScheme();195    // A URI is regarded as having a file scheme if it either has its scheme as "file"196    // (or) if the scheme is null (which is true when uri's represent local file system path.)197    return scheme == null || "file".equalsIgnoreCase(scheme);198  }199  public List<XmlSuite> parseToList() throws IOException {200    return Lists.newArrayList(parse());201  }202  public static Collection<XmlSuite> parse(String suite, IPostProcessor processor)203      throws IOException {204    return newParser(suite, processor).parse();205  }206  public static Collection<XmlSuite> parse(InputStream is, IPostProcessor processor)207      throws IOException {208    return newParser(is, processor).parse();209  }210  public static boolean canParse(String fileName) {211    for (ISuiteParser parser : PARSERS) {212      if (parser.accept(fileName)) {213        return true;214      }215    }216    return DEFAULT_FILE_PARSER.accept(fileName);217  }218  private static Parser newParser(String path, IPostProcessor processor) {219    Parser result = new Parser(path);220    result.setPostProcessor(processor);221    return result;222  }223  private static Parser newParser(InputStream is, IPostProcessor processor) {224    Parser result = new Parser(is);225    result.setPostProcessor(processor);226    return result;227  }228  private static URI constructURI(String text) {229    try {230      return URI.create(text);231    } catch (Exception e) {232      return null;233    }234  }235}...setPostProcessor
Using AI Code Generation
1public class TestNGXmlParser {2public static void main(String[] args) throws Exception {3    File file = new File("C:\\Users\\sandeep\\Desktop\\testng.xml");4    TestNGXmlParser parser = new TestNGXmlParser();5    parser.setPostProcessor(new TestNGXmlPostProcessor());6    parser.parse(file);7}8private ITestNGXmlPostProcessor postProcessor;9public void setPostProcessor(ITestNGXmlPostProcessor postProcessor) {10    this.postProcessor = postProcessor;11}12public void parse(File file) throws Exception {13    if (file == null) {14        throw new Exception("File path is empty");15    }16    if (!file.exists()) {17        throw new Exception("File does not exist: " + file.getAbsolutePath());18    }19    if (!file.isFile()) {20        throw new Exception("File is not a file: " + file.getAbsolutePath());21    }22    if (!file.canRead()) {23        throw new Exception("File is not readable: " + file.getAbsolutePath());24    }25    try {26        InputStream is = new FileInputStream(file);27        parse(is);28    } catch (Exception e) {29        throw new Exception("Failed to parse file: " + file.getAbsolutePath(), e);30    }31}32public void parse(InputStream is) throws Exception {33    if (is == null) {34        throw new Exception("InputStream is null");35    }36    try {37        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();38        Document doc = builder.parse(is);39        doc.getDocumentElement().normalize();40        if (postProcessor != null) {41            postProcessor.process(doc);42        }43        parse(doc);44    } catch (Exception e) {45        throw new Exception("Failed to parse input stream", e);46    }47}48private void parse(Document doc) throws Exception {49    if (doc == null) {50        throw new Exception("Document is null");51    }52    Element root = doc.getDocumentElement();53    if (root == null) {54        throw new Exception("Root element is null");55    }56    if (!root.getNodeName().equals("suite")) {57        throw new Exception("Root element is not suite");58    }59    NodeList nl = root.getChildNodes();60    for (int i = 0; i < nl.getLength(); i++) {61        Node node = nl.item(i);62        if (node instanceof Element) {63            Element element = (Element) node;64            String name = element.getNodeName();65            if (name.equalsTestNG is a Java-based open-source framework for test automation that includes various test types, such as unit testing, functional testing, E2E testing, etc. TestNG is in many ways similar to JUnit and NUnit. But in contrast to its competitors, its extensive features make it a lot more reliable framework. One of the major reasons for its popularity is its ability to structure tests and improve the scripts' readability and maintainability. Another reason can be the important characteristics like the convenience of using multiple annotations, reliance, and priority that make this framework popular among developers and testers for test design. You can refer to the TestNG tutorial to learn why you should choose the TestNG framework.
You can push your abilities to do automated testing using TestNG and advance your career by earning a TestNG certification. Check out our TestNG certification.
Watch this complete tutorial to learn how you can leverage the capabilities of the TestNG framework for Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!
