Simplify `UserAgentUtil`

This commit is contained in:
Jon Chambers 2025-04-15 16:41:51 -04:00 committed by Jon Chambers
parent f5e49b6db7
commit 05c74f1997
2 changed files with 12 additions and 32 deletions

View File

@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.util.ua;
import com.google.common.annotations.VisibleForTesting;
import com.vdurmont.semver4j.Semver;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -21,10 +20,10 @@ public class UserAgentUtil {
}
try {
final UserAgent standardUserAgent = parseStandardUserAgentString(userAgentString);
final Matcher matcher = STANDARD_UA_PATTERN.matcher(userAgentString);
if (standardUserAgent != null) {
return standardUserAgent;
if (matcher.matches()) {
return new UserAgent(ClientPlatform.valueOf(matcher.group(1).toUpperCase()), new Semver(matcher.group(2)), StringUtils.stripToNull(matcher.group(4)));
}
} catch (final Exception e) {
throw new UnrecognizedUserAgentException(e);
@ -32,15 +31,4 @@ public class UserAgentUtil {
throw new UnrecognizedUserAgentException();
}
@VisibleForTesting
static UserAgent parseStandardUserAgentString(final String userAgentString) {
final Matcher matcher = STANDARD_UA_PATTERN.matcher(userAgentString);
if (matcher.matches()) {
return new UserAgent(ClientPlatform.valueOf(matcher.group(1).toUpperCase()), new Semver(matcher.group(2)), StringUtils.stripToNull(matcher.group(4)));
}
return null;
}
}

View File

@ -13,28 +13,20 @@ import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import javax.annotation.Nullable;
class UserAgentUtilTest {
@ParameterizedTest
@MethodSource
void testParseBogusUserAgentString(final String userAgentString) {
assertThrows(UnrecognizedUserAgentException.class, () -> UserAgentUtil.parseUserAgentString(userAgentString));
}
@SuppressWarnings("unused")
private static Stream<String> testParseBogusUserAgentString() {
return Stream.of(
null,
"This is obviously not a reasonable User-Agent string.",
"Signal-Android/4.6-8.3.unreasonableversionstring-17"
);
}
@ParameterizedTest
@MethodSource("argumentsForTestParseStandardUserAgentString")
void testParseStandardUserAgentString(final String userAgentString, final UserAgent expectedUserAgent) {
assertEquals(expectedUserAgent, UserAgentUtil.parseStandardUserAgentString(userAgentString));
void testParseStandardUserAgentString(final String userAgentString, @Nullable final UserAgent expectedUserAgent)
throws UnrecognizedUserAgentException {
if (expectedUserAgent != null) {
assertEquals(expectedUserAgent, UserAgentUtil.parseUserAgentString(userAgentString));
} else {
assertThrows(UnrecognizedUserAgentException.class, () -> UserAgentUtil.parseUserAgentString(userAgentString));
}
}
private static Stream<Arguments> argumentsForTestParseStandardUserAgentString() {