#### Generate xml report Transform to junit-like xml for Jenkins
196098
function results2xml(errorsNumber) {
        errorCount = 0;
        var result = ['<testsuite name="root" errors="' + errorsNumber + '">'];
        Object.keys(results).forEach(function(suite) {
            result.push('\r\n\t<testsuite name="' + escapeXML(suite) + '">');
            Object.keys(results[suite]).forEach(function(testcase) {
                result.push('\r\n\t\t<testcase name="' +
                escapeXML(testcase) + '">');
                results[suite][testcase].forEach(function(err) {
                    result.push('\r\n\t\t\t<failure>\r\n\t\t\t\t' +
                    escapeXML(JSON.stringify(err)) +
                    '\r\n\t\t\t</failure>');
                });
                result.push('\r\n\t\t</testcase>');
            });
            result.push('\r\n\t</testsuite>\n');
        });
        result.push('</testsuite>\n');
        return result.join('');
    }
942500
public static void main(String[] args) throws TransformerConfigurationException, SAXException{
        XSDocument xsd = new XSDocument(new StreamResult(System.out), false, 4, null);
        xsd.startDocument();
        {
            String n1 = "http://www.example.com/N1";
            String n2 = "http://www.example.com/N2";
            xsd.xml().declarePrefix("n1", n1);
            xsd.xml().declarePrefix("n2", n2);
            xsd.startSchema(n1);
            {
                xsd.addImport(n2, "imports/b.xsd");
                xsd.startComplexType().name("MyType");
                {
                    xsd.startCompositor(Compositor.SEQUENCE);
                    xsd.startElement().ref(n1, "e1").endElement();
                    xsd.endCompositor();
                }
                xsd.endComplexType();
                xsd.startElement().name("root").type(n1, "MyType").endElement();
            }
            xsd.endSchema();
        }
        xsd.endDocument();
    }
777426
def to_xml
      xml = Builder::XmlMarkup.new
      case
      when @self_closing && @content_type == 'container'
        xml.tag!(@name, @attributes)
      when @value.nil?
        xml.tag!(@name, @attributes.merge!("xsi:nil" => "true"))
      when ::Hash === @value
        xml.tag!(@name, @attributes) { xml << XmlFu::Hash.to_xml(@value) }
      when ::Array === @value
        case @content_type
        when "collection"
          xml << XmlFu::Array.to_xml(@value.flatten, {
            :key => (@self_closing ? "#{@name}/" : @name),
            :attributes => @attributes,
            :content_type => "collection"
          })
        when "container"
          xml.tag!(@name, @attributes) { xml << XmlFu::Array.to_xml(@value) }
        else
          # Shouldn't be anything else
        end
      else
        xml.tag!(@name, @attributes) { xml << self.value.to_s }
      end
      xml.target!
    end
1292799
private static void generateParserOnXmlCharacters(BindTypeContext context, MethodSpec.Builder methodBuilder,
			String instanceName, String parserName, BindEntity entity) {
		BindTransform bindTransform;
		int count = 0;
		for (BindProperty property : entity.getCollection()) {
			if (property.xmlInfo.xmlType != XmlType.VALUE && property.xmlInfo.xmlType != XmlType.VALUE_CDATA)
				continue;

			count++;
			methodBuilder.beginControlFlow("if (elementName!=null && $L.hasText())", parserName);
			methodBuilder.addCode("// property $L\n", property.getName());
			bindTransform = BindTransformer.lookup(property);
			bindTransform.generateParseOnXml(context, methodBuilder, parserName,
					property.getPropertyType().getTypeName(), "instance", property);
			methodBuilder.endControlFlow();
		}

		if (count == 0) {
			methodBuilder.addCode("// no property is binded to VALUE o CDATA ");
		}
	}
