Skip to content

Commit

Permalink
Removed dependency on 'org.apache.commons.lang' (openhab#1433)
Browse files Browse the repository at this point in the history
Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de>
  • Loading branch information
cweitkamp committed Apr 22, 2020
1 parent e17046e commit d371a34
Show file tree
Hide file tree
Showing 86 changed files with 249 additions and 230 deletions.
Expand Up @@ -28,7 +28,6 @@
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.audio.AudioException;
Expand Down Expand Up @@ -121,13 +120,23 @@ protected void deactivate() {
}
}

private String substringAfterLast(String str, String separator) {
int index = str.lastIndexOf(separator);
return index == -1 || index == str.length() - separator.length() ? ""
: str.substring(index + separator.length());
}

private String substringBefore(String str, String separator) {
int index = str.indexOf(separator);
return index == -1 ? str : str.substring(0, index);
}

@Override
protected void doGet(@NonNullByDefault({}) HttpServletRequest req, @NonNullByDefault({}) HttpServletResponse resp)
throws ServletException, IOException {
removeTimedOutStreams();

final String streamId = StringUtils.substringBefore(StringUtils.substringAfterLast(req.getRequestURI(), "/"),
".");
final String streamId = substringBefore(substringAfterLast(req.getRequestURI(), "/"), ".");

try (final InputStream stream = prepareInputStream(streamId, resp)) {
if (stream == null) {
Expand Down
Expand Up @@ -25,7 +25,6 @@

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.UrlEncoded;
import org.openhab.core.auth.client.oauth2.AccessTokenRefreshListener;
import org.openhab.core.auth.client.oauth2.AccessTokenResponse;
Expand Down Expand Up @@ -302,7 +301,8 @@ public AccessTokenResponse refreshToken() throws OAuthException, IOException, OA
persistedParams.scope, Boolean.TRUE.equals(persistedParams.supportsBasicAuth));

// The service may not return the refresh token so use the last refresh token otherwise it's not stored.
if (StringUtil.isBlank(accessTokenResponse.getRefreshToken())) {
String refreshToken = accessTokenResponse.getRefreshToken();
if (refreshToken == null || refreshToken.isBlank()) {
accessTokenResponse.setRefreshToken(lastAccessToken.getRefreshToken());
}
// store it
Expand Down
Expand Up @@ -21,7 +21,6 @@
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.audio.AudioManager;
Expand Down Expand Up @@ -114,8 +113,10 @@ private List<ParameterOption> getSoundOptions() {
if (soundsDir.isDirectory()) {
for (String fileName : soundsDir.list()) {
if (fileName.contains(".") && !fileName.startsWith(".")) {
String soundName = StringUtils.capitalize(fileName.substring(0, fileName.lastIndexOf(".")));
options.add(new ParameterOption(fileName, soundName));
String soundName = fileName.substring(0, fileName.lastIndexOf("."));
String capitalizedSoundName = soundName.substring(0, 1).toUpperCase()
+ soundName.substring(1).toLowerCase();
options.add(new ParameterOption(fileName, capitalizedSoundName));
}
}
}
Expand Down
Expand Up @@ -21,7 +21,6 @@

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.automation.RuleRegistry;
Expand Down Expand Up @@ -90,7 +89,6 @@ public DefaultScriptScopeProvider(final @Reference ItemRegistry itemRegistry,

elements.put("State", State.class);
elements.put("Command", Command.class);
elements.put("StringUtils", StringUtils.class);
elements.put("URLEncoder", URLEncoder.class);
elements.put("FileUtils", FileUtils.class);
elements.put("FilenameUtils", FilenameUtils.class);
Expand Down
Expand Up @@ -17,8 +17,8 @@
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
Expand Down Expand Up @@ -179,7 +179,7 @@ protected void unsetRuleManager(RuleManager ruleManager) {
@Override
public void execute(String[] args, Console console) {
if (args.length == 0) {
console.println(StringUtils.join(getUsages(), "\n"));
console.println(getUsages().stream().collect(Collectors.joining("\n")));
return;
}

Expand Down
Expand Up @@ -16,8 +16,8 @@
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.openhab.core.config.core.ConfigConstants;
import org.osgi.framework.FrameworkUtil;

Expand All @@ -34,6 +34,17 @@ public class OpenHAB {
/** the configuraton parameter name used for the base package */
public static final String CFG_PACKAGE = "package";

private static String substringAfterLast(String str, String separator) {
int index = str.lastIndexOf(separator);
return index == -1 || index == str.length() - separator.length() ? ""
: str.substring(index + separator.length());
}

private static String substringBeforeLast(String str, String separator) {
int index = str.lastIndexOf(separator);
return index == -1 ? str : str.substring(0, index);
}

/**
* Returns the current openHAB version, retrieving the information from the core bundle version.
*
Expand All @@ -42,18 +53,18 @@ public class OpenHAB {
public static String getVersion() {
String versionString = FrameworkUtil.getBundle(OpenHAB.class).getVersion().toString();
// if the version string contains a "snapshot" qualifier, remove it!
if (StringUtils.countMatches(versionString, ".") == 3) {
String qualifier = StringUtils.substringAfterLast(versionString, ".");
if (StringUtils.isNumeric(qualifier) || "qualifier".equals(qualifier)) {
versionString = StringUtils.substringBeforeLast(versionString, ".");
if (versionString.chars().filter(ch -> ch == '.').count() == 3) {
final Pattern pattern = Pattern.compile("\\d+(\\.\\d+)?");
String qualifier = substringAfterLast(versionString, ".");
if (pattern.matcher(qualifier).matches() || "qualifier".equals(qualifier)) {
versionString = substringBeforeLast(versionString, ".");
}
}
return versionString;
}

public static String buildString() {
Properties prop = new Properties();

Path versionFilePath = Paths.get(ConfigConstants.getUserDataFolder(), "etc", "version.properties");
try (FileInputStream fis = new FileInputStream(versionFilePath.toFile())) {
prop.load(fis);
Expand Down
Expand Up @@ -13,6 +13,7 @@
package org.openhab.core.config.core.internal;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.math.BigDecimal;
Expand All @@ -23,7 +24,6 @@
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.reflect.FieldUtils;
import org.eclipse.jdt.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -58,8 +58,9 @@ public class ConfigMapper {
public static <T> @Nullable T as(Map<String, Object> properties, Class<T> configurationClass) {
T configuration = null;
try {
configuration = configurationClass.newInstance();
} catch (InstantiationException | IllegalAccessException ex) {
configuration = configurationClass.getConstructor().newInstance();
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
return null;
}

Expand Down Expand Up @@ -98,16 +99,22 @@ public class ConfigMapper {
value = objectConvert(value, type);
LOGGER.trace("Setting value ({}) {} to field '{}' in configuration class {}", type.getSimpleName(),
value, fieldName, configurationClass.getName());
FieldUtils.writeField(configuration, fieldName, value, true);

} catch (Exception ex) {
writeField(configuration, fieldName, value, true);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
LOGGER.warn("Could not set field value for field '{}': {}", fieldName, ex.getMessage(), ex);
}
}

return configuration;
}

private static void writeField(Object target, String fieldName, Object value, boolean forceAccess)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Field field = target.getClass().getDeclaredField(fieldName);
field.setAccessible(forceAccess);
field.set(target, value);
}

/**
* Return fields of the given class as well as all super classes.
*
Expand Down
Expand Up @@ -30,7 +30,6 @@
import java.util.stream.Collectors;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.config.core.ConfigConstants;
Expand Down Expand Up @@ -255,6 +254,16 @@ public int compare(File left, File right) {
storeCurrentExclusivePIDList();
}

private String substringBefore(String str, String separator) {
int index = str.indexOf(separator);
return index == -1 ? str : str.substring(0, index);
}

private String substringBeforeLast(String str, String separator) {
int index = str.lastIndexOf(separator);
return index == -1 ? str : str.substring(0, index);
}

/**
* The filename of a given configuration file is assumed to be the service PID. If the filename
* without extension contains ".", we assume it is the fully qualified name.
Expand All @@ -263,7 +272,7 @@ public int compare(File left, File right) {
* @return The PID
*/
private String pidFromFilename(File configFile) {
String filenameWithoutExt = StringUtils.substringBeforeLast(configFile.getName(), ".");
String filenameWithoutExt = substringBeforeLast(configFile.getName(), ".");
if (filenameWithoutExt.contains(".")) {
// it is a fully qualified namespace
return filenameWithoutExt;
Expand Down Expand Up @@ -412,9 +421,9 @@ private ParseLineResult parseLine(final String filePath, final String line) {
}

String pid = null; // no override of the pid is default
String key = StringUtils.substringBefore(trimmedLine, DEFAULT_VALUE_DELIMITER);
String key = substringBefore(trimmedLine, DEFAULT_VALUE_DELIMITER);
if (key.contains(DEFAULT_PID_DELIMITER)) {
pid = StringUtils.substringBefore(key, DEFAULT_PID_DELIMITER);
pid = substringBefore(key, DEFAULT_PID_DELIMITER);
trimmedLine = trimmedLine.substring(pid.length() + 1);
pid = pid.trim();
// PID is not fully qualified, so prefix with namespace
Expand All @@ -423,7 +432,7 @@ private ParseLineResult parseLine(final String filePath, final String line) {
}
}
if (!trimmedLine.isEmpty() && trimmedLine.substring(1).contains(DEFAULT_VALUE_DELIMITER)) {
String property = StringUtils.substringBefore(trimmedLine, DEFAULT_VALUE_DELIMITER);
String property = substringBefore(trimmedLine, DEFAULT_VALUE_DELIMITER);
String value = trimmedLine.substring(property.length() + 1).trim();
if (value.startsWith(DEFAULT_LIST_STARTING_CHARACTER) && value.endsWith(DEFAULT_LIST_ENDING_CHARACTER)) {
logger.debug("Found list in value '{}'", value);
Expand Down
Expand Up @@ -13,15 +13,14 @@
package org.openhab.core.extension.sample.internal;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.openhab.core.events.Event;
import org.openhab.core.events.EventPublisher;
import org.openhab.core.extension.Extension;
Expand Down Expand Up @@ -71,9 +70,11 @@ protected void activate() {
for (int i = 0; i < 10; i++) {
String id = type.getId() + Integer.toString(i);
boolean installed = Math.random() > 0.5;
String name = RandomStringUtils.randomAlphabetic(5);
String label = name + " " + StringUtils.capitalize(type.getId());
byte[] array = new byte[5];
new Random().nextBytes(array);
String name = new String(array, StandardCharsets.UTF_8);
String typeId = type.getId();
String label = name + " " + typeId.substring(0, 1).toUpperCase() + typeId.substring(1).toLowerCase();
String version = "1.0";
String link = (Math.random() < 0.5) ? null : "http://lmgtfy.com/?q=" + name;
String description = createDescription();
Expand All @@ -97,7 +98,7 @@ private String createRandomColor() {
}

private String createDescription() {
int index = StringUtils.indexOf(LOREM_IPSUM, ' ', RANDOM.nextInt(LOREM_IPSUM.length()));
int index = LOREM_IPSUM.indexOf(" ", RANDOM.nextInt(LOREM_IPSUM.length()));
if (index < 0) {
index = LOREM_IPSUM.length();
}
Expand Down
Expand Up @@ -20,7 +20,6 @@
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.openhab.core.config.core.ConfigConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -55,7 +54,7 @@ public static synchronized String get() {
writeFile(file, uuid);
} else {
uuid = readFirstLine(file);
if (StringUtils.isNotEmpty(uuid)) {
if (uuid != null && !uuid.isEmpty()) {
LOGGER.debug("UUID '{}' has been restored from file '{}'", file.getAbsolutePath(), uuid);
} else {
uuid = java.util.UUID.randomUUID().toString();
Expand Down
Expand Up @@ -21,7 +21,6 @@
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.commons.lang.StringUtils;
import org.eclipse.osgi.framework.console.CommandInterpreter;
import org.eclipse.osgi.framework.console.CommandProvider;
import org.openhab.core.io.console.Console;
Expand Down Expand Up @@ -93,7 +92,7 @@ public Object _smarthome(final CommandInterpreter interpreter) {
final List<String> argsList = new ArrayList<>();
while (true) {
final String narg = interpreter.nextArgument();
if (!StringUtils.isEmpty(narg)) {
if (narg != null && !narg.isEmpty()) {
argsList.add(narg);
} else {
break;
Expand Down
Expand Up @@ -28,7 +28,6 @@
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpProxy;
import org.eclipse.jetty.client.ProxyConfiguration;
Expand Down Expand Up @@ -195,7 +194,7 @@ private static ContentResponse executeUrlAndGetReponse(String httpMethod, String

HttpProxy proxy = null;
// Only configure a proxy if a host is provided
if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) {
if (proxyHost != null && !proxyHost.isBlank() && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) {
AuthenticationStore authStore = httpClient.getAuthenticationStore();
ProxyConfiguration proxyConfig = httpClient.getProxyConfiguration();
List<Proxy> proxies = proxyConfig.getProxies();
Expand Down Expand Up @@ -274,7 +273,7 @@ private static ProxyParams prepareProxyParams() {
if ("true".equalsIgnoreCase(proxySet)) {
proxyParams.proxyHost = System.getProperty("http.proxyHost");
String proxyPortString = System.getProperty("http.proxyPort");
if (StringUtils.isNotBlank(proxyPortString)) {
if (proxyPortString != null && !proxyPortString.isBlank()) {
try {
proxyParams.proxyPort = Integer.valueOf(proxyPortString);
} catch (NumberFormatException e) {
Expand All @@ -299,7 +298,7 @@ private static ProxyParams prepareProxyParams() {
* <code>nonProxyHosts</code>-list and <code>true</code> otherwise
*/
private static boolean shouldUseProxy(String urlString, String nonProxyHosts) {
if (StringUtils.isNotBlank(nonProxyHosts)) {
if (nonProxyHosts != null && !nonProxyHosts.isBlank()) {
String givenHost = urlString;

try {
Expand Down

0 comments on commit d371a34

Please sign in to comment.