All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.gradle.internal.nativeintegration.ReflectiveEnvironment Maven / Gradle / Ivy

There is a newer version: 8.11.1
Show newest version
/*
 * Copyright 2011 the original author or authors.
 *
 * 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.gradle.internal.nativeintegration;

import org.gradle.internal.os.OperatingSystem;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * Uses reflection to update private environment state
 */
public class ReflectiveEnvironment {

    public void unsetenv(String name) {
        Map map = getEnv();
        map.remove(name);
        if (OperatingSystem.current().isWindows()) {
            Map env2 = getWindowsEnv();
            env2.remove(name);
        }
    }

    public void setenv(String name, String value) {
        Map map = getEnv();
        map.put(name, value);
        if (OperatingSystem.current().isWindows()) {
            Map env2 = getWindowsEnv();
            env2.put(name, value);
        }
    }

    /**
     * Windows keeps an extra map with case insensitive keys. The map is used when the user calls {@link System#getenv(String)}
     */
    private Map getWindowsEnv() {
        try {
            Class sc = Class.forName("java.lang.ProcessEnvironment");
            Field caseinsensitive = sc.getDeclaredField("theCaseInsensitiveEnvironment");
            caseinsensitive.setAccessible(true);
            @SuppressWarnings("unchecked")
            Map result = (Map)caseinsensitive.get(null);
            return result;
        } catch (Exception e) {
            throw new NativeIntegrationException("Unable to get mutable windows case insensitive environment map", e);
        }
    }

    private Map getEnv() {
        try {
            Map theUnmodifiableEnvironment = System.getenv();
            Class cu = theUnmodifiableEnvironment.getClass();
            Field m = cu.getDeclaredField("m");
            m.setAccessible(true);
            @SuppressWarnings("unchecked")
            Map result = (Map)m.get(theUnmodifiableEnvironment);
            return result;
        } catch (Exception e) {
            throw new NativeIntegrationException("Unable to get mutable environment map", e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy