<commit_before>package info.ganglia.jmxetric;


import info.ganglia.gmetric4j.gmetric.GMetric;
import info.ganglia.gmetric4j.gmetric.GMetric.UDPAddressingMode;
import info.ganglia.gmetric4j.gmetric.GMetricSlope;
import info.ganglia.gmetric4j.gmetric.GMetricType;

import java.io.IOException;
//import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * Configures the JMXetricAgent based on the XML config file
 */
public class XMLConfigurationService {
//    private static Logger log =
//      Logger.getLogger(JMXetricAgent.class.getName());

    private final static XPath xpath = XPathFactory.newInstance().newXPath();
    
    private static final String DEFAULT_HOST = "localhost";
    private static final String DEFAULT_PORT = "8649";
    private static final String DEFAULT_CONFIG="jmxetric.xml";
    private static final String DEFAULT_MODE="multicast";
    private static final String DEFAULT_USE_WIREFORMAT31 = "false";
    
    /**
     * Configures the JMXetricAgent based on the supplied agentArgs
     * @param agent the agent to configure
     * @param agentArgs the agent arguments list
     * @throws java.lang.Exception
     */
    public static void configure(JMXetricAgent agent, String agentArgs) throws Exception {
        String host = null ;
        String port = null ;
        String mode = null ;
        String config = DEFAULT_CONFIG ;
        String wireformat = null ;
        String processName = null ;
        String spoof = null;
        
        if ( agentArgs != null ) {
            String[] args = agentArgs.split(",");
            host = getTagValue("host", args, DEFAULT_HOST);
            port = getTagValue("port", args, DEFAULT_PORT);
            config = getTagValue("config", args, DEFAULT_CONFIG);
            mode = getTagValue( "mode", args, DEFAULT_MODE);
            wireformat = getTagValue( "wireformat31x", args, DEFAULT_USE_WIREFORMAT31);
            processName = getTagValue( "process", args, null );
            spoof = getTagValue( "spoof", args, null );
        }

        // log.config("Command line argument found: host=" + host );
        // log.config("Command line args: port=" + port );
        // log.config("Command line args: config=" + config );
        // log.config("Command line args: mode=" + mode );
        // log.config("Command line args: wireformat31x=" + wireformat );
        // log.config("Command line args: process=" + processName );
        // log.config("Command line args: spoof=" + spoof );
        
        InputSource inputSource = new InputSource(config);

        configureGangliaFromXML( agent, inputSource, host, port, mode, 
            wireformat, spoof );
        configureJMXetricFromXML( agent, inputSource, config, processName );
    }

    private final static Pattern argPattern = Pattern.compile( "(\\S+?)\\=(\\S*)" );

    // Default multicast TTL = 5 (same site)
	private static final int DEFAULT_TTL = 5;
    
    /**
     * Parses the string array, input, looking for a pattern tag=value
     * @param tag the tag to search for
     * @param input the array list 
     * @param defaultValue the default value if tag is not found
     * @return tha value
     */
    private static String getTagValue(String tag, String[] input, String defaultValue) {
        for( String arg: input) {
            Matcher matcher = argPattern.matcher(arg);
            // Get tagname and contents of tag
            if ( matcher.find() ) {
                String tagname = matcher.group(1);     
                if ( tag.equals( tagname )) {
                    return matcher.group(2);
                }
            }
        }
        return defaultValue ;
    }
    
    private static String selectParameterFromNode( Node ganglia, 
    		String attributeName, String defaultValue ) {
    	return selectParameterFromNode( (String)null, ganglia, attributeName, defaultValue);
    }

    private static String selectParameterFromNode(String cmdLine, 
    		Node ganglia, String attributeName, 
    		String defaultValue) {
    	String ret = defaultValue ;
    	if ( cmdLine != null )
    		ret = cmdLine ;
    	else if ( ganglia != null ) {
    		Node node = ganglia.getAttributes().getNamedItem(attributeName);
    		if ( node != null ) {
	    		String value = node.getNodeValue();
	    		if ( value != null )
	    			ret = value ;
    		}
    	}
    	return ret ;
    }
    /**
     * Creates a GMetric attribute on the JMXetricAgent from the XML config
     * @param agent the agent to configure
     * @param inputSource the input xml
     * @param cmdLineHost the host found on the agent arg list
     * @param cmdLinePort the port found on the agent arg list
     * @param cmdLineMode the mode found on the agent arg list
     * @param v31x true if the ganglia v31x wire format should be used
     * @param cmdLineSpoof the spoof value found on the agent arg list
     * @throws IOException
     * @throws XPathExpressionException
     * @throws java.lang.Exception
     */
    private static void configureGangliaFromXML(JMXetricAgent agent, 
            InputSource inputSource, String cmdLineHost, 
            String cmdLinePort, String cmdLineMode, String cmdLinev31x, String cmdLineSpoof)
            		throws XPathExpressionException, IOException
                    {
        // Gets the config for ganglia
        // Note that the ganglia config needs to be found before the samplers 
        // are created.
        GMetric gmetric = makeGMetricFromXml(inputSource, cmdLineHost, cmdLinePort, cmdLineMode, cmdLinev31x, cmdLineSpoof);
        agent.setGmetric(gmetric);
    }
    