637021
@SuppressWarnings("squid:S134")
    private void createHtmlReport(FilePath reportFolder,
                                  String testFolderPath,
                                  File artifactsDir,
                                  List<String> reportNames,
                                  TestResult testResult) throws IOException, InterruptedException {
        String archiveTestResultMode =
                _resultsPublisherModel.getArchiveTestResultsMode();
        boolean createReport = archiveTestResultMode.equals(ResultsPublisherModel.CreateHtmlReportResults.getValue());


        if (createReport) {
            File testFolderPathFile = new File(testFolderPath);
            FilePath srcDirectoryFilePath = new FilePath(reportFolder, HTML_REPORT_FOLDER);
            if (srcDirectoryFilePath.exists()) {
                FilePath srcFilePath = new FilePath(srcDirectoryFilePath, IE_REPORT_FOLDER);
                if (srcFilePath.exists()) {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    srcFilePath.zip(baos);
                    File reportDirectory = new File(artifactsDir.getParent(), PERFORMANCE_REPORT_FOLDER);
                    if (!reportDirectory.exists()) {
                        reportDirectory.mkdir();
                    }
                    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
                    FilePath reportDirectoryFilePath = new FilePath(reportDirectory);
                    FilePath tmpZipFile = new FilePath(reportDirectoryFilePath, "tmp.zip");
                    tmpZipFile.copyFrom(bais);
                    bais.close();
                    baos.close();
                    tmpZipFile.unzip(reportDirectoryFilePath);
                    String newFolderName = org.apache.commons.io.FilenameUtils.getName(testFolderPathFile.getPath());
                    FileUtils.moveDirectory(new File(reportDirectory, IE_REPORT_FOLDER),
                            new File(reportDirectory, newFolderName));
                    tmpZipFile.delete();
                    outputReportFiles(reportNames, reportDirectory, testResult, false);
                }
            }
        }
    }
1329998
private void generatePackageXml(File packageFile, Collection<ArchiveEntry> files) throws Exception
    {
        getLog().info(String.format("Generating package.xml descriptor at [%s]", packageFile.getPath()));

        OutputFormat outputFormat = new OutputFormat("", true);
        outputFormat.setEncoding(this.encoding);
        OutputStream out = new FileOutputStream(packageFile);
        XMLWriter writer = new XMLWriter(out, outputFormat);
        writer.write(toXML(files));
        writer.close();
        out.close();
    }
408611
public static void serializeXMLDocument (Document doc, Writer output) throws TransformerException {
        // serialize XML document using identity transformation
        Transformer trans = TransformerFactory.newInstance().newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(output);
        trans.transform(source, result);
    }
283187
def generate_reporter_options
      reporter = []

      valid_types = @output_types & SUPPORTED_REPORT_TYPES
      valid_types.each do |raw_type|
        type = raw_type.strip
        output_path = File.join(File.expand_path(@output_directory), determine_output_file_name(type))
        reporter << "--report #{type}"
        reporter << "--output '#{output_path}'"

        if type == "html" && @open_report
          Scan.cache[:open_html_report_path] = output_path
        end
      end

      # adds another junit reporter in case the user does not specify one
      # this will be used to generate a results table and then discarded
      require 'tempfile'
      @temp_junit_report = Tempfile.new("junit_report")
      Scan.cache[:temp_junit_report] = @temp_junit_report.path
      reporter << "--report junit"
      reporter << "--output '#{Scan.cache[:temp_junit_report]}'"
      return reporter
    end
459684
function(run) {
            var t = this;

            var output = '<?xml version="1.0" encoding="UTF-8" ?>\n';
            output += '<testsuites>\n';

            run.getSuites().forEach(
                function(suite) {
                    output += t.getTestSuite(suite);
                }
            );

            output += '</testsuites>';

            var outfile = path.resolve(t.options.junitOutput);
            return fs.writeFile(outfile, output).then(
                function() {
                    console.log('\nwrote JUnit output to %s', outfile);
                },
                function(err) {
                    throw new Error('failed to write to file "'+outfile+'"');
                }
            );
        }
326537
public static String toXml(DeploymentDescriptor descriptor) {
        try {

            Marshaller marshaller = getContext().createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.jboss.org/jbpm deployment-descriptor.xsd");
            marshaller.setSchema(schema);
            StringWriter stringWriter = new StringWriter();

            // clone the object and cleanup transients
            DeploymentDescriptor clone = ((DeploymentDescriptorImpl) descriptor).clearClone();

            marshaller.marshal(clone, stringWriter);
            String output = stringWriter.toString();

            return output;
        } catch (Exception e) {
            throw new RuntimeException("Unable to generate xml from deployment descriptor", e);
        }
    }
