Run jing.jar using the RNG file against the given XML file.
4386
def jing(rng_filepath, *xml_filepaths):
    """"""
    cmd = ['java', '-jar']
    cmd.extend([str(JING_JAR), str(rng_filepath)])
    for xml_filepath in xml_filepaths:
        cmd.append(str(xml_filepath))
    proc = subprocess.Popen(cmd,
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            close_fds=True)
    out, err = proc.communicate()
    return _parse_jing_output(out.decode('utf-8'))
364505
def main(argv=None):
    
    parser = ArgumentParser(
        description='Convert between ReSpecTh XML file and ChemKED YAML file '
                    'automatically based on file extension.'
        )
    parser.add_argument('-i', '--input',
                        type=str,
                        required=True,
                        help='Input filename (e.g., "file1.yaml" or "file2.xml")'
                        )
    parser.add_argument('-o', '--output',
                        type=str,
                        required=False,
                        default='',
                        help='Output filename (e.g., "file1.xml" or "file2.yaml")'
                        )
    parser.add_argument('-fa', '--file-author',
                        dest='file_author',
                        type=str,
                        required=False,
                        default='',
                        help='File author name to override original'
                        )
    parser.add_argument('-fo', '--file-author-orcid',
                        dest='file_author_orcid',
                        type=str,
                        required=False,
                        default='',
                        help='File author ORCID'
                        )

    args = parser.parse_args(argv)

    if os.path.splitext(args.input)[1] == '.xml' and os.path.splitext(args.output)[1] == '.yaml':
        respth2ck(['-i', args.input, '-o', args.output, '-fa', args.file_author,
                   '-fo', args.file_author_orcid])

    elif os.path.splitext(args.input)[1] == '.yaml' and os.path.splitext(args.output)[1] == '.xml':
        c = chemked.ChemKED(yaml_file=args.input)
        c.convert_to_ReSpecTh(args.output)

    elif os.path.splitext(args.input)[1] == '.xml' and os.path.splitext(args.output)[1] == '.xml':
        raise KeywordError('Cannot convert .xml to .xml')

    elif os.path.splitext(args.input)[1] == '.yaml' and os.path.splitext(args.output)[1] == '.yaml':
        raise KeywordError('Cannot convert .yaml to .yaml')

    else:
        raise KeywordError('Input/output args need to be .xml/.yaml')
1068539
public void checkXmlFile(File file) throws IOException, SAXException {
        validator.reset();
        InputSource is = new InputSource(new FileInputStream(file));
        is.setSystemId(file.toURI().toURL().toString());
        checkAsXML(is);
    }
684357
def generate(self, *args, **kwargs):
        
        xmlstr = str(self)
        filename = args[0]
        with open(filename, 'w') as fil:
            fil.write(xmlstr)

        with open(self.get_latest_filename('junit.xml'), "w") as latest_report:
            latest_report.write(xmlstr)
877928
public T loadXml(File file) {

    FileResource resource = new FileResource(file);
    return loadXml(resource);
  }
201030
def __xinclude_libxml2(target, source, env):
    
    doc = libxml2.readFile(str(source[0]), None, libxml2.XML_PARSE_NOENT)
    doc.xincludeProcessFlags(libxml2.XML_PARSE_NOENT)
    doc.saveFile(str(target[0]))
    doc.freeDoc()

    return None
1111735
public void processFile(String fileName, boolean failOnFileNotFound) throws Exception {

    boolean fileFound = false;
    InputStream f = null;
    try {
      String furl = null;

      File file = new File(fileName); // files in filesystem
      if (!file.exists()) {
        URL url = classLoadHelper.getResource(fileName);
        if (url != null) {
          try {
            furl = URLDecoder.decode(url.getPath(), "UTF-8");
          } catch (UnsupportedEncodingException e) {
            furl = url.getPath();
          }
          file = new File(furl);
          try {
            f = url.openStream();
          } catch (IOException ignor) {
            // Swallow the exception
          }
        }
      } else {
        try {
          f = new java.io.FileInputStream(file);
        } catch (FileNotFoundException e) {
          // ignore
        }
      }

      if (f == null) {
        fileFound = false;
      } else {
        fileFound = true;
      }
    } finally {
      try {
        if (f != null) {
          f.close();
        }
      } catch (IOException ioe) {
        logger.warn("Error closing jobs file " + fileName, ioe);
      }
    }

    if (!fileFound) {
      if (failOnFileNotFound) {
        throw new SchedulerException("File named '" + fileName + "' does not exist.");
      } else {
        logger.warn(
            "File named '"
                + fileName
                + "' does not exist. This is OK if you don't want to use an XML job config file.");
      }
    } else {
      processFile(fileName);
    }
  }
