Package org.jconfig

Source Code of org.jconfig.VariableManager

package org.jconfig;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;
/**
* This class manages all variables for all log configurations.
* Every handler or formatter can use this class to replace
* any variables that are used inside of the parameters.
* Please refer to the specific handler or formatter to see
* which parameters support the use of variables.
*
* @author Andreas Mecky
* @author Terry Dye
*/
public class VariableManager {
   
    private static VariableManager vm = null;
    private HashMap varMapping;
    private Properties envVariables;
    // a HashMap containing a Vector for every config
    // with the immutable proerpties that were included
    private HashMap includedProperties;
    private HashMap inheritance = new HashMap();
   
    private VariableManager() {
        varMapping = new HashMap();
        includedProperties = new HashMap();
    }
   
    /**
     * This method will return an instance of the VariableManager
     *
     * @return the one and only instance of the VariableManager
     */
    public static VariableManager getInstance() {
        if ( vm == null ) {
            vm = new VariableManager();
        }
        return vm;
    }
   
    /**
     * Returns a Map of the variables associated to the given Configuration.
     *
     * @param configName
     * @return
     */
    public HashMap getVariables(String configName) {
        HashMap vars = (HashMap)varMapping.get(configName);
        if ( vars == null ) {
            vars = new HashMap();
        }       
        Vector includes = (Vector)includedProperties.get(configName);
        if ( includes != null ) {
            for ( int i=0;i < includes.size();i++) {
                String name = (String)includes.get(i);
                if ( vars.containsKey(name)) {
                    vars.remove(name);
                }
            }
        }
        return vars;
    }
   
    /**
     * Returns the variable's value.
     *
     * @param configName
     * @param name
     * @return
     */
    public String getVariable(String configName, String name) {
        HashMap vars = (HashMap)varMapping.get(configName);
        if ( vars != null && vars.containsKey(name)) {
            return (String)vars.get(name);
        }
        else {
          if ( inheritance.containsKey(configName)) {
            String base = (String)inheritance.get(configName);
            return getVariable(base,name);
          }
        }
        return null;
    }
   
    public void setInheritance(String configName,String baseConfig) {
      if ( !inheritance.containsKey(configName) && baseConfig != null ) {
          inheritance.put(configName,baseConfig);
        }
    }
    /**
     * This method adds a variable for a given configuration.
     *
     * @param varName name of the variable
     * @param varValue the value for this variable
     * @param configName the configuration to which this variable belongs
     */
    public void addVariable(String varName,String varValue,String configName) {
        HashMap vars = (HashMap)varMapping.get(configName);
        if ( vars == null ) {
            vars = new HashMap();
        }
        vars.put(varName,varValue);
        varMapping.put(configName,vars);
    }
   
    /**
     * This method removes a variable for a given configuration.
     *
     * @param varName name of the variable    
     * @param configName the configuration to which this variable belongs
     */
    public void removeVariable(String varName,String configName) {
        HashMap vars = (HashMap)varMapping.get(configName);
        if ( vars != null ) {
            vars.remove(varName);
            varMapping.put(configName,vars);
        }
    }
   
    /**
     *
     * @param varName
     * @param varValue
     * @param configName
     */
    public void addIncludedVariable(String varName,String varValue,String configName) {
        addVariable(varName,varValue,configName);
        Vector includes = (Vector)includedProperties.get(configName);
        if ( includes == null ) {
            includes = new Vector();
        }
        includes.add(varName);
        includedProperties.put(configName,includes);
    }
   
    /**
     * This method will replace all variables inside one String that
     * are in this configuration. A variable is used as ${name}.
     * This occurance will be replaced with the specific value
     * or will be left as is if the variable name is not found
     * in the specific configuration.
     *
     * @param text the line of text which contains variables
     * @param configName the name of the configuration
     * @return a String where all variables are replaced with their values
     */       
    public String replaceVariables(String text, String configName) {
        Map vars = (Map) varMapping.get(configName);
        if (vars != null && vars.size() > 0) {
            text = replaceVar(text, vars,configName);
        }
        text = replaceEnvVar(text);
        return replaceSystemVar(text);
    }
   