86518
def _gen_xml(name,
             cpu,
             mem,
             diskp,
             nicp,
             hypervisor,
             os_type,
             arch,
             graphics=None,
             loader=None,
             **kwargs):
    '''
    
    '''
    mem = int(mem) * 1024  # MB
    context = {
        'hypervisor': hypervisor,
        'name': name,
        'cpu': six.text_type(cpu),
        'mem': six.text_type(mem),
    }
    if hypervisor in ['qemu', 'kvm']:
        context['controller_model'] = False
    elif hypervisor == 'vmware':
        # TODO: make bus and model parameterized, this works for 64-bit Linux
        context['controller_model'] = 'lsilogic'

    # By default, set the graphics to listen to all addresses
    if graphics:
        if 'listen' not in graphics:
            graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'}
        elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address':
            graphics['listen']['address'] = '0.0.0.0'

        # Graphics of type 'none' means no graphics device at all
        if graphics.get('type', 'none') == 'none':
            graphics = None
    context['graphics'] = graphics

    if loader and 'path' not in loader:
        log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration')
        loader = None
    elif loader:
        loader_attributes = []
        for key, val in loader.items():
            if key == 'path':
                continue
            loader_attributes.append("{key}='{val}'".format(key=key, val=val))
        loader['_attributes'] = ' '.join(loader_attributes)

    if 'boot_dev' in kwargs:
        context['boot_dev'] = []
        for dev in kwargs['boot_dev'].split():
            context['boot_dev'].append(dev)
    else:
        context['boot_dev'] = ['hd']

    context['loader'] = loader

    if os_type == 'xen':
        # Compute the Xen PV boot method
        if __grains__['os_family'] == 'Suse':
            context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen'
            context['boot_dev'] = []

    if 'serial_type' in kwargs:
        context['serial_type'] = kwargs['serial_type']
    if 'serial_type' in context and context['serial_type'] == 'tcp':
        if 'telnet_port' in kwargs:
            context['telnet_port'] = kwargs['telnet_port']
        else:
            context['telnet_port'] = 23023  # FIXME: use random unused port
    if 'serial_type' in context:
        if 'console' in kwargs:
            context['console'] = kwargs['console']
        else:
            context['console'] = True

    context['disks'] = []
    disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'}
    for i, disk in enumerate(diskp):
        prefix = disk_bus_map.get(disk['model'], 'sd')
        disk_context = {
            'device': disk.get('device', 'disk'),
            'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]),
            'disk_bus': disk['model'],
            'type': disk['format'],
            'index': six.text_type(i),
        }
        if 'source_file' and disk['source_file']:
            disk_context['source_file'] = disk['source_file']

        if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']:
            disk_context['address'] = False
            disk_context['driver'] = True
        elif hypervisor in ['esxi', 'vmware']:
            disk_context['address'] = True
            disk_context['driver'] = False
        context['disks'].append(disk_context)
    context['nics'] = nicp

    context['os_type'] = os_type
    context['arch'] = arch

    fn_ = 'libvirt_domain.jinja'
    try:
        template = JINJA.get_template(fn_)
    except jinja2.exceptions.TemplateNotFound:
        log.error('Could not load template %s', fn_)
        return ''

    return template.render(**context)
692213
def generate(basename, xml):
    ''''''
    if basename.endswith('.py'):
        filename = basename
    else:
        filename = basename + '.py'

    msgs = []
    enums = []
    filelist = []
    for x in xml:
        msgs.extend(x.message)
        enums.extend(x.enum)
        filelist.append(os.path.basename(x.filename))

    for m in msgs:
        if xml[0].little_endian:
            m.fmtstr = '<'
        else:
            m.fmtstr = '>'
        m.native_fmtstr = m.fmtstr
        for f in m.ordered_fields:
            m.fmtstr += mavfmt(f)
            m.native_fmtstr += native_mavfmt(f)
        m.order_map = [ 0 ] * len(m.fieldnames)
        m.len_map = [ 0 ] * len(m.fieldnames)
        m.array_len_map = [ 0 ] * len(m.fieldnames)
        for i in range(0, len(m.fieldnames)):
            m.order_map[i] = m.ordered_fieldnames.index(m.fieldnames[i])
            m.array_len_map[i] = m.ordered_fields[i].array_length
        for i in range(0, len(m.fieldnames)):
            n = m.order_map[i]
            m.len_map[n] = m.fieldlengths[i]

    print("Generating %s" % filename)
    outf = open(filename, "w")
    generate_preamble(outf, msgs, basename, filelist, xml[0])
    generate_enums(outf, enums)
    generate_message_ids(outf, msgs)
    generate_classes(outf, msgs)
    generate_mavlink_class(outf, msgs, xml[0])
    generate_methods(outf, msgs)
    outf.close()
    print("Generated %s OK" % filename)
