<commit_before>/*
 * ################################################################
 *
 * ProActive: The Java(TM) library for Parallel, Distributed,
 *            Concurrent computing with Security and Mobility
 *
 * Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis
 * Contact: <EMAIL>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version
 * 2 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 *  Initial developer(s):               The ProActive Team
 *                        http://proactive.inria.fr/team_members.htm
 *  Contributor(s):
 *
 * ################################################################
 */
package org.objectweb.proactive.extra.scheduler.common.job;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.iso_relax.verifier.Schema;
import org.iso_relax.verifier.Verifier;
import org.iso_relax.verifier.VerifierConfigurationException;
import org.iso_relax.verifier.VerifierFactory;
import org.objectweb.proactive.extra.scheduler.common.exception.JobCreationException;
import org.objectweb.proactive.extra.scheduler.common.exception.UserException;
import org.objectweb.proactive.extra.scheduler.common.scripting.GenerationScript;
import org.objectweb.proactive.extra.scheduler.common.scripting.InvalidScriptException;
import org.objectweb.proactive.extra.scheduler.common.scripting.Script;
import org.objectweb.proactive.extra.scheduler.common.scripting.SelectionScript;
import org.objectweb.proactive.extra.scheduler.common.scripting.SimpleScript;
import org.objectweb.proactive.extra.scheduler.common.task.JavaExecutable;
import org.objectweb.proactive.extra.scheduler.common.task.JavaTask;
import org.objectweb.proactive.extra.scheduler.common.task.NativeTask;
import org.objectweb.proactive.extra.scheduler.common.task.ProActiveExecutable;
import org.objectweb.proactive.extra.scheduler.common.task.ProActiveTask;
import org.objectweb.proactive.extra.scheduler.common.task.ResultDescriptor;
import org.objectweb.proactive.extra.scheduler.common.task.Task;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;


public class JobFactory {
    public static final String SCHEMA_LOCATION = "/org/objectweb/proactive/extra/scheduler/common/xml/schemas/jobdescriptor/0.9/schedulerjob.rng";
    public static final String STYLESHEET_LOCATION = "/org/objectweb/proactive/extra/scheduler/common/xml/stylesheets/variables.xsl";
    public static final String JOB_NAMESPACE = "urn:proactive:jobdescriptor:0.9";
    public static final String JOB_PREFIX = "js";
    private static XPath xpath;

    /**
     * Singleton Pattern
     */
    private static JobFactory factory = null;

    private JobFactory() {
        xpath = XPathFactory.newInstance().newXPath();
        xpath.setNamespaceContext(new SchedulerNamespaceContext());
    }

    public static JobFactory getFactory() {
        if (factory == null) {
            factory = new JobFactory();
        }
        return factory;
    }

    /**
     * Creates a job using the given job descriptor
     * @param filePath the path to a job descriptor
     * @return a Job instance
     * @throws JobCreationException
     */
    public Job createJob(String filePath) throws JobCreationException {
        Job job = null;

        try {
            File f = new File(filePath);
            if (!f.exists()) {
                throw new FileNotFoundException(
                    "This file has not been found : " + filePath);
            }
            validate(filePath);
            Node rootNode = transformVariablesAndGetDOM(new FileInputStream(f));
            job = createJob(rootNode);
        } catch (Exception e) {
            throw new JobCreationException("Exception occured during Job creation",
                e);
        }
        return job;
    }

    /**
     * Validate the given job descriptor using the internal RELAX_NG Schema
     * @param filePath
     */
    private void validate(String filePath)
        throws URISyntaxException, VerifierConfigurationException, SAXException,
            IOException {
        // We use sun multi validator (msv)
        VerifierFactory vfactory = new com.sun.msv.verifier.jarv.TheFactoryImpl();

        URL schemaURL = this.getClass().getResource(SCHEMA_LOCATION);
        File schemaFile = new File(schemaURL.toURI());
        Schema schema = vfactory.compileSchema(schemaFile);
        Verifier verifier = schema.newVerifier();
        ValidatingErrorHandler veh = new ValidatingErrorHandler();
        verifier.setErrorHandler(veh);
        verifier.verify(filePath);
        if (veh.mistakes > 0) {
            System.err.println(veh.mistakes + " mistakes.");
            System.exit(1);
        }
    }