    private static GMetric makeGMetricFromXml(InputSource inputSource, String cmdLineHost,
            String cmdLinePort, String cmdLineMode, String cmdLinev31x, String cmdLineSpoof)
            		throws XPathExpressionException, IOException {
        String gangliaExpr = "/jmxetric-config/ganglia";
        Node g = (Node) xpath.evaluate(gangliaExpr, inputSource,
                XPathConstants.NODE);
        String hostname = selectParameterFromNode(cmdLineHost,
        		g, "hostname", "localhost");
        String port = selectParameterFromNode(cmdLinePort,
        		g, "port", "8649");
        int iport = Integer.parseInt(port);
        String mode = selectParameterFromNode(cmdLineMode,
        		g, "mode",DEFAULT_MODE);
        UDPAddressingMode addressingMode = UDPAddressingMode.MULTICAST;
        if (mode.toLowerCase().equals("unicast")) {
        	addressingMode = UDPAddressingMode.UNICAST;
        }
        String stringv31x = selectParameterFromNode(cmdLinev31x,
        		g, "wireformat31x", "false");
        boolean v31x = Boolean.parseBoolean(stringv31x);
        String spoof = selectParameterFromNode(cmdLineSpoof,
                g, "spoof", null);
        
        StringBuilder buf = new StringBuilder();
        buf.append("GMetric host=").append(hostname);
        buf.append(" port=").append(port);
        buf.append(" mode=").append(mode);
        buf.append(" v31x=").append(v31x);
        buf.append(" spoof=").append(spoof);
        // log.fine(buf.toString());
        return new GMetric(hostname, iport, addressingMode, DEFAULT_TTL, v31x, null, spoof);
    }

