Skip to content

Commit 103cf3a

Browse files
committed
refactor(RequestUtils): Add back logic to create most of User-Agent header
1 parent 85ce584 commit 103cf3a

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

src/main/java/com/ibm/cloud/sdk/core/util/RequestUtils.java

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,10 @@
2121
import java.io.InputStream;
2222
import java.io.UnsupportedEncodingException;
2323
import java.net.URLEncoder;
24+
import java.util.ArrayList;
2425
import java.util.Arrays;
2526
import java.util.HashMap;
27+
import java.util.List;
2628
import java.util.Map;
2729
import java.util.Properties;
2830
import java.util.logging.Level;
@@ -35,6 +37,9 @@
3537
public final class RequestUtils {
3638

3739
private static final Logger LOG = Logger.getLogger(RequestUtils.class.getName());
40+
private static final String[] properties =
41+
new String[] { "java.vendor", "java.version", "os.arch", "os.name", "os.version" };
42+
private static String userAgent;
3843

3944
private RequestUtils() {
4045
// This is a utility class - no instantiation allowed.
@@ -135,7 +140,7 @@ public static String join(Iterable<?> iterable, String separator) {
135140
return sb.toString();
136141
}
137142

138-
public static String loadCoreVersion() {
143+
private static String loadCoreVersion() {
139144
ClassLoader classLoader = RequestUtils.class.getClassLoader();
140145
InputStream inputStream = classLoader.getResourceAsStream("sdk-core-version.properties");
141146
Properties properties = new Properties();
@@ -149,6 +154,32 @@ public static String loadCoreVersion() {
149154
return properties.getProperty("version", "unknown-version");
150155
}
151156

157+
/**
158+
* Builds the user agent using System properties.
159+
*
160+
* @return the string that represents the user agent
161+
*/
162+
private static String buildUserAgent() {
163+
final List<String> details = new ArrayList<>();
164+
for (String propertyName : properties) {
165+
details.add(propertyName + "=" + System.getProperty(propertyName));
166+
}
167+
168+
return "ibm-java-sdk-core/" + loadCoreVersion() + " (" + RequestUtils.join(details, "; ") + ")";
169+
}
170+
171+
/**
172+
* Gets the user agent.
173+
*
174+
* @return the user agent
175+
*/
176+
public static synchronized String getUserAgent() {
177+
if (userAgent == null) {
178+
userAgent = buildUserAgent();
179+
}
180+
return userAgent;
181+
}
182+
152183
/**
153184
* Returns a request body that encapsulates the specified file qualified with the specified content type.
154185
*

0 commit comments

Comments
 (0)