<commit_before>/* 
 * Copyright 2005  The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package org.apache.commons.exec.environment;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.CommandLineImpl;
import org.apache.commons.exec.Execute;
import org.apache.commons.exec.OS;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Wrapper for environment variables.
 * @todo change from inheritence to delegation, implement map
 */
public class Environment extends HashMap {

    private static Log LOG = LogFactory.getLog(Environment.class);

    public static Environment createEnvironment() {
        if (OS.isFamilyOpenVms()) {
            return new OpenVmsEnvironment();
        } else {
            return new Environment();
        }
    }

    public static Environment createEnvironment(String[] envVars) {
        Environment env = createEnvironment();

        if(envVars != null) {
            for (int i = 0; i < envVars.length; i++) {
                env.addVariable(EnvironmentVariable
                        .createEnvironmentVariable(envVars[i]));
            }
        }
        return env;
    }

    /**
     * Comment for <code>serialVersionUID</code>
     */
    private static final long serialVersionUID = 3256443594801165364L;

    private static Environment procEnvironment;

    /**
     * Default constructor, creates an empty environment
     */
    protected Environment() {
    }

    /**
     * Creates an environment from a @link Map of @link String
     * keys and values.
     * 
     * @param env A map containg the environment variable name
     * as @link String key and the variable value as @link String 
     * value 
     */
    protected Environment(Map env) {
        this();

        Set entries = env.entrySet();
        for (Iterator iter = entries.iterator(); iter.hasNext();) {
            Map.Entry entry = (Map.Entry) iter.next();
            addVariable((String) entry.getKey(),
                        (String) entry.getValue());
        }
    }

    /**
     * add a variable. Validity checking is <i>not</i> performed at this point.
     * Duplicates are not caught either.
     * 
     * @param var
     *            new variable.
     */
    public void addVariable(final EnvironmentVariable var) {
        put(var.getKey(), var);
    }

    public void addVariable(final String key, final String value) {
        put(key, EnvironmentVariable.createEnvironmentVariable(key, value));
    }

    /**
     * get the variable list as an array
     * 
     * @return array of key=value assignment strings
     */
    public String[] getVariables() {
        if (size() == 0) {
            return null;
        }
        String[] result = new String[size()];
        int i = 0;
        for (Iterator iter = entrySet().iterator(); iter.hasNext();) {
            Map.Entry entry = (Map.Entry) iter.next();

            result[i] = ((EnvironmentVariable) entry.getValue()).toString();
            i++;
        }
        return result;
    }

    /**
     * Find the list of environment variables for this process.
     * 
     * @return a vector containing the environment variables the vector elements
     *         are strings formatted like variable = value
     * @throws IOException
     */
    public static synchronized Environment getProcEnvironment() throws IOException {
        if (procEnvironment == null) {
            try
            {
                Method getenvs = System.class.getMethod( "getenv", null );
                Map env = (Map) getenvs.invoke( null, null );
                procEnvironment = new Environment( env );
            }
            catch ( NoSuchMethodException e )
            {
                // ok, just not on JDK 1.5
            }
            catch ( IllegalAccessException e )
            {
                LOG.warn( "Unexpected error obtaining environment - using JDK 1.4 method" );
            }
            catch ( InvocationTargetException e )
            {
                LOG.warn( "Unexpected error obtaining environment - using JDK 1.4 method" );
            }
        }

        if(procEnvironment == null) {
            procEnvironment = new Environment();
            BufferedReader in = runProcEnvCommand();

            String var = null;
            String line, lineSep = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                if (line.indexOf('=') == -1) {
                    // Chunk part of previous env var (UNIX env vars can
                    // contain embedded new lines).
                    if (var == null) {
                        var = lineSep + line;
                    } else {
                        var += lineSep + line;
                    }
                } else {
                    // New env var...append the previous one if we have it.
                    if (var != null) {
                        procEnvironment.addVariable(EnvironmentVariable
                                .createEnvironmentVariable(var));
                    }
                    var = line;
                }
            }
            // Since we "look ahead" before adding, there's one last env var.
            if (var != null) {
                procEnvironment.addVariable(EnvironmentVariable
                        .createEnvironmentVariable(var));
            }
        }
        return procEnvironment;
    }

    /**
     * @return
     * @throws IOException
     */
    protected static BufferedReader runProcEnvCommand() throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Execute exe = new Execute(new PumpStreamHandler(out));<commit_msg>Fixing 36705: "small refactor of Environment for style" Patch by <NAME>.<commit_after>/* 
 * Copyright 2005  The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package org.apache.commons.exec.environment;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.CommandLineImpl;
import org.apache.commons.exec.Execute;
import org.apache.commons.exec.OS;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Wrapper for environment variables.
 * @todo change from inheritence to delegation, implement map
 */