    private String replaceVar(String text, Map vars,String configName) {
        if (text == null) {
            return text;
        }
        // Find the start of the variable
        int startPosition = text.indexOf("${");
        if (startPosition == -1) {
            return text;
        }
       
        StringBuffer buffer = new StringBuffer();
        int textLength = text.length();
        int lastIndex = 0;
        // Loop while there are instances of "${" and cursor position is < length -2
        // so there are no index out of bounds on the indexOf calls.
        while (startPosition > -1 && (startPosition+2) < textLength) {
            int endPosition = text.indexOf("}", startPosition + 2);
            if (endPosition == -1) {
                // No end tag
                break;
            }
           
            // Append previous text to this point
            buffer.append(text.substring(lastIndex, startPosition));
           
            // key is ${currentKey}
            String currentKey = text.substring(startPosition + 2, endPosition);
            //String value = (String) vars.get(currentKey);
            String value = getVariable(configName,currentKey);
            if (value != null) {
                // Substitute any var's in this variable value
                value = replaceVar(value, vars,configName);
               
                // Append the new String
                buffer.append(value);
                lastIndex = endPosition + 1;
            } else {
                // append the ${ and start at the character after { to check more possible
                // variables.
                buffer.append(text.charAt(startPosition));
                buffer.append(text.charAt(startPosition+1));
                lastIndex = startPosition + 2;
            }
            // Set the 'pointer' to the end of the oldString in 'text'
            startPosition = text.indexOf("${", lastIndex);
        }
        // Append the final part
        buffer.append(text.substring(lastIndex, textLength));
        return buffer.toString();
    }
   
    protected String replaceEnvVar(String text) {
        if ( text != null ) {
            if ( envVariables == null && text.indexOf("${env:") != -1 ) {
                envVariables = getEnvVars();
            }
            int idx = text.indexOf("${env:");
            // walk through the text and replace it
            while ( idx != -1 ) {
                String firstPart = text.substring(0, idx);
                String tmp = text.substring(idx+6);
                String envVar = tmp.substring(0,tmp.indexOf("}"));
                String secondPart = text.substring(idx + envVar.length()+7);
                String value = envVariables.getProperty(envVar);
                if ( value == null ) {
                    value = "${env:"+envVar+"}";
                }
                text = firstPart + value + secondPart;
                idx = text.indexOf("${env:",idx+1);
            }
        }
        return text;
    }
   
    protected String replaceSystemVar(String text) {
        if ( text != null ) {
            int idx = text.indexOf("${system:");
            // walk through the text and replace it
            while ( idx != -1 ) {
                String firstPart = text.substring(0, idx);
                String tmp = text.substring(idx+9);
                String sysVar = tmp.substring(0,tmp.indexOf("}"));
                String secondPart = text.substring(idx + sysVar.length()+10);
                String value = System.getProperty(sysVar);
                if ( value == null ) {
                    value = "${system:"+sysVar+"}";
                }
                text = firstPart + value + secondPart;
                idx = text.indexOf("${system:",idx+1);
            }
        }
        return text;
    }
   
    // Thanx to http://www.rgagnon.com/howto.html for
    // this implementation.
    private Properties getEnvVars() {
        Process p = null;
        Properties envVars = new Properties();
        BufferedReader br = null;
        try {
            Runtime r = Runtime.getRuntime();
            String OS = System.getProperty("os.name").toLowerCase();
            if (OS.indexOf("windows 9") > -1) {
                p = r.exec( "command.com /c set" );
            }
            else if ( (OS.indexOf("nt") > -1)
            || (OS.indexOf("windows 2000") > -1
            || (OS.indexOf("windows xp") > -1) ) ) {
                // thanks to JuanFran for the xp fix!
                p = r.exec( "cmd.exe /c set" );
            }
            else {
                // our last hope, we assume Unix (thanks to H. Ware for the fix)
                p = r.exec( "env" );
            }
            br = new BufferedReader( new InputStreamReader( p.getInputStream() ) );
            String line;
            while( (line = br.readLine()) != null ) {
                int idx = line.indexOf( '=' );
                String key = line.substring( 0, idx );
                String value = line.substring( idx+1 );
                envVars.setProperty( key, value );
            }
            br.close();
        }
        catch (Exception e) {
            // we do not care here. Just no env vars for the user. Sorry.
            try {
                if ( br != null ) {
                    br.close();
                }
            } catch (IOException e1) {
            }
        }
        return envVars;
    }
}
TOP

Related Classes of org.jconfig.VariableManager

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.