    /**
     * Creates managed attributed on the JMXetricAgent from the XML config
     * @param agent the agent to configure
     * @param inputSource the input xml
     * @param file the config file from trom the agent arg list
     * @throws java.lang.Exception
     */
    private static void configureJMXetricFromXML(JMXetricAgent agent,
            InputSource inputSource, String file, String processName) throws Exception {

        // if the processName supplied from the agent arg list is null, see if 
        // it's in the xml
        if ( processName == null ) {
            Node jvm = (Node) xpath.evaluate("/jmxetric-config/jvm", inputSource,
                XPathConstants.NODE);
            if ( jvm != null )<commit_msg>Fix regression introduced by 78fb5c7<commit_after>package info.ganglia.jmxetric;


import info.ganglia.gmetric4j.gmetric.GMetric;
import info.ganglia.gmetric4j.gmetric.GMetric.UDPAddressingMode;
import info.ganglia.gmetric4j.gmetric.GMetricSlope;
import info.ganglia.gmetric4j.gmetric.GMetricType;

import java.io.IOException;
//import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * Configures the JMXetricAgent based on the XML config file
 */
public class XMLConfigurationService {
//    private static Logger log =
//      Logger.getLogger(JMXetricAgent.class.getName());

    private final static XPath xpath = XPathFactory.newInstance().newXPath();
    
    private static final String DEFAULT_HOST = "localhost";
    private static final String DEFAULT_PORT = "8649";
    private static final String DEFAULT_CONFIG="jmxetric.xml";
    private static final String DEFAULT_MODE="multicast";
    private static final String DEFAULT_USE_WIREFORMAT31 = "false";
    
    /**
     * Configures the JMXetricAgent based on the supplied agentArgs
     * @param agent the agent to configure
     * @param agentArgs the agent arguments list
     * @throws java.lang.Exception
     */
    public static void configure(JMXetricAgent agent, String agentArgs) throws Exception {
    	String host = null,
    		   port = null,
    		   mode = null,
    		   config = DEFAULT_CONFIG,
    		   wireformat = null,
    		   processName = null,
    		   spoof = null;
        
        if (agentArgs != null) {
            String[] args = agentArgs.split(",");
            host = getTagValue("host", args, null);
            port = getTagValue("port", args, null);
            config = getTagValue("config", args, DEFAULT_CONFIG);
            mode = getTagValue( "mode", args, null);
            wireformat = getTagValue( "wireformat31x", args, null);
            processName = getTagValue( "process", args, null );
            spoof = getTagValue( "spoof", args, null );
        }

        // log.config("Command line argument found: host=" + host );
        // log.config("Command line args: port=" + port );
        // log.config("Command line args: config=" + config );
        // log.config("Command line args: mode=" + mode );
        // log.config("Command line args: wireformat31x=" + wireformat );
        // log.config("Command line args: process=" + processName );
        // log.config("Command line args: spoof=" + spoof );
        
        InputSource inputSource = new InputSource(config);

        configureGangliaFromXML( agent, inputSource, host, port, mode, 
            wireformat, spoof );
        configureJMXetricFromXML( agent, inputSource, config, processName );
    }

    private final static Pattern argPattern = Pattern.compile( "(\\S+?)\\=(\\S*)" );

    // Default multicast TTL = 5 (same site)
	private static final int DEFAULT_TTL = 5;
    
    /**
     * Parses the string array, input, looking for a pattern tag=value
     * @param tag the tag to search for
     * @param input the array list 
     * @param defaultValue the default value if tag is not found
     * @return tha value
     */
    private static String getTagValue(String tag, String[] input, String defaultValue) {
        for( String arg: input) {
            Matcher matcher = argPattern.matcher(arg);
            // Get tagname and contents of tag
            if ( matcher.find() ) {
                String tagname = matcher.group(1);     
                if ( tag.equals( tagname )) {
                    return matcher.group(2);
                }
            }
        }
        return defaultValue ;
    }
    
    private static String selectParameterFromNode( Node ganglia, 
    		String attributeName, String defaultValue ) {
    	return selectParameterFromNode( (String)null, ganglia, attributeName, defaultValue);
    }

    private static String selectParameterFromNode(String cmdLine, 
    		Node ganglia, String attributeName, 
    		String defaultValue) {
    	String ret = defaultValue ;
    	if ( cmdLine != null )
    		ret = cmdLine ;
    	else if ( ganglia != null ) {
    		Node node = ganglia.getAttributes().getNamedItem(attributeName);
    		if ( node != null ) {
	    		String value = node.getNodeValue();
	    		if ( value != null )
	    			ret = value ;
    		}
    	}
    	return ret ;
    }
    /**
     * Creates a GMetric attribute on the JMXetricAgent from the XML config
     * @param agent the agent to configure
     * @param inputSource the input xml
     * @param cmdLineHost the host found on the agent arg list
     * @param cmdLinePort the port found on the agent arg list
     * @param cmdLineMode the mode found on the agent arg list
     * @param v31x true if the ganglia v31x wire format should be used
     * @param cmdLineSpoof the spoof value found on the agent arg list
     * @throws IOException
     * @throws XPathExpressionException
     * @throws java.lang.Exception
     */
    private static void configureGangliaFromXML(JMXetricAgent agent, 
            InputSource inputSource, String cmdLineHost, 
            String cmdLinePort, String cmdLineMode, String cmdLinev31x, String cmdLineSpoof)
            		throws XPathExpressionException, IOException
                    {
        // Gets the config for ganglia
        // Note that the ganglia config needs to be found before the samplers 
        // are created.
        GMetric gmetric = makeGMetricFromXml(inputSource, cmdLineHost, cmdLinePort, cmdLineMode, cmdLinev31x, cmdLineSpoof);
        agent.setGmetric(gmetric);
    }
    
    private static GMetric makeGMetricFromXml(InputSource inputSource, String cmdLineHost,
            String cmdLinePort, String cmdLineMode, String cmdLinev31x, String cmdLineSpoof)
            		throws XPathExpressionException, IOException {
        String gangliaExpr = "/jmxetric-config/ganglia";
        Node g = (Node) xpath.evaluate(gangliaExpr, inputSource,
                XPathConstants.NODE);
        String hostname = selectParameterFromNode(cmdLineHost,
        		g, "hostname", DEFAULT_HOST);
        String port = selectParameterFromNode(cmdLinePort,
        		g, "port", DEFAULT_PORT);
        int iport = Integer.parseInt(port);
        String mode = selectParameterFromNode(cmdLineMode,
        		g, "mode",DEFAULT_MODE);
        UDPAddressingMode addressingMode = UDPAddressingMode.MULTICAST;
        if (mode.toLowerCase().equals("unicast")) {
        	addressingMode = UDPAddressingMode.UNICAST;
        }
        String stringv31x = selectParameterFromNode(cmdLinev31x,
        		g, "wireformat31x", DEFAULT_USE_WIREFORMAT31);
        boolean v31x = Boolean.parseBoolean(stringv31x);
        String spoof = selectParameterFromNode(cmdLineSpoof,
                g, "spoof", null);
        
        StringBuilder buf = new StringBuilder();
        buf.append("GMetric host=").append(hostname);
        buf.append(" port=").append(port);
        buf.append(" mode=").append(mode);
        buf.append(" v31x=").append(v31x);
        buf.append(" spoof=").append(spoof);
        // log.fine(buf.toString());
        return new GMetric(hostname, iport, addressingMode, DEFAULT_TTL, v31x, null, spoof);
    }

    /**
     * Creates managed attributed on the JMXetricAgent from the XML config
     * @param agent the agent to configure
     * @param inputSource the input xml
     * @param file the config file from trom the agent arg list
     * @throws java.lang.Exception
     */
    private static void configureJMXetricFromXML(JMXetricAgent agent,
            InputSource inputSource, String file, String processName) throws Exception {

        // if the processName supplied from the agent arg list is null, see if 
        // it's in the xml
        if ( processName == null ) {
            Node jvm = (Node) xpath.evaluate("/jmxetric-config/jvm", inputSource,
                XPathConstants.NODE);
            if ( jvm != null )
{'fraction_non_alphanumeric': 0.09247285592289863, 'fraction_numerical': 0.006343784311333415, 'mean_word_length': 2.596972356296621, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 18}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6743326', 'n_tokens_mistral': 4649, 'n_tokens_neox': 4517, 'n_words': 1332}