public class Environment extends HashMap {

    private static Log LOG = LogFactory.getLog(Environment.class);
    /**
     * TODO move this and other final static / constants into a constants class ?
     */
    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    public static Environment createEnvironment() {
        if (OS.isFamilyOpenVms()) {
            return new OpenVmsEnvironment();
        } else {
            return new Environment();
        }
    }

    public static Environment createEnvironment(String[] envVars) {
        Environment env = createEnvironment();

        if(envVars != null) {
            for (int i = 0; i < envVars.length; i++) {
                env.addVariable(EnvironmentVariable
                        .createEnvironmentVariable(envVars[i]));
            }
        }
        return env;
    }

    /**
     * Comment for <code>serialVersionUID</code>
     */
    private static final long serialVersionUID = 3256443594801165364L;

    private static Environment procEnvironment;

    /**
     * Default constructor, creates an empty environment
     */
    protected Environment() {
    }

    /**
     * Creates an environment from a @link Map of @link String
     * keys and values.
     * 
     * @param env A map containg the environment variable name
     * as @link String key and the variable value as @link String 
     * value 
     */
    protected Environment(Map env) {
        this();

        Set entries = env.entrySet();
        for (Iterator iter = entries.iterator(); iter.hasNext();) {
            Map.Entry entry = (Map.Entry) iter.next();
            addVariable((String) entry.getKey(),
                        (String) entry.getValue());
        }
    }

    /**
     * add a variable. Validity checking is <i>not</i> performed at this point.
     * Duplicates are not caught either.
     * 
     * @param var
     *            new variable.
     */
    public void addVariable(final EnvironmentVariable var) {
        put(var.getKey(), var);
    }

    public void addVariable(final String key, final String value) {
        put(key, EnvironmentVariable.createEnvironmentVariable(key, value));
    }

    /**
     * get the variable list as an array
     * 
     * @return array of key=value assignment strings
     */
    public String[] getVariables() {
        if (size() == 0) {
            return null;
        }
        String[] result = new String[size()];
        int i = 0;
        for (Iterator iter = entrySet().iterator(); iter.hasNext();) {
            Map.Entry entry = (Map.Entry) iter.next();

            result[i] = ((EnvironmentVariable) entry.getValue()).toString();
            i++;
        }
        return result;
    }

    /**
     * Find the list of environment variables for this process.
     * 
     * @return a vector containing the environment variables the vector elements
     *         are strings formatted like variable = value
     * @throws IOException
     */
    public static synchronized Environment getProcEnvironment() throws IOException {
        if (procEnvironment == null) {
            try {
                Method getenvs = System.class.getMethod( "getenv", null );
                Map env = (Map) getenvs.invoke( null, null );
                procEnvironment = new Environment( env );
            } catch ( NoSuchMethodException e ) {
                // ok, just not on JDK 1.5
            } catch ( IllegalAccessException e ) {
                LOG.warn( "Unexpected error obtaining environment - using JDK 1.4 method" );
            } catch ( InvocationTargetException e ) {
                LOG.warn( "Unexpected error obtaining environment - using JDK 1.4 method" );
            }
        }

        if(procEnvironment == null) {
            procEnvironment = new Environment();
            BufferedReader in = runProcEnvCommand();

            String var = null;
            String line;
            while ((line = in.readLine()) != null) {
                if (line.indexOf('=') == -1) {
                    // Chunk part of previous env var (UNIX env vars can
                    // contain embedded new lines).
                    if (var == null) {
                        var = LINE_SEPARATOR + line;
                    } else {
                        var += LINE_SEPARATOR + line;
                    }
                } else {
                    // New env var...append the previous one if we have it.
                    if (var != null) {
                        procEnvironment.addVariable(EnvironmentVariable
                                .createEnvironmentVariable(var));
                    }
                    var = line;
                }
            }
            // Since we "look ahead" before adding, there's one last env var.
            if (var != null) {
                procEnvironment.addVariable(EnvironmentVariable
                        .createEnvironmentVariable(var));
            }
        }
        return procEnvironment;
    }

    /**
     * @return
     * @throws IOException
     */
    protected static BufferedReader runProcEnvCommand() throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Execute exe = new Execute(new PumpStreamHandler(out));
{'fraction_non_alphanumeric': 0.09339678762641285, 'fraction_numerical': 0.005874479476502082, 'mean_word_length': 1.9428884026258206, 'pattern_counts': {'":': 0, '<': 14, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, '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': '2892660', 'n_tokens_mistral': 3425, 'n_tokens_neox': 3272, 'n_words': 1067}