[LANG-1393] Add API SystemUtils.String getEnvironmentVariable(final

String name, final String defaultValue).
This commit is contained in:
Gary Gregory 2018-04-20 08:55:32 -06:00
parent 8e3ec1722b
commit efba54d35f
3 changed files with 46 additions and 0 deletions

View File

@ -59,6 +59,7 @@ The <action> type attribute can be add,update,fix,remove.
<action issue="LANG-1372" type="add" dev="pschumacher" due-to="Sérgio Ozaki">Add ToStringSummary annotation</action>
<action issue="LANG-1356" type="add" dev="pschumacher" due-to="Yathos UG">Add bypass option for classes to recursive and reflective EqualsBuilder</action>
<action issue="LANG-1391" type="add" dev="ggregory" due-to="Sauro Matulli, Oleg Chubaryov">Improve Javadoc for StringUtils.isAnyEmpty(null)</action>
<action issue="LANG-1393" type="add" dev="ggregory" due-to="Gary Gregory">Add API SystemUtils.String getEnvironmentVariable(final String name, final String defaultValue)</action>
</release>
<release version="3.7" date="2017-11-04" description="New features and bug fixes. Requires Java 7, supports Java 8, 9, 10.">

View File

@ -1605,6 +1605,33 @@ private static String getSystemProperty(final String property) {
}
}
/**
* <p>
* Gets an environment variable, defaulting to {@code defaultValue} if the variable cannot be read.
* </p>
* <p>
* If a {@code SecurityException} is caught, the return value is {@code defaultValue} and a message is written to
* {@code System.err}.
* </p>
*
* @param name
* the environment variable name
* @param defaultValue
* the default value
* @return the environment variable value or {@code defaultValue} if a security problem occurs
* @since 3.7
*/
public static String getEnvironmentVariable(final String name, final String defaultValue) {
try {
final String value = System.getenv(name);
return value == null ? defaultValue : value;
} catch (final SecurityException ex) {
// we are not allowed to look at this property
System.err.println("Caught a SecurityException reading the environment variable '" + name + "'.");
return defaultValue;
}
}
/**
* <p>
* Gets the user directory as a {@code File}.

View File

@ -40,6 +40,7 @@
import java.lang.reflect.Modifier;
import java.util.Locale;
import org.junit.Assert;
import org.junit.Test;
/**
@ -59,6 +60,23 @@ public void testConstructor() {
assertFalse(Modifier.isFinal(SystemUtils.class.getModifiers()));
}
@Test
public void testGetEnvironmentVariableAbsent() {
final String name = "THIS_ENV_VAR_SHOULD_NOT_EXIST_FOR_THIS_TEST_TO_PASS";
final String expected = System.getenv(name);
Assert.assertNull(expected);
final String value = SystemUtils.getEnvironmentVariable(name, "DEFAULT");
assertEquals("DEFAULT", value);
}
@Test
public void testGetEnvironmentVariablePresent() {
final String name = "PATH";
final String expected = System.getenv(name);
final String value = SystemUtils.getEnvironmentVariable(name, null);
assertEquals(expected, value);
}
@Test
public void testGetHostName() {
final String hostName = SystemUtils.getHostName();