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>
GitOrigin-RevId: d371a34
  • Loading branch information
cweitkamp authored and splatch committed Jul 11, 2023
1 parent e6cf72c commit 3757095
Show file tree
Hide file tree
Showing 55 changed files with 241 additions and 187 deletions.
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,15 @@

import static org.junit.Assert.*;

import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import org.apache.commons.lang.RandomStringUtils;
import org.junit.Before;
import org.junit.Test;

Expand All @@ -37,7 +38,11 @@ public class ExpiringCacheMapTest {
private static final String RESPONSE_1 = "ACTION 1";
private static final String RESPONSE_2 = "ACTION 2";

private static final Supplier<String> CACHE_ACTION = () -> RandomStringUtils.random(8);
private static final Supplier<String> CACHE_ACTION = () -> {
byte[] array = new byte[8];
new Random().nextBytes(array);
return new String(array, StandardCharsets.UTF_8);
};
private static final Supplier<String> PREDICTABLE_CACHE_ACTION_1 = () -> RESPONSE_1;
private static final Supplier<String> PREDICTABLE_CACHE_ACTION_2 = () -> RESPONSE_2;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@

import static org.junit.Assert.*;

import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import org.apache.commons.lang.RandomStringUtils;
import org.junit.Before;
import org.junit.Test;

Expand All @@ -28,7 +29,11 @@
*/
public class ExpiringCacheTest {
private static final long CACHE_EXPIRY = TimeUnit.SECONDS.toMillis(2);
private static final Supplier<String> CACHE_ACTION = () -> RandomStringUtils.random(8);
private static final Supplier<String> CACHE_ACTION = () -> {
byte[] array = new byte[8];
new Random().nextBytes(array);
return new String(array, StandardCharsets.UTF_8);
};

private ExpiringCache<String> subject;

Expand Down
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
import javax.measure.quantity.Temperature;
import javax.measure.spi.SystemOfUnits;

import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.i18n.LocaleProvider;
Expand Down Expand Up @@ -178,7 +177,7 @@ private void setMeasurementSystem(@Nullable String measurementSystem) {
private void setLocale(@Nullable String language, @Nullable String script, @Nullable String region,
@Nullable String variant) {
Locale oldLocale = this.locale;
if (StringUtils.isEmpty(language)) {
if (language == null || language.isEmpty()) {
// at least the language must be defined otherwise the system default locale is used
logger.debug("No language set, setting locale to 'null'.");
locale = null;
Expand Down Expand Up @@ -251,7 +250,7 @@ private void setLocation(final @Nullable String location) {

private void setTimeZone(final @Nullable String zoneId) {
ZoneId oldTimeZone = this.timeZone;
if (StringUtils.isBlank(zoneId)) {
if (zoneId == null || zoneId.isBlank()) {
timeZone = null;
} else {
try {
Expand Down
Loading

0 comments on commit 3757095

Please sign in to comment.