Skip to content

Commit 648900e

Browse files
authored
Use Static ObjectMappers Instead of Instances (Azure#23639)
Use Static ObjectMappers Instead of Instances
1 parent d8ece7c commit 648900e

File tree

27 files changed

+168
-153
lines changed

27 files changed

+168
-153
lines changed

sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import com.azure.core.util.CoreUtils;
2222
import com.azure.core.util.logging.ClientLogger;
2323
import com.azure.core.util.serializer.JacksonAdapter;
24+
import com.azure.core.util.serializer.SerializerAdapter;
2425
import com.azure.data.appconfiguration.implementation.ConfigurationSettingJsonDeserializer;
2526
import com.azure.data.appconfiguration.implementation.ConfigurationSettingJsonSerializer;
2627
import com.azure.data.appconfiguration.implementation.SyncTokenPolicy;
@@ -60,13 +61,23 @@ public final class ConfigurationAsyncClient {
6061
// Please see <a href=https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/azure-services-resource-providers>here</a>
6162
// for more information on Azure resource provider namespaces.
6263
private static final String APP_CONFIG_TRACING_NAMESPACE_VALUE = "Microsoft.AppConfiguration";
63-
6464
private static final String ETAG_ANY = "*";
65+
66+
private static final SerializerAdapter SERIALIZER_ADAPTER;
67+
6568
private final String serviceEndpoint;
6669
private final ConfigurationService service;
6770
private final String apiVersion;
6871
private final SyncTokenPolicy syncTokenPolicy;
6972

73+
static {
74+
JacksonAdapter jacksonAdapter = new JacksonAdapter();
75+
jacksonAdapter.serializer().registerModule(ConfigurationSettingJsonSerializer.getModule());
76+
jacksonAdapter.serializer().registerModule(ConfigurationSettingJsonDeserializer.getModule());
77+
78+
SERIALIZER_ADAPTER = jacksonAdapter;
79+
}
80+
7081
/**
7182
* Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}.
7283
* Each service call goes through the {@code pipeline}.
@@ -79,11 +90,7 @@ public final class ConfigurationAsyncClient {
7990
ConfigurationAsyncClient(String serviceEndpoint, HttpPipeline pipeline, ConfigurationServiceVersion version,
8091
SyncTokenPolicy syncTokenPolicy) {
8192

82-
final JacksonAdapter jacksonAdapter = new JacksonAdapter();
83-
jacksonAdapter.serializer().registerModule(ConfigurationSettingJsonSerializer.getModule());
84-
jacksonAdapter.serializer().registerModule(ConfigurationSettingJsonDeserializer.getModule());
85-
86-
this.service = RestProxy.create(ConfigurationService.class, pipeline, jacksonAdapter);
93+
this.service = RestProxy.create(ConfigurationService.class, pipeline, SERIALIZER_ADAPTER);
8794
this.serviceEndpoint = serviceEndpoint;
8895
this.apiVersion = version.getVersion();
8996
this.syncTokenPolicy = syncTokenPolicy;

sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/implementation/ConfigurationSettingJsonDeserializer.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ public final class ConfigurationSettingJsonDeserializer extends JsonDeserializer
5757
private static final JacksonAdapter MAPPER;
5858
private static final SimpleModule MODULE;
5959
static {
60-
MAPPER = new JacksonAdapter();
60+
MAPPER = (JacksonAdapter) JacksonAdapter.createDefaultSerializerAdapter();
6161
MODULE = new SimpleModule()
6262
.addDeserializer(ConfigurationSetting.class, new ConfigurationSettingJsonDeserializer())
6363
.addDeserializer(SecretReferenceConfigurationSetting.class,

sdk/appconfiguration/azure-spring-cloud-appconfiguration-config-web/src/main/java/com/azure/spring/cloud/config/web/pushbusrefresh/AppConfigurationBusRefreshEndpoint.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public final class AppConfigurationBusRefreshEndpoint extends AbstractBusEndpoin
3838

3939
private static final Logger LOGGER = LoggerFactory.getLogger(AppConfigurationBusRefreshEndpoint.class);
4040

41-
private final ObjectMapper objectmapper = new ObjectMapper();
41+
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
4242

4343
private final AppConfigurationProperties appConfiguration;
4444

@@ -60,10 +60,10 @@ public AppConfigurationBusRefreshEndpoint(ApplicationEventPublisher context, Str
6060
/**
6161
* Checks a HttpServletRequest to see if it is a refresh event. Validates token information. If request is a
6262
* validation request returns validation code.
63-
*
63+
*
6464
* @param request Request checked for refresh.
6565
* @param response Response for request.
66-
* @param allRequestParams request parameters needs to contain validation token.
66+
* @param allRequestParams request parameters needs to contain validation token.
6767
* @return 200 if refresh event triggered. 500 if invalid for any reason. Validation response if requested.
6868
* @throws IOException Unable to parse request info for validation.
6969
*/
@@ -73,7 +73,7 @@ public String refresh(HttpServletRequest request, HttpServletResponse response,
7373
@RequestParam Map<String, String> allRequestParams) throws IOException {
7474
String reference = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
7575

76-
JsonNode kvReference = objectmapper.readTree(reference);
76+
JsonNode kvReference = OBJECT_MAPPER.readTree(reference);
7777

7878
AppConfigurationEndpoint validation;
7979
try {

sdk/appconfiguration/azure-spring-cloud-appconfiguration-config-web/src/main/java/com/azure/spring/cloud/config/web/pushrefresh/AppConfigurationRefreshEndpoint.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public final class AppConfigurationRefreshEndpoint implements ApplicationEventPu
3737

3838
private final ContextRefresher contextRefresher;
3939

40-
private final ObjectMapper objectmapper = new ObjectMapper();
40+
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
4141

4242
private final AppConfigurationProperties appConfiguration;
4343

@@ -59,10 +59,10 @@ public AppConfigurationRefreshEndpoint(ContextRefresher contextRefresher,
5959
/**
6060
* Checks a HttpServletRequest to see if it is a refresh event. Validates token information. If request is a
6161
* validation request returns validation code.
62-
*
62+
*
6363
* @param request Request checked for refresh.
6464
* @param response Response for request.
65-
* @param allRequestParams request parameters needs to contain validation token.
65+
* @param allRequestParams request parameters needs to contain validation token.
6666
* @return 200 if refresh event triggered. 500 if invalid for any reason. Validation response if requested.
6767
* @throws IOException Unable to parse request info for validation.
6868
*/
@@ -73,7 +73,7 @@ public String refresh(HttpServletRequest request, HttpServletResponse response,
7373

7474
String reference = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
7575

76-
JsonNode kvReference = objectmapper.readTree(reference);
76+
JsonNode kvReference = OBJECT_MAPPER.readTree(reference);
7777
AppConfigurationEndpoint validation = new AppConfigurationEndpoint(kvReference, appConfiguration.getStores(),
7878
allRequestParams);
7979

sdk/appconfiguration/azure-spring-cloud-appconfiguration-config/src/main/java/com/azure/spring/cloud/config/AppConfigurationPropertySource.java

Lines changed: 32 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,6 @@
22
// Licensed under the MIT License.
33
package com.azure.spring.cloud.config;
44

5-
import static com.azure.spring.cloud.config.AppConfigurationConstants.FEATURE_FLAG_PREFIX;
6-
import static com.azure.spring.cloud.config.AppConfigurationConstants.FEATURE_MANAGEMENT_KEY;
7-
import static java.util.Collections.emptyList;
8-
import static java.util.stream.Collectors.toMap;
9-
10-
import java.io.IOException;
11-
import java.net.URI;
12-
import java.net.URISyntaxException;
13-
import java.util.Arrays;
14-
import java.util.Collections;
15-
import java.util.Date;
16-
import java.util.HashMap;
17-
import java.util.LinkedHashMap;
18-
import java.util.List;
19-
import java.util.Map;
20-
import java.util.Map.Entry;
21-
import java.util.Set;
22-
import java.util.stream.IntStream;
23-
24-
import org.slf4j.Logger;
25-
import org.slf4j.LoggerFactory;
26-
import org.springframework.core.env.EnumerablePropertySource;
27-
import org.springframework.util.ReflectionUtils;
28-
import org.springframework.util.StringUtils;
29-
305
import com.azure.core.http.rest.PagedIterable;
316
import com.azure.data.appconfiguration.ConfigurationClient;
327
import com.azure.data.appconfiguration.models.ConfigurationSetting;
@@ -47,13 +22,35 @@
4722
import com.fasterxml.jackson.databind.MapperFeature;
4823
import com.fasterxml.jackson.databind.ObjectMapper;
4924
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
25+
import org.slf4j.Logger;
26+
import org.slf4j.LoggerFactory;
27+
import org.springframework.core.env.EnumerablePropertySource;
28+
import org.springframework.util.ReflectionUtils;
29+
import org.springframework.util.StringUtils;
30+
31+
import java.io.IOException;
32+
import java.net.URI;
33+
import java.net.URISyntaxException;
34+
import java.util.Arrays;
35+
import java.util.Collections;
36+
import java.util.Date;
37+
import java.util.HashMap;
38+
import java.util.LinkedHashMap;
39+
import java.util.List;
40+
import java.util.Map;
41+
import java.util.Map.Entry;
42+
import java.util.Set;
43+
import java.util.stream.IntStream;
44+
45+
import static com.azure.spring.cloud.config.AppConfigurationConstants.FEATURE_FLAG_PREFIX;
46+
import static com.azure.spring.cloud.config.AppConfigurationConstants.FEATURE_MANAGEMENT_KEY;
47+
import static java.util.Collections.emptyList;
48+
import static java.util.stream.Collectors.toMap;
5049

5150
/**
5251
* Azure App Configuration PropertySource unique per Store Label(Profile) combo.
53-
*
54-
* <p>
55-
* i.e. If connecting to 2 stores and have 2 labels set 4 AppConfigurationPropertySources need to be created.
56-
* </p>
52+
*
53+
* <p>i.e. If connecting to 2 stores and have 2 labels set 4 AppConfigurationPropertySources need to be created.</p>
5754
*/
5855
public final class AppConfigurationPropertySource extends EnumerablePropertySource<ConfigurationClient> {
5956

@@ -78,6 +75,9 @@ public final class AppConfigurationPropertySource extends EnumerablePropertySour
7875
private static final ObjectMapper CASE_INSENSITIVE_MAPPER = new ObjectMapper()
7976
.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
8077

78+
private static final ObjectMapper FEATURE_MAPPER = new ObjectMapper()
79+
.setPropertyNamingStrategy(PropertyNamingStrategies.KEBAB_CASE);
80+
8181
private final AppConfigurationStoreSelects selectedKeys;
8282

8383
private final List<String> profiles;
@@ -212,7 +212,7 @@ FeatureSet initProperties(FeatureSet featureSet) throws IOException {
212212
/**
213213
* Given a Setting's Key Vault Reference stored in the Settings value, it will get its entry in Key Vault.
214214
*
215-
* @param value {"uri": "&lt;your-vault-url&gt;/secret/&lt;secret&gt;/&lt;version&gt;"}
215+
* @param secretReference {"uri": "&lt;your-vault-url&gt;/secret/&lt;secret&gt;/&lt;version&gt;"}
216216
* @return Key Vault Secret Value
217217
*/
218218
private String getKeyVaultEntry(SecretReferenceConfigurationSetting secretReference) {
@@ -254,10 +254,8 @@ private String getKeyVaultEntry(SecretReferenceConfigurationSetting secretRefere
254254
* @param featureSet Feature Flag info to be set to this property source.
255255
*/
256256
void initFeatures(FeatureSet featureSet) {
257-
ObjectMapper featureMapper = new ObjectMapper();
258-
featureMapper.setPropertyNamingStrategy(PropertyNamingStrategies.KEBAB_CASE);
259257
properties.put(FEATURE_MANAGEMENT_KEY,
260-
featureMapper.convertValue(featureSet.getFeatureManagement(), LinkedHashMap.class));
258+
FEATURE_MAPPER.convertValue(featureSet.getFeatureManagement(), LinkedHashMap.class));
261259
}
262260

263261
private FeatureSet addToFeatureSet(FeatureSet featureSet, PagedIterable<ConfigurationSetting> features, Date date)
@@ -282,10 +280,9 @@ private FeatureSet addToFeatureSet(FeatureSet featureSet, PagedIterable<Configur
282280
*
283281
* @param item Used to create Features before being converted to be set into properties.
284282
* @return Feature created from KeyValueItem
285-
* @throws IOException - If a ConfigurationSetting isn't of the feature flag content type.
286283
*/
287284
@SuppressWarnings("unchecked")
288-
private Object createFeature(FeatureFlagConfigurationSetting item) throws IOException {
285+
private Object createFeature(FeatureFlagConfigurationSetting item) {
289286
String key = getFeatureSimpleName(item);
290287
Feature feature = new Feature(key, item);
291288
Map<Integer, FeatureFlagFilter> featureEnabledFor = feature.getEnabledFor();

sdk/appconfiguration/azure-spring-cloud-appconfiguration-config/src/main/java/com/azure/spring/cloud/config/JsonConfigurationParser.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import com.fasterxml.jackson.databind.ObjectMapper;
1717

1818
final class JsonConfigurationParser {
19+
private static final ObjectMapper MAPPER = new ObjectMapper();
1920

2021
static boolean isJsonContentType(String contentType) {
2122
String acceptedMainType = "application";
@@ -45,8 +46,7 @@ static boolean isJsonContentType(String contentType) {
4546
static HashMap<String, Object> parseJsonSetting(ConfigurationSetting setting)
4647
throws JsonMappingException, JsonProcessingException {
4748
HashMap<String, Object> settings = new HashMap<String, Object>();
48-
ObjectMapper jsonMapper = new ObjectMapper();
49-
JsonNode json = jsonMapper.readTree(setting.getValue());
49+
JsonNode json = MAPPER.readTree(setting.getValue());
5050
parseSetting(setting.getKey(), json, settings);
5151
return settings;
5252
}

sdk/appconfiguration/azure-spring-cloud-feature-management/src/main/java/com/azure/spring/cloud/feature/manager/FeatureManager.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,13 @@ public class FeatureManager extends HashMap<String, Object> {
4545

4646
private Map<String, Boolean> onOff;
4747

48-
private ObjectMapper mapper = new ObjectMapper();
48+
private static final ObjectMapper MAPPER = new ObjectMapper()
49+
.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE);
4950

5051
public FeatureManager(FeatureManagementConfigProperties properties) {
5152
this.properties = properties;
5253
featureManagement = new HashMap<>();
5354
onOff = new HashMap<>();
54-
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE);
5555
}
5656

5757
/**
@@ -116,7 +116,7 @@ private void addToFeatures(Map<? extends String, ? extends Object> features, Str
116116
} else {
117117
Feature feature = null;
118118
try {
119-
feature = mapper.convertValue(featureKey, Feature.class);
119+
feature = MAPPER.convertValue(featureKey, Feature.class);
120120
} catch (IllegalArgumentException e) {
121121
LOGGER.error("Found invalid feature {} with value {}.", combined + key, featureKey.toString());
122122
}

sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/implementation/models/AttestationSignerImpl.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
*/
2727
@Fluent
2828
public class AttestationSignerImpl implements AttestationSigner {
29+
private static final ObjectMapper MAPPER = new ObjectMapper();
2930

3031
/**
3132
* Sets the signing certificate.
@@ -135,8 +136,7 @@ public static AttestationSigner fromJWK(JWK jwk) throws Error {
135136

136137
JsonWebKey jsonWebKey;
137138
try {
138-
ObjectMapper om = new ObjectMapper();
139-
jsonWebKey = om.readValue(serializedKey, JsonWebKey.class);
139+
jsonWebKey = MAPPER.readValue(serializedKey, JsonWebKey.class);
140140
} catch (JsonProcessingException e) {
141141
throw logger.logExceptionAsError(new RuntimeException(e.getMessage()));
142142
}

sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/implementation/models/AttestationTokenImpl.java

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@
6060
@Fluent
6161
@Immutable
6262
public class AttestationTokenImpl implements AttestationToken {
63+
private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter();
6364

6465
/**
6566
* Creates a new instance of an AttestationToken object.
@@ -102,15 +103,11 @@ public AttestationTokenImpl(String serializedToken) {
102103
if (payload.toString().length() == 0) {
103104
return null;
104105
} else {
105-
SerializerAdapter serializerAdapter = new JacksonAdapter();
106-
T t;
107-
108106
try {
109-
t = serializerAdapter.deserialize(payload.toString(), returnType, SerializerEncoding.JSON);
107+
return SERIALIZER_ADAPTER.deserialize(payload.toString(), returnType, SerializerEncoding.JSON);
110108
} catch (IOException e) {
111109
throw logger.logExceptionAsError(new RuntimeException(e.getMessage()));
112110
}
113-
return t;
114111
}
115112
}
116113

sdk/containerregistry/azure-containers-containerregistry/src/main/java/com/azure/containers/containerregistry/implementation/authentication/JsonWebToken.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import java.util.Base64;
1515

1616
class JsonWebToken {
17+
private static final ObjectMapper MAPPER = new ObjectMapper();
1718

1819
/**
1920
* Retrieves the expiration date from the specified JWT value.
@@ -42,11 +43,9 @@ public static OffsetDateTime retrieveExpiration(String jwtValue) {
4243

4344
byte[] jwtPayloadDecodedData = Base64.getDecoder().decode(jwtPayloadEncoded);
4445

45-
ObjectMapper mapper = new ObjectMapper();
46-
4746
JsonNode rootNode;
4847
try {
49-
rootNode = mapper.readTree(jwtPayloadDecodedData);
48+
rootNode = MAPPER.readTree(jwtPayloadDecodedData);
5049
} catch (IOException exception) {
5150
return null;
5251
}

0 commit comments

Comments
 (0)