12121
public void execute() throws Exception {
        final var jsonFile = new File(buildDir, "classes/java/main/META-INF/spring-configuration-metadata.json");
        if (!jsonFile.exists()) {
            throw new RuntimeException("Could not locate file " + jsonFile.getCanonicalPath());
        }
        final var mapper = new ObjectMapper().findAndRegisterModules();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);

        final TypeReference<Map<String, Set<ConfigurationMetadataProperty>>> values = new TypeReference<>() {
        };
        final Map<String, Set> jsonMap = mapper.readValue(jsonFile, values);
        final Set<ConfigurationMetadataProperty> properties = jsonMap.get("properties");
        final Set<ConfigurationMetadataProperty> groups = jsonMap.get("groups");

        final Set<ConfigurationMetadataProperty> collectedProps = new HashSet<>();
        final Set<ConfigurationMetadataProperty> collectedGroups = new HashSet<>();

        properties.stream()
            .filter(p -> NESTED_TYPE_PATTERN.matcher(p.getType()).matches())
            .forEach(Unchecked.consumer(p -> {
                final var matcher = NESTED_TYPE_PATTERN.matcher(p.getType());
                final var indexBrackets = matcher.matches();
                final var typeName = matcher.group(1);
                final var typePath = ConfigurationMetadataClassSourceLocator.buildTypeSourcePath(this.sourcePath, typeName);

                final var parser = new ConfigurationMetadataUnitParser(this.sourcePath);
                parser.parseCompilationUnit(collectedProps, collectedGroups, p, typePath, typeName, indexBrackets);
            }));

        properties.addAll(collectedProps);
        groups.addAll(collectedGroups);

        final var hints = processHints(properties, groups);

        processNestedEnumProperties(properties, groups);

        jsonMap.put("properties", properties);
        jsonMap.put("groups", groups);
        jsonMap.put("hints", hints);

        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        final var pp = new MinimalPrettyPrinter();
        final var writer = mapper.writer(pp);
        writer.writeValue(jsonFile, jsonMap);
    }
212210
public void execute() throws XDocletException
    {
        if (getJspversion().equals(JspVersionTypes.VERSION_1_1)) {
            setPublicId(TLD_PUBLICID_1_1);
            setSystemId(TLD_SYSTEMID_1_1);
            setDtdURL(getClass().getResource(TLD_DTD_FILE_NAME_1_1));
        }
        else {
            setPublicId(TLD_PUBLICID_1_2);
            setSystemId(TLD_SYSTEMID_1_2);
            setDtdURL(getClass().getResource(TLD_DTD_FILE_NAME_1_2));
        }

        startProcess();
    }
467211
public Object run(GroovyCodeSource source, String[] args) throws CompilationFailedException {
        Class scriptClass = parseClass(source);
        return runScriptOrMainOrTestOrRunnable(scriptClass, args);
    }