    /**
     * Parse the given octet stream to a XML DOM, and transform variable definitions using a stylesheet
     * @param input
     * @return
     */
    private Node transformVariablesAndGetDOM(InputStream input)
        throws ParserConfigurationException, SAXException, IOException {
        // create a new parser
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);
        DocumentBuilder db = factory.newDocumentBuilder();<commit_msg>stylesheet is now loaded as a stream to manage jar execution.<commit_after>/*
 * ################################################################
 *
 * ProActive: The Java(TM) library for Parallel, Distributed,
 *            Concurrent computing with Security and Mobility
 *
 * Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis
 * Contact: <EMAIL>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version
 * 2 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 *  Initial developer(s):               The ProActive Team
 *                        http://proactive.inria.fr/team_members.htm
 *  Contributor(s):
 *
 * ################################################################
 */
package org.objectweb.proactive.extra.scheduler.common.job;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.iso_relax.verifier.Schema;
import org.iso_relax.verifier.Verifier;
import org.iso_relax.verifier.VerifierConfigurationException;
import org.iso_relax.verifier.VerifierFactory;
import org.objectweb.proactive.extra.scheduler.common.exception.JobCreationException;
import org.objectweb.proactive.extra.scheduler.common.exception.UserException;
import org.objectweb.proactive.extra.scheduler.common.scripting.GenerationScript;
import org.objectweb.proactive.extra.scheduler.common.scripting.InvalidScriptException;
import org.objectweb.proactive.extra.scheduler.common.scripting.Script;
import org.objectweb.proactive.extra.scheduler.common.scripting.SelectionScript;
import org.objectweb.proactive.extra.scheduler.common.scripting.SimpleScript;
import org.objectweb.proactive.extra.scheduler.common.task.JavaExecutable;
import org.objectweb.proactive.extra.scheduler.common.task.JavaTask;
import org.objectweb.proactive.extra.scheduler.common.task.NativeTask;
import org.objectweb.proactive.extra.scheduler.common.task.ProActiveExecutable;
import org.objectweb.proactive.extra.scheduler.common.task.ProActiveTask;
import org.objectweb.proactive.extra.scheduler.common.task.ResultDescriptor;
import org.objectweb.proactive.extra.scheduler.common.task.Task;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;


public class JobFactory {
    public static final String SCHEMA_LOCATION = "/org/objectweb/proactive/extra/scheduler/common/xml/schemas/jobdescriptor/0.9/schedulerjob.rng";
    public static final String STYLESHEET_LOCATION = "/org/objectweb/proactive/extra/scheduler/common/xml/stylesheets/variables.xsl";
    public static final String JOB_NAMESPACE = "urn:proactive:jobdescriptor:0.9";
    public static final String JOB_PREFIX = "js";
    private static XPath xpath;

    /**
     * Singleton Pattern
     */
    private static JobFactory factory = null;

    private JobFactory() {
        xpath = XPathFactory.newInstance().newXPath();
        xpath.setNamespaceContext(new SchedulerNamespaceContext());
    }

    public static JobFactory getFactory() {
        if (factory == null) {
            factory = new JobFactory();
        }
        return factory;
    }

    /**
     * Creates a job using the given job descriptor
     * @param filePath the path to a job descriptor
     * @return a Job instance
     * @throws JobCreationException
     */
    public Job createJob(String filePath) throws JobCreationException {
        Job job = null;

        try {
            File f = new File(filePath);
            if (!f.exists()) {
                throw new FileNotFoundException(
                    "This file has not been found : " + filePath);
            }
            validate(filePath);
            Node rootNode = transformVariablesAndGetDOM(new FileInputStream(f));
            job = createJob(rootNode);
        } catch (Exception e) {
            throw new JobCreationException("Exception occured during Job creation",
                e);
        }
        return job;
    }

    /**
     * Validate the given job descriptor using the internal RELAX_NG Schema
     * @param filePath
     */
    private void validate(String filePath)
        throws URISyntaxException, VerifierConfigurationException, SAXException,
            IOException {
        // We use sun multi validator (msv)
        VerifierFactory vfactory = new com.sun.msv.verifier.jarv.TheFactoryImpl();

        InputStream schemaStream = this.getClass()
                                       .getResourceAsStream(SCHEMA_LOCATION);
        Schema schema = vfactory.compileSchema(schemaStream);
        Verifier verifier = schema.newVerifier();
        ValidatingErrorHandler veh = new ValidatingErrorHandler();
        verifier.setErrorHandler(veh);
        verifier.verify(filePath);
        if (veh.mistakes > 0) {
            System.err.println(veh.mistakes + " mistakes.");
            System.exit(1);
        }
    }

    /**
     * Parse the given octet stream to a XML DOM, and transform variable definitions using a stylesheet
     * @param input
     * @return
     */
    private Node transformVariablesAndGetDOM(InputStream input)
        throws ParserConfigurationException, SAXException, IOException {
        // create a new parser
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);
        DocumentBuilder db = factory.newDocumentBuilder();
{'fraction_non_alphanumeric': 0.10532260341663137, 'fraction_numerical': 0.004517859663984188, 'mean_word_length': 3.6449180327868853, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 46}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1091593', 'n_tokens_mistral': 3908, 'n_tokens_neox': 3797, 'n_words': 950}