889916
@Override
    public void writeXML(@WillClose XMLOutput xmlOutput) throws IOException {
        assert project != null;
        try {
            writePrologue(xmlOutput);
            if (withMessages) {
                computeBugHashes();
                getProjectStats().computeFileStats(this);
                String commonBase = null;
                for (String s : project.getSourceDirList()) {
                    if (commonBase == null) {
                        commonBase = s;
                    } else {
                        commonBase = commonBase.substring(0, commonPrefix(commonBase, s));
                    }

                }
                if (commonBase != null && commonBase.length() > 0) {
                    if (commonBase.indexOf("/./") > 0) {
                        commonBase = commonBase.substring(0, commonBase.indexOf("/."));
                    }
                    File base = new File(commonBase);
                    if (base.exists() && base.isDirectory() && base.canRead()) {
                        SourceLineAnnotation.generateRelativeSource(base, project);
                    }
                }
            }
            if (earlyStats && !minimalXML) {
                getProjectStats().writeXML(xmlOutput, withMessages);
            }

            // Write BugInstances
            for (BugInstance bugInstance : getCollection()) {
                if (!applySuppressions || !project.getSuppressionFilter().match(bugInstance)) {
                    bugInstance.writeXML(xmlOutput, this, withMessages);
                }
            }

            writeEpilogue(xmlOutput);

        } finally {
            xmlOutput.finish();
            SourceLineAnnotation.clearGenerateRelativeSource();
        }
    }
1265719
def generate(basename, xml):
    ''''''
    if basename.endswith('.lua'):
        filename = basename
    else:
        filename = basename + '.lua'

    msgs = []
    enums = []
    filelist = []
    for x in xml:
        msgs.extend(x.message)
        enums.extend(x.enum)
        filelist.append(os.path.basename(x.filename))

    for m in msgs:
        if xml[0].little_endian:
            m.fmtstr = '<'
        else:
            m.fmtstr = '>'
        for f in m.ordered_fields:
            m.fmtstr += mavfmt(f)
        m.order_map = [ 0 ] * len(m.fieldnames)
        for i in range(0, len(m.fieldnames)):
            m.order_map[i] = m.ordered_fieldnames.index(m.fieldnames[i])

    print("Generating %s" % filename)
    outf = open(filename, "w")
    generate_preamble(outf)
    generate_msg_table(outf, msgs)
    generate_body_fields(outf)
    
    for m in msgs:
        generate_msg_fields(outf, m)
    
    for m in msgs:
        generate_payload_dissector(outf, m)
    
    generate_packet_dis(outf)
#    generate_enums(outf, enums)
#    generate_message_ids(outf, msgs)
#    generate_classes(outf, msgs)
#    generate_mavlink_class(outf, msgs, xml[0])
#    generate_methods(outf, msgs)
    generate_epilog(outf)
    outf.close()
    print("Generated %s OK" % filename)
729556
protected function createJUnitXMLWriter()
    {
        $streamWriter = $this->createStreamWriter($this->junitXMLFile);
        $utf8Converter = extension_loaded('mbstring') ? new UTF8Converter() : new NullUTF8Converter();

        return $this->junitXMLRealtime ? new StreamJUnitXMLWriter($streamWriter, $utf8Converter) : new DOMJUnitXMLWriter($streamWriter, $utf8Converter);
    }
783757
public void writeXml(OutputStream out) throws IOException {
        Properties properties = getProps();
        try {
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            Element conf = doc.createElement("configuration");
            doc.appendChild(conf);
            conf.appendChild(doc.createTextNode("\n"));
            for (Enumeration e = properties.keys(); e.hasMoreElements();) {
                String name = (String) e.nextElement();
                Object object = properties.get(name);
                String value;
                if (object instanceof String) {
                    value = (String) object;
                } else {
                    continue;
                }
                Element propNode = doc.createElement("property");
                conf.appendChild(propNode);

                Element nameNode = doc.createElement("name");
                nameNode.appendChild(doc.createTextNode(name));
                propNode.appendChild(nameNode);

                Element valueNode = doc.createElement("value");
                valueNode.appendChild(doc.createTextNode(value));
                propNode.appendChild(valueNode);

                conf.appendChild(doc.createTextNode("\n"));
            }

            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(out);
            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer transformer = transFactory.newTransformer();
            transformer.transform(source, result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
424278
public static void convertDOMToXML(Node doc, Writer out)
    {
        try {
            // Use a Transformer for output
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();

            DOMSource source = new DOMSource(doc);

            StreamResult result = new StreamResult(out);
            transformer.transform(source, result);
        } catch (TransformerConfigurationException tce) {
            // Error generated by the parser
            tce.printStackTrace();
        } catch (TransformerException te) {
            // Error generated by the parser
            te.printStackTrace();
        }
    }