1 package org.testng; 2 3 import com.beust.jcommander.JCommander; 4 import com.beust.jcommander.Parameter; 5 import com.beust.jcommander.ParameterException; 6 7 import org.testng.collections.Sets; 8 import org.testng.internal.Yaml; 9 import org.testng.xml.Parser; 10 import org.testng.xml.XmlSuite; 11 import org.xml.sax.SAXException; 12 13 import javax.xml.parsers.ParserConfigurationException; 14 15 import java.io.File; 16 import java.io.FileWriter; 17 import java.io.IOException; 18 import java.util.Arrays; 19 import java.util.Collection; 20 import java.util.List; 21 import java.util.Set; 22 23 /** 24 * Convert XML files to YAML and vice versa. 25 * 26 * @author cbeust 27 */ 28 public class Converter { 29 30 @Parameter(description = "file1 [file2 file3...]", required = true) 31 private List<String> m_files; 32 33 @Parameter(names = "-d", description = "The directory where the file(s) will be created") 34 private String m_outputDirectory = "."; 35 main(String[] args)36 public static void main(String[] args) 37 throws ParserConfigurationException, SAXException, IOException { 38 Converter c = new Converter(); 39 c.run(args); 40 } 41 findAllSuites(Collection<XmlSuite> suites, Set<XmlSuite> result)42 private void findAllSuites(Collection<XmlSuite> suites, Set<XmlSuite> result) { 43 for (XmlSuite s : suites) { 44 result.add(s); 45 for (XmlSuite xs : s.getChildSuites()) { 46 findAllSuites(Arrays.asList(xs), result); 47 } 48 } 49 } 50 run(String[] args)51 private void run(String[] args) 52 throws ParserConfigurationException, SAXException, IOException { 53 JCommander jc = new JCommander(this); 54 try { 55 jc.parse(args); 56 File f = new File(m_outputDirectory); 57 if (! f.exists()) f.mkdir(); 58 59 for (String file : m_files) { 60 Set<XmlSuite> allSuites = Sets.newHashSet(); 61 Parser parser = new Parser(file); 62 parser.setLoadClasses(false); // we might not have these classes on the classpath 63 findAllSuites(parser.parse(), allSuites); 64 65 for (XmlSuite suite : allSuites) { 66 String fileName = suite.getFileName(); 67 int ind = fileName.lastIndexOf("."); 68 String bn = fileName.substring(0, ind); 69 int ind2 = bn.lastIndexOf(File.separatorChar); 70 String baseName = bn.substring(ind2 + 1); 71 72 if (file.endsWith(".xml")) { 73 File newFile = new File(m_outputDirectory, baseName + ".yaml"); 74 writeFile(newFile, Yaml.toYaml(suite).toString()); 75 } 76 else if (file.endsWith(".yaml")) { 77 File newFile = new File(m_outputDirectory, baseName + ".xml"); 78 writeFile(newFile, suite.toXml()); 79 } 80 else { 81 throw new TestNGException("Unknown file type:" + file); 82 } 83 } 84 } 85 } 86 catch(ParameterException ex) { 87 System.out.println("Error: " + ex.getMessage()); 88 jc.usage(); 89 } 90 } 91 writeFile(File newFile, String content)92 private void writeFile(File newFile, String content) throws IOException { 93 try (FileWriter bw = new FileWriter(newFile)) { 94 bw.write(content); 95 } 96 System.out.println("Wrote " + newFile); 97 } 98 } 99