973315
public int execute() throws IOException
   {
      outputDir.mkdirs();

      // some archetypes might not use maven or use the maven source layout so lets remove
      // the pom.xml and src folder if its already been pre-created
      // as these will be created if necessary via the archetype jar's contents
      File pom = new File(outputDir, "pom.xml");
      if (pom.isFile() && pom.exists()) {
         pom.delete();
      }
      File src = new File(outputDir, "src");
      if (src.isDirectory() && src.exists()) {
         recursiveDelete(src);
      }

      if (packageName == null || packageName.length() == 0)
      {
         packageName = groupId + "." + artifactId;
      }

      String packageDir = packageName.replace('.', '/');

      info("Creating archetype using Maven groupId: " +
               groupId + ", artifactId: " + artifactId + ", version: " + version
               + " in directory: " + outputDir);

      Map<String, String> replaceProperties = new HashMap<String, String>();

      ZipInputStream zip = null;
      try
      {
         zip = new ZipInputStream(archetypeIn);
         boolean ok = true;
         while (ok)
         {
            ZipEntry entry = zip.getNextEntry();
            if (entry == null)
            {
               ok = false;
            }
            else
            {
               if (!entry.isDirectory())
               {
                  String fullName = entry.getName();
                  if (fullName != null && fullName.startsWith(zipEntryPrefix))
                  {
                     String name = replaceFileProperties(fullName.substring(zipEntryPrefix.length()), replaceProperties);
                     debug("Processing resource: " + name);

                     int idx = name.lastIndexOf('/');
                     Matcher matcher = sourcePathRegexPattern.matcher(name);
                     String dirName;
                     if (packageName.length() > 0 && idx > 0 && matcher.matches())
                     {
                        String prefix = matcher.group(1);
                        dirName = prefix + packageDir + "/" + name.substring(prefix.length());
                     }
                     else if (packageName.length() > 0 && name.startsWith(webInfResources))
                     {
                        dirName = "src/main/webapp/WEB-INF/" + packageDir + "/resources"
                                 + name.substring(webInfResources.length());
                     }
                     else
                     {
                        dirName = name;
                     }

                     // lets replace properties...
                     File file = new File(outputDir, dirName);
                     file.getParentFile().mkdirs();
                     FileOutputStream out = null;
                     try
                     {
                        out = new FileOutputStream(file);
                        boolean isBinary = false;
                        for (String suffix : binarySuffixes)
                        {
                           if (name.endsWith(suffix))
                           {
                              isBinary = true;
                              break;
                           }
                        }
                        if (isBinary)
                        {
                           // binary file? don't transform.
                           Streams.write(zip, out);
                        }
                        else
                        {
                           // text file...
                           ByteArrayOutputStream bos = new ByteArrayOutputStream();
                           Streams.write(zip, bos);
                           String text = new String(bos.toByteArray(), "UTF-8");
                           out.write(transformContents(text, replaceProperties).getBytes());
                        }
                     }
                     finally
                     {
                        if (out != null)
                        {
                           out.close();
                        }
                     }
                  }
                  else if (fullName != null && fullName.equals("META-INF/maven/archetype-metadata.xml"))
                  {
                     // we assume that this resource will be first in Archetype's ZIP
                     // this way we can find out what are the required properties before we will actually use them
                     parseReplaceProperties(zip, replaceProperties);
                     replaceProperties.putAll(overrideProperties);
                  }
               }
               zip.closeEntry();
            }
         }
      }
      catch (Exception e)
      {
         throw new IOException(e.getMessage(), e);
      }
      finally
      {
         if (zip != null)
         {
            zip.close();
         }
      }

      info("Using replace properties: " + replaceProperties);

      // now lets replace all the properties in the pom.xml
      if (!replaceProperties.isEmpty())
      {
         String text;
         try (FileInputStream fis = new FileInputStream(pom))
         {
            text = Streams.toString(fis);
         }
         for (Map.Entry<String, String> e : replaceProperties.entrySet())
         {
            text = replaceVariable(text, e.getKey(), e.getValue());
         }
         try (FileWriter writer = new FileWriter(pom))
         {
            writer.write(text);
            writer.flush();
         }
      }

      // now lets create the default directories
      if (createDefaultDirectories && pom.exists())
      {
         File srcDir = new File(outputDir, "src");
         File mainDir = new File(srcDir, "main");
         File testDir = new File(srcDir, "test");

         String srcDirName = "java";
         // Who needs Scala in 2014?
         // if (new File(mainDir, "scala").exists() || new File(textDir, "scala").exists()) {
         // srcDirName = "scala";
         // }

         for (File dir : new File[] { mainDir, testDir })
         {
            for (String name : new String[] { srcDirName + "/" + packageDir, "resources" })
            {
               new File(dir, name).mkdirs();
            }
         }
      }

      return 0;
   }
699114
def run(self, element, outfolder):
        """"""
        filepath = self.relative_path_for_element(element)
        if outfolder and not os.path.isabs(filepath):
            filepath = os.path.join(outfolder, filepath)

        _logger.debug('{!r} --> {!r}'.format(element, filepath))

        self.ensure_folder(filepath)
        self.generate_file(element, filepath)
815077
public static void main(String[] args) throws ClassNotFoundException, XMLStreamException, IOException, IntrospectionException
   {
      if (args.length != 3)
      {
         System.out.println("Usage: MapFileGenerator <file.jar> <remapfile.xml> <map class methods flag>");
      }
      else
      {
         MapFileGenerator generator = new MapFileGenerator();
         generator.generateMapFile(new File(args[0]), args[1], Boolean.parseBoolean(args[2]));
      }
   }
630605
def run(self):
        """"""
        self._make_lib_file_symbolic_links()
        self._copy_each_include_files_to_include_dir()
        self._make_dep_lib_file_sym_links_and_copy_include_files()
        self.setup_py.add_patchs_to_build_without_pkg_config(
            self.rpm.lib_dir, self.rpm.include_dir
        )
        self.setup_py.apply_and_save()
        self._build_and_install()
559149
def create_from_xml(sourcefileTag, get_value_from_logfile, listOfColumns,
                        correct_only, log_zip_cache, columns_relevant_for_diff,
                        result_file_or_url):
        '''
        
        '''

        def read_logfile_lines(log_file):
            if not log_file:
                return []
            log_file_url = Util.make_url(log_file)
            url_parts = urllib.parse.urlparse(log_file_url, allow_fragments=False)
            log_zip_path = os.path.dirname(url_parts.path) + ".zip"
            log_zip_url = urllib.parse.urlunparse((url_parts.scheme, url_parts.netloc,
                log_zip_path, url_parts.params, url_parts.query, url_parts.fragment))
            path_in_zip = urllib.parse.unquote(
                os.path.relpath(url_parts.path, os.path.dirname(log_zip_path)))
            if log_zip_url.startswith("file:///") and not log_zip_path.startswith("/"):
                # Replace file:/// with file: for relative paths,
                # otherwise opening fails.
                log_zip_url = "file:" + log_zip_url[8:]

            try:
                with Util.open_url_seekable(log_file_url, 'rt') as logfile:
                    return logfile.readlines()
            except IOError as unused_e1:
                try:
                    if log_zip_url not in log_zip_cache:
                        log_zip_cache[log_zip_url] = zipfile.ZipFile(
                            Util.open_url_seekable(log_zip_url, 'rb'))
                    log_zip = log_zip_cache[log_zip_url]

                    try:
                        with io.TextIOWrapper(log_zip.open(path_in_zip)) as logfile:
                            return logfile.readlines()
                    except KeyError:
                        logging.warning("Could not find logfile '%s' in archive '%s'.",
                                        log_file, log_zip_url)
                        return []

                except IOError as unused_e2:
                    logging.warning("Could not find logfile '%s' nor log archive '%s'.",
                                    log_file, log_zip_url)
                    return []

        status = Util.get_column_value(sourcefileTag, 'status', '')
        category = Util.get_column_value(sourcefileTag, 'category', result.CATEGORY_MISSING)
        score = result.score_for_task(
            sourcefileTag.get('properties', '').split(), category, status)
        logfileLines = None

        values = []

        for column in listOfColumns: # for all columns that should be shown
            value = None # default value
            if column.title.lower() == 'status':
                value = status

            elif not correct_only or category == result.CATEGORY_CORRECT:
                if not column.pattern or column.href:
                    # collect values from XML
                    value = Util.get_column_value(sourcefileTag, column.title)

                else: # collect values from logfile
                    if logfileLines is None: # cache content
                        logfileLines = read_logfile_lines(sourcefileTag.get('logfile'))

                    value = get_value_from_logfile(logfileLines, column.pattern)

            if column.title.lower() == 'score' and value is None and score is not None:
                # If no score column exists in the xml, take the internally computed score,
                # if available
                value = str(score)
            values.append(value)

        sourcefiles = sourcefileTag.get('files')
        if sourcefiles:
            if sourcefiles.startswith('['):
                sourcefileList = [s.strip() for s in sourcefiles[1:-1].split(',') if s.strip()]
                sourcefiles_exist = True if sourcefileList else False
            else:
                raise AssertionError('Unknown format for files tag:')
        else:
            sourcefiles_exist = False

        return RunResult(get_task_id(sourcefileTag, result_file_or_url if sourcefiles_exist else None),
                         status, category, score,
                         sourcefileTag.get('logfile'), listOfColumns, values,
                         columns_relevant_for_diff, sourcefiles_exist=sourcefiles_exist)
863868
def runs_to_xml(self, runSet, runs, blockname=None):
        
        # copy benchmarkinfo, limits, columntitles, systeminfo from xml_header
        runsElem = util.copy_of_xml_element(self.xml_header)
        runsElem.set("options", " ".join(runSet.options))
        if blockname is not None:
            runsElem.set("block", blockname)
            runsElem.set("name", ((runSet.real_name + ".") if runSet.real_name else "") + blockname)
        elif runSet.real_name:
            runsElem.set("name", runSet.real_name)

        # collect XMLelements from all runs
        for run in runs:
            runsElem.append(run.xml)

        return runsElem
524305
@Override
  protected void run() throws Exception {
    final ResourceLoader resourceLoader = new MojoResourceLoader(getRuntimeRealm(), getScriptpath());
    final Map<String, Object> context = createContext();
    final Map<String, Object> options = Maps.newHashMap();
    final ShellRunner shell = getRuntime().createShellRunner();

    shell.run(getRuntimeRealm(), resourceLoader, context, options);
  }