add telemetry in application insights (#322)

This commit is contained in:
Yunge Zhu 2018-05-03 19:54:10 -07:00 коммит произвёл GitHub
Родитель aea8de755b
Коммит 99174e518c
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
41 изменённых файлов: 430 добавлений и 90 удалений

Просмотреть файл

@ -4,6 +4,7 @@
Following [this instruction](http://blog.sonatype.com/2010/01/how-to-generate-pgp-signatures-with-maven/ ) to setup gpg key and publish it. save your passphrase.
1. python version >=3.5.
1. install necessary python packages: requests, xmltodict, jenkinsapi
1. run maven install locally. **Important** when do build please use profile `release` which will contains ai PROD instrument key. Please refer [code here](https://github.com/Microsoft/azure-spring-boot/blob/yungez-ai/azure-spring-boot-starters/azure-spring-boot-starter/pom.xml#L51-L73) for detail.
1. setup configuration in config.json
```
"targetFolder": "//path-to-your-local-to-copy-signed-jars",

Просмотреть файл

@ -53,6 +53,7 @@
<azure.media.version>0.9.7</azure.media.version>
<azure.servicebus.version>1.0.0</azure.servicebus.version>
<azure.spring.boot.version>2.0.2-SNAPSHOT</azure.spring.boot.version>
<azure.applicationinsights.version>1.0.9</azure.applicationinsights.version>
<spring.data.documentdb.version>2.0.1</spring.data.documentdb.version>
<microsoft.client-runtime.version>1.0.0</microsoft.client-runtime.version>
</properties>
@ -142,6 +143,11 @@
<artifactId>azure-servicebus</artifactId>
<version>${azure.servicebus.version}</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>applicationinsights-core</artifactId>
<version>${azure.applicationinsights.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>

Просмотреть файл

@ -12,18 +12,10 @@ import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import sample.aad.model.TodoItem;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.*;
import java.util.stream.Collectors;
@RestController

Просмотреть файл

@ -5,11 +5,7 @@
*/
package sample.aad.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.annotation.*;
import java.util.Objects;

Просмотреть файл

@ -5,12 +5,7 @@
*/
package sample.cloudfoundry.servicebus;
import com.microsoft.azure.servicebus.ExceptionPhase;
import com.microsoft.azure.servicebus.IMessage;
import com.microsoft.azure.servicebus.IMessageHandler;
import com.microsoft.azure.servicebus.Message;
import com.microsoft.azure.servicebus.MessageHandlerOptions;
import com.microsoft.azure.servicebus.QueueClient;
import com.microsoft.azure.servicebus.*;
import com.microsoft.azure.servicebus.primitives.ServiceBusException;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.slf4j.Logger;

Просмотреть файл

@ -9,15 +9,7 @@ package sample.mediaservices;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.services.media.MediaContract;
import com.microsoft.windowsazure.services.media.WritableBlobContainerContract;
import com.microsoft.windowsazure.services.media.models.AccessPolicy;
import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo;
import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission;
import com.microsoft.windowsazure.services.media.models.Asset;
import com.microsoft.windowsazure.services.media.models.AssetFile;
import com.microsoft.windowsazure.services.media.models.AssetInfo;
import com.microsoft.windowsazure.services.media.models.Locator;
import com.microsoft.windowsazure.services.media.models.LocatorInfo;
import com.microsoft.windowsazure.services.media.models.LocatorType;
import com.microsoft.windowsazure.services.media.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;

Просмотреть файл

@ -5,14 +5,7 @@
*/
package sample.servicebus;
import com.microsoft.azure.servicebus.ExceptionPhase;
import com.microsoft.azure.servicebus.IMessage;
import com.microsoft.azure.servicebus.IMessageHandler;
import com.microsoft.azure.servicebus.Message;
import com.microsoft.azure.servicebus.MessageHandlerOptions;
import com.microsoft.azure.servicebus.QueueClient;
import com.microsoft.azure.servicebus.SubscriptionClient;
import com.microsoft.azure.servicebus.TopicClient;
import com.microsoft.azure.servicebus.*;
import com.microsoft.azure.servicebus.primitives.ServiceBusException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;

Просмотреть файл

@ -57,4 +57,10 @@ private AADAuthenticationFilter aadAuthFilter;
* Role-based Authorization with annotation `@PreAuthorize("hasRole('GROUP_NAME')")`
* Role-based Authorization with method `isMemberOf()`
### Allow telemetry
Microsoft would like to collect data about how users use this Spring boot starter. Microsoft uses this information to improve our tooling experience. Participation is voluntary. If you don't want to participate, just simply disable it by setting below configuration in `application.properties`.
```
azure.mediaservices.allow-telemetry=false
```
Find more information about Azure Service Privacy Statement, please check [Microsoft Online Services Privacy Statement](https://www.microsoft.com/en-us/privacystatement/OnlineServices/Default.aspx).

Просмотреть файл

@ -31,4 +31,5 @@
<artifactId>spring-data-documentdb</artifactId>
</dependency>
</dependencies>
</project>

Просмотреть файл

@ -40,3 +40,10 @@ Add below alike code to auto-wire the `MediaContract` object. Then you can use i
private MediaContract mediaService;
```
### Allow telemetry
Microsoft would like to collect data about how users use this Spring boot starter. Microsoft uses this information to improve our tooling experience. Participation is voluntary. If you don't want to participate, just simply disable it by setting below configuration in `application.properties`.
```
azure.mediaservices.allow-telemetry=false
```
Find more information about Azure Service Privacy Statement, please check [Microsoft Online Services Privacy Statement](https://www.microsoft.com/en-us/privacystatement/OnlineServices/Default.aspx).

Просмотреть файл

@ -61,3 +61,13 @@ private SubscriptionClient subscriptionClient;
```
### Allow telemetry
Microsoft would like to collect data about how users use this Spring boot starter. Microsoft uses this information to improve our tooling experience. Participation is voluntary. If you don't want to participate, just simply disable it by setting below configuration in `application.properties`.
```
azure.servicebus.allow-telemetry=false
```
Find more information about Azure Service Privacy Statement, please check [Microsoft Online Services Privacy Statement](https://www.microsoft.com/en-us/privacystatement/OnlineServices/Default.aspx).

Просмотреть файл

@ -35,4 +35,42 @@
<artifactId>azure-spring-boot</artifactId>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/ApplicationInsights.xml</include>
</includes>
</resource>
</resources>
</build>
<profiles>
<profile>
<id>dev</id>
<activation>
<property>
<name>!release</name>
</property>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<ai.instrumentkey>fda156f5-2eb8-48ab-8a3c-3e06b3c64b49</ai.instrumentkey>
</properties>
</profile>
<profile>
<id>release</id>
<activation>
<property>
<name>release</name>
</property>
</activation>
<properties>
<ai.instrumentkey>d3278c59-22d7-4697-af8c-ff0077e3b4e9</ai.instrumentkey>
</properties>
</profile>
</profiles>
</project>

Просмотреть файл

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings" schemaVersion="2014-05-30">
<!-- The key from the portal: -->
<InstrumentationKey>${ai.instrumentkey}</InstrumentationKey>
<!-- HTTP request component (not required for bare API) -->
<TelemetryModules>
</TelemetryModules>
<!-- Events correlation (not required for bare API) -->
<!-- These initializers add context data to each event -->
<TelemetryInitializers>
</TelemetryInitializers>
</ApplicationInsights>

Просмотреть файл

@ -30,3 +30,10 @@ Add below alike code to auto-wire the `CloudStorageAccount` object. Then you can
private CloudStorageAccount storageAccount;
```
### Allow telemetry
Microsoft would like to collect data about how users use this Spring boot starter. Microsoft uses this information to improve our tooling experience. Participation is voluntary. If you don't want to participate, just simply disable it by setting below configuration in `application.properties`.
```
azure.storage.allow-telemetry=false
```
Find more information about Azure Service Privacy Statement, please check [Microsoft Online Services Privacy Statement](https://www.microsoft.com/en-us/privacystatement/OnlineServices/Default.aspx).

Просмотреть файл

@ -123,7 +123,10 @@
<artifactId>adal4j</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>applicationinsights-core</artifactId>
</dependency>
<!-- Annotation processor -->
<dependency>
<groupId>org.springframework.boot</groupId>
@ -158,4 +161,5 @@
<scope>test</scope>
</dependency>
</dependencies>
</project>

Просмотреть файл

@ -12,12 +12,7 @@ import com.microsoft.aad.adal4j.ClientCredential;
import com.microsoft.azure.keyvault.authentication.KeyVaultCredentials;
import java.net.MalformedURLException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.*;
public class AzureKeyVaultCredential extends KeyVaultCredentials {

Просмотреть файл

@ -10,20 +10,26 @@ import com.microsoft.azure.AzureResponseBuilder;
import com.microsoft.azure.keyvault.KeyVaultClient;
import com.microsoft.azure.serializer.AzureJacksonAdapter;
import com.microsoft.azure.spring.support.UserAgent;
import com.microsoft.rest.LogLevel;
import com.microsoft.azure.telemetry.TelemetryData;
import com.microsoft.azure.telemetry.TelemetryProxy;
import com.microsoft.rest.RestClient;
import com.microsoft.rest.credentials.ServiceClientCredentials;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import java.util.HashMap;
class KeyVaultEnvironmentPostProcessorHelper {
private final ConfigurableEnvironment environment;
private final TelemetryProxy telemetryProxy;
public KeyVaultEnvironmentPostProcessorHelper(ConfigurableEnvironment environment) {
this.environment = environment;
this.telemetryProxy = new TelemetryProxy(this.allowTelemetry(environment));
}
public void addKeyVaultPropertySource() {
@ -37,15 +43,17 @@ class KeyVaultEnvironmentPostProcessorHelper {
final ServiceClientCredentials credentials =
new AzureKeyVaultCredential(clientId, clientKey, timeAcquiringTimeoutInSeconds);
final RestClient restClient = new RestClient.Builder().withBaseUrl(vaultUri)
.withCredentials(credentials)
.withSerializerAdapter(new AzureJacksonAdapter())
.withResponseBuilderFactory(new AzureResponseBuilder.Factory())
.withUserAgent(UserAgent.getUserAgent(Constants.AZURE_KEYVAULT_USER_AGENT,
allowTelemetry(environment)))
.build();
.withCredentials(credentials)
.withSerializerAdapter(new AzureJacksonAdapter())
.withResponseBuilderFactory(new AzureResponseBuilder.Factory())
.withUserAgent(UserAgent.getUserAgent(Constants.AZURE_KEYVAULT_USER_AGENT,
allowTelemetry(environment)))
.build();
final KeyVaultClient kvClient = new KeyVaultClient(restClient);
this.trackCustomEvent();
try {
final MutablePropertySources sources = environment.getPropertySources();
final KeyVaultOperation kvOperation = new KeyVaultOperation(kvClient, vaultUri);
@ -79,4 +87,11 @@ class KeyVaultEnvironmentPostProcessorHelper {
return env.getProperty(Constants.AZURE_KEYVAULT_ALLOW_TELEMETRY, Boolean.class, true);
}
private void trackCustomEvent() {
final HashMap<String, String> customTelemetryProperties = new HashMap<>();
customTelemetryProperties.put(TelemetryData.SERVICE_NAME, "keyvault");
telemetryProxy.trackEvent(ClassUtils.getUserClass(this.getClass()).getSimpleName(), customTelemetryProperties);
}
}

Просмотреть файл

@ -9,7 +9,6 @@ import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;
import com.microsoft.aad.adal4j.ClientCredential;
import com.microsoft.aad.adal4j.UserAssertion;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.proc.BadJOSEException;
import org.slf4j.Logger;

Просмотреть файл

@ -5,6 +5,9 @@
*/
package com.microsoft.azure.spring.autoconfigure.aad;
import com.microsoft.azure.telemetry.TelemetryData;
import com.microsoft.azure.telemetry.TelemetryProxy;
import com.microsoft.azure.utils.PropertyLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
@ -14,6 +17,9 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.util.ClassUtils;
import java.util.HashMap;
@Configuration
@ConditionalOnWebApplication
@ -25,10 +31,13 @@ public class AADAuthenticationFilterAutoConfiguration {
private final AADAuthenticationFilterProperties aadAuthFilterProperties;
private final ServiceEndpointsProperties serviceEndpointsProperties;
private final TelemetryProxy telemetryProxy;
public AADAuthenticationFilterAutoConfiguration(AADAuthenticationFilterProperties aadAuthFilterProperties,
ServiceEndpointsProperties serviceEndpointsProperties) {
this.aadAuthFilterProperties = aadAuthFilterProperties;
this.serviceEndpointsProperties = serviceEndpointsProperties;
this.telemetryProxy = new TelemetryProxy(aadAuthFilterProperties.isAllowTelemetry());
}
/**
@ -41,6 +50,17 @@ public class AADAuthenticationFilterAutoConfiguration {
@ConditionalOnMissingBean(AADAuthenticationFilter.class)
public AADAuthenticationFilter azureADJwtTokenFilter() {
LOG.info("AzureADJwtTokenFilter Constructor.");
trackCustomEvent();
return new AADAuthenticationFilter(aadAuthFilterProperties, serviceEndpointsProperties);
}
private void trackCustomEvent() {
final HashMap<String, String> customTelemetryProperties = new HashMap<>();
final String[] packageNames = this.getClass().getPackage().getName().split("\\.");
if (packageNames.length > 1) {
customTelemetryProperties.put(TelemetryData.SERVICE_NAME, packageNames[packageNames.length - 1]);
}
telemetryProxy.trackEvent(ClassUtils.getUserClass(this.getClass()).getSimpleName(), customTelemetryProperties);
}
}

Просмотреть файл

@ -37,6 +37,16 @@ public class AADAuthenticationFilterProperties {
@NotEmpty
private List<String> activeDirectoryGroups;
private boolean allowTelemetry = true;
public boolean isAllowTelemetry() {
return allowTelemetry;
}
public void setAllowTelemetry(boolean allowTelemetry) {
this.allowTelemetry = allowTelemetry;
}
public String getEnvironment() {
return StringUtils.isEmpty(environment) ? DEFAULT_SERVICE_ENVIRONMENT : environment;
}

Просмотреть файл

@ -29,7 +29,7 @@ public class AzureADGraphClient {
if (responseCode == HTTPResponse.SC_OK) {
return responseInJson;
} else {
throw new IllegalStateException("Response is not " + HTTPResponse.SC_OK +
throw new IllegalStateException("Response is not " + HTTPResponse.SC_OK +
", response json: " + responseInJson);
}
}

Просмотреть файл

@ -19,11 +19,7 @@ import com.nimbusds.jose.proc.JWSKeySelector;
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.proc.BadJWTException;
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
import com.nimbusds.jwt.proc.DefaultJWTClaimsVerifier;
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
import com.nimbusds.jwt.proc.JWTClaimsSetVerifier;
import com.nimbusds.jwt.proc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
@ -35,15 +31,11 @@ import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.*;
import static java.util.stream.Collectors.toList;
public class UserPrincipal{
public class UserPrincipal {
private static final Logger LOG = LoggerFactory.getLogger(UserPrincipal.class);
private ServiceEndpoints serviceEndpoints;
@ -163,7 +155,7 @@ public class UserPrincipal{
return jwtProcessor;
}
private List<UserGroup> loadUserGroups(String graphApiToken) throws IOException{
private List<UserGroup> loadUserGroups(String graphApiToken) throws IOException {
final String responseInJson =
AzureADGraphClient.getUserMembershipsV1(graphApiToken, serviceEndpoints.getAadMembershipRestUri());
final List<UserGroup> lUserGroups = new ArrayList<>();

Просмотреть файл

@ -17,9 +17,8 @@ import java.util.List;
/**
* Yaml file initializer to load the specified yaml configuration file,
* by default the Spring will load the application.yml file.
*
* <p>
* In order to avoid possible overwritten by users' default yaml configuration file.
*
*/
public class YamlFileApplicationContextInitializer
implements ApplicationContextInitializer<ConfigurableApplicationContext> {

Просмотреть файл

@ -14,6 +14,8 @@ import com.microsoft.azure.spring.data.documentdb.core.DocumentDbTemplate;
import com.microsoft.azure.spring.data.documentdb.core.convert.MappingDocumentDbConverter;
import com.microsoft.azure.spring.data.documentdb.core.mapping.DocumentDbMappingContext;
import com.microsoft.azure.spring.support.GetHashMac;
import com.microsoft.azure.telemetry.TelemetryData;
import com.microsoft.azure.telemetry.TelemetryProxy;
import com.microsoft.azure.utils.PropertyLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -28,6 +30,9 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.data.annotation.Persistent;
import org.springframework.util.ClassUtils;
import java.util.HashMap;
@Configuration
@ConditionalOnClass({DocumentClient.class, DocumentDbTemplate.class})
@ -40,6 +45,8 @@ public class DocumentDBAutoConfiguration {
private final DocumentDBProperties properties;
private final ConnectionPolicy connectionPolicy;
private final ApplicationContext applicationContext;
private final TelemetryProxy telemetryProxy;
public DocumentDBAutoConfiguration(DocumentDBProperties properties,
ObjectProvider<ConnectionPolicy> connectionPolicyObjectProvider,
@ -47,6 +54,8 @@ public class DocumentDBAutoConfiguration {
this.properties = properties;
this.connectionPolicy = connectionPolicyObjectProvider.getIfAvailable();
this.applicationContext = applicationContext;
this.telemetryProxy = new TelemetryProxy(properties.isAllowTelemetry());
}
@Bean
@ -68,11 +77,24 @@ public class DocumentDBAutoConfiguration {
}
policy.setUserAgentSuffix(userAgent);
trackCustomEvent();
return new DocumentClient(properties.getUri(), properties.getKey(), policy,
properties.getConsistencyLevel() == null ?
ConsistencyLevel.Session : properties.getConsistencyLevel());
}
private void trackCustomEvent() {
final HashMap<String, String> customTelemetryProperties = new HashMap<>();
final String[] packageNames = this.getClass().getPackage().getName().split("\\.");
if (packageNames.length > 1) {
customTelemetryProperties.put(TelemetryData.SERVICE_NAME, packageNames[packageNames.length - 1]);
}
telemetryProxy.trackEvent(ClassUtils.getUserClass(this.getClass()).getSimpleName(), customTelemetryProperties);
}
@Bean
@ConditionalOnMissingBean
public DocumentDbFactory documentDbFactory(DocumentClient documentClient) {

Просмотреть файл

@ -6,6 +6,8 @@
package com.microsoft.azure.spring.autoconfigure.mediaservices;
import com.microsoft.azure.telemetry.TelemetryData;
import com.microsoft.azure.telemetry.TelemetryProxy;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.services.media.MediaConfiguration;
import com.microsoft.windowsazure.services.media.MediaContract;
@ -17,10 +19,11 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ClassUtils;
import static com.microsoft.windowsazure.Configuration.PROPERTY_HTTP_PROXY_HOST;
import static com.microsoft.windowsazure.Configuration.PROPERTY_HTTP_PROXY_PORT;
import static com.microsoft.windowsazure.Configuration.PROPERTY_HTTP_PROXY_SCHEME;
import java.util.HashMap;
import static com.microsoft.windowsazure.Configuration.*;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
@ -33,9 +36,11 @@ public class MediaServicesAutoConfiguration {
private static final Logger LOG = LoggerFactory.getLogger(MediaServicesAutoConfiguration.class);
private final MediaServicesProperties mediaServicesProperties;
private final TelemetryProxy telemetryProxy;
public MediaServicesAutoConfiguration(MediaServicesProperties mediaServicesProperties) {
this.mediaServicesProperties = mediaServicesProperties;
this.telemetryProxy = new TelemetryProxy(mediaServicesProperties.isAllowTelemetry());
}
/**
@ -47,6 +52,7 @@ public class MediaServicesAutoConfiguration {
@Bean
public MediaContract mediaContract() throws ServiceException {
LOG.debug("mediaContract called");
trackCustomEvent();
return createMediaContract();
}
@ -72,4 +78,14 @@ public class MediaServicesAutoConfiguration {
}
return MediaService.create(configuration);
}
private void trackCustomEvent() {
final HashMap<String, String> customTelemetryProperties = new HashMap<>();
final String[] packageNames = this.getClass().getPackage().getName().split("\\.");
if (packageNames.length > 1) {
customTelemetryProperties.put(TelemetryData.SERVICE_NAME, packageNames[packageNames.length - 1]);
}
telemetryProxy.trackEvent(ClassUtils.getUserClass(this.getClass()).getSimpleName(), customTelemetryProperties);
}
}

Просмотреть файл

@ -48,6 +48,29 @@ public class MediaServicesProperties {
*/
private String proxyScheme = "http";
/**
* Weather allow telemetry collecting.
*/
private boolean allowTelemetry = true;
/**
* return allow telemery or not
*
* @return
*/
public boolean isAllowTelemetry() {
return allowTelemetry;
}
/**
* Set allowTelemetry
*
* @param allowTelemetry
*/
public void setAllowTelemetry(boolean allowTelemetry) {
this.allowTelemetry = allowTelemetry;
}
/**
* @return the accountName
*/

Просмотреть файл

@ -11,12 +11,17 @@ import com.microsoft.azure.servicebus.SubscriptionClient;
import com.microsoft.azure.servicebus.TopicClient;
import com.microsoft.azure.servicebus.primitives.ConnectionStringBuilder;
import com.microsoft.azure.servicebus.primitives.ServiceBusException;
import com.microsoft.azure.telemetry.TelemetryData;
import com.microsoft.azure.telemetry.TelemetryProxy;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.ClassUtils;
import java.util.HashMap;
@Lazy
@Configuration
@ -25,15 +30,18 @@ import org.springframework.context.annotation.Lazy;
public class ServiceBusAutoConfiguration {
private final ServiceBusProperties properties;
private final TelemetryProxy telemetryProxy;
public ServiceBusAutoConfiguration(ServiceBusProperties properties) {
this.properties = properties;
this.telemetryProxy = new TelemetryProxy(properties.isAllowTelemetry());
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "azure.servicebus", value = {"queue-name", "queue-receive-mode"})
public QueueClient queueClient() throws InterruptedException, ServiceBusException {
trackCustomEvent();
return new QueueClient(new ConnectionStringBuilder(properties.getConnectionString(),
properties.getQueueName()), properties.getQueueReceiveMode());
}
@ -42,6 +50,7 @@ public class ServiceBusAutoConfiguration {
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "azure.servicebus", value = "topic-name")
public TopicClient topicClient() throws InterruptedException, ServiceBusException {
trackCustomEvent();
return new TopicClient(new ConnectionStringBuilder(properties.getConnectionString(),
properties.getTopicName()));
}
@ -51,8 +60,19 @@ public class ServiceBusAutoConfiguration {
@ConditionalOnProperty(prefix = "azure.servicebus",
value = {"topic-name", "subscription-name", "subscription-receive-mode"})
public SubscriptionClient subscriptionClient() throws ServiceBusException, InterruptedException {
trackCustomEvent();
return new SubscriptionClient(new ConnectionStringBuilder(properties.getConnectionString(),
properties.getTopicName() + "/subscriptions/" + properties.getSubscriptionName()),
properties.getSubscriptionReceiveMode());
}
private void trackCustomEvent() {
final HashMap<String, String> customTelemetryProperties = new HashMap<>();
final String[] packageNames = this.getClass().getPackage().getName().split("\\.");
if (packageNames.length > 1) {
customTelemetryProperties.put(TelemetryData.SERVICE_NAME, packageNames[packageNames.length - 1]);
}
telemetryProxy.trackEvent(ClassUtils.getUserClass(this.getClass()).getSimpleName(), customTelemetryProperties);
}
}

Просмотреть файл

@ -45,6 +45,26 @@ public class ServiceBusProperties {
*/
private ReceiveMode subscriptionReceiveMode;
private boolean allowTelemetry = true;
/**
* return allow telemery or not
*
* @return
*/
public boolean isAllowTelemetry() {
return allowTelemetry;
}
/**
* Set allowTelemetry
*
* @param allowTelemetry
*/
public void setAllowTelemetry(boolean allowTelemetry) {
this.allowTelemetry = allowTelemetry;
}
public String getConnectionString() {
return connectionString;
}

Просмотреть файл

@ -7,6 +7,8 @@
package com.microsoft.azure.spring.autoconfigure.storage;
import com.microsoft.azure.storage.CloudStorageAccount;
import com.microsoft.azure.telemetry.TelemetryData;
import com.microsoft.azure.telemetry.TelemetryProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
@ -15,9 +17,11 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.util.ClassUtils;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.util.HashMap;
@Configuration
@ConditionalOnMissingBean(CloudStorageAccount.class)
@ -27,9 +31,11 @@ public class StorageAutoConfiguration {
private static final Logger LOG = LoggerFactory.getLogger(StorageAutoConfiguration.class);
private final StorageProperties properties;
private final TelemetryProxy telemetryProxy;
public StorageAutoConfiguration(StorageProperties properties) {
this.properties = properties;
this.telemetryProxy = new TelemetryProxy(properties.isAllowTelemetry());
}
/**
@ -41,6 +47,7 @@ public class StorageAutoConfiguration {
@Scope("prototype")
public CloudStorageAccount cloudStorageAccount() throws URISyntaxException, InvalidKeyException {
LOG.debug("cloudStorageAccount called");
trackCustomEvent();
return createCloudStorageAccount();
}
@ -53,4 +60,14 @@ public class StorageAutoConfiguration {
LOG.debug("createCloudStorageAccount called");
return CloudStorageAccount.parse(properties.getConnectionString());
}
private void trackCustomEvent() {
final HashMap<String, String> customTelemetryProperties = new HashMap<>();
final String[] packageNames = this.getClass().getPackage().getName().split("\\.");
if (packageNames.length > 1) {
customTelemetryProperties.put(TelemetryData.SERVICE_NAME, packageNames[packageNames.length - 1]);
}
telemetryProxy.trackEvent(ClassUtils.getUserClass(this.getClass()).getSimpleName(), customTelemetryProperties);
}
}

Просмотреть файл

@ -20,6 +20,26 @@ public class StorageProperties {
@NotEmpty
private String connectionString;
private boolean allowTelemetry = true;
/**
* return allow telemery or not
*
* @return
*/
public boolean isAllowTelemetry() {
return allowTelemetry;
}
/**
* Set allowTelemetry
*
* @param allowTelemetry
*/
public void setAllowTelemetry(boolean allowTelemetry) {
this.allowTelemetry = allowTelemetry;
}
/**
* Get storage account connection string.
*

Просмотреть файл

@ -12,11 +12,7 @@
package com.microsoft.azure.spring.support;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;

Просмотреть файл

@ -10,7 +10,7 @@ public class UserAgent {
/**
* Generate UserAgent string for given service.
*
* @param serviceName Name of the service from which called this method.
* @param serviceName Name of the service from which called this method.
* @param allowTelemetry Whether allows telemtry
* @return generated UserAgent string
*/

Просмотреть файл

@ -0,0 +1,18 @@
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for
* license information.
*/
package com.microsoft.azure.telemetry;
import com.microsoft.applicationinsights.TelemetryConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ApplicationInsightsConfiguration {
@Bean
public TelemetryConfiguration telemetryConfiguration() {
return TelemetryConfiguration.getActive();
}
}

Просмотреть файл

@ -0,0 +1,13 @@
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for
* license information.
*/
package com.microsoft.azure.telemetry;
public class TelemetryData {
public static final String TELEMETRY_NOT_ALLOWED = "telemetryNotAllowed";
public static final String INSTALLATION_ID = "installationId";
public static final String PROJECT_VERSION = "version";
public static final String SERVICE_NAME = "serviceName";
}

Просмотреть файл

@ -0,0 +1,90 @@
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for
* license information.
*/
package com.microsoft.azure.telemetry;
import com.microsoft.applicationinsights.TelemetryClient;
import com.microsoft.azure.spring.support.GetHashMac;
import com.microsoft.azure.utils.PropertyLoader;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class TelemetryProxy {
private static final String PROJECT_INFO = "spring-boot-starter/" + PropertyLoader.getProjectVersion();
protected TelemetryClient client;
private boolean isAllowTelemetry;
public TelemetryProxy(boolean isAllowTelemetry) {
this.client = new TelemetryClient();
this.isAllowTelemetry = isAllowTelemetry;
}
public void trackEvent(final String eventName) {
trackEvent(eventName, null, false);
}
public void trackEvent(final String eventName, final Map<String, String> customProperties) {
trackEvent(eventName, customProperties, false);
}
public void trackEvent(final String eventName, final Map<String, String> customProperties,
final boolean overrideDefaultProperties) {
Map<String, String> properties = getDefaultProperties();
if (this.isAllowTelemetry) {
properties = mergeProperties(getDefaultProperties(), customProperties,
overrideDefaultProperties);
}
client.trackEvent(eventName, properties, null);
client.flush();
}
protected Map<String, String> mergeProperties(Map<String, String> defaultProperties,
Map<String, String> customProperties,
boolean overrideDefaultProperties) {
if (customProperties == null) {
return defaultProperties;
}
final Map<String, String> merged = new HashMap<>();
if (overrideDefaultProperties) {
merged.putAll(defaultProperties);
merged.putAll(customProperties);
} else {
merged.putAll(customProperties);
merged.putAll(defaultProperties);
}
final Iterator<Map.Entry<String, String>> it = merged.entrySet().iterator();
while (it.hasNext()) {
if (StringUtils.isEmpty(it.next().getValue())) {
it.remove();
}
}
return merged;
}
public Map<String, String> getDefaultProperties() {
final Map<String, String> properties = new HashMap<>();
if (this.isAllowTelemetry) {
properties.put(TelemetryData.INSTALLATION_ID, GetHashMac.getHashMac());
properties.put(TelemetryData.PROJECT_VERSION, PROJECT_INFO);
} else {
properties.put(TelemetryData.TELEMETRY_NOT_ALLOWED, "true");
}
return properties;
}
}

Просмотреть файл

@ -64,7 +64,7 @@ public class AADAuthenticationFilterPropertiesTest {
}
}
private void configureAllRequiredProperties(){
private void configureAllRequiredProperties() {
System.setProperty(Constants.CLIENT_ID_PROPERTY, Constants.CLIENT_ID);
System.setProperty(Constants.CLIENT_SECRET_PROPERTY, Constants.CLIENT_SECRET);
System.setProperty(Constants.TARGETED_GROUPS_PROPERTY,

Просмотреть файл

@ -8,11 +8,7 @@ package com.microsoft.azure.spring.autoconfigure.documentdb;
import org.springframework.context.annotation.Import;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.*;
@Target(ElementType.TYPE)

Просмотреть файл

@ -12,7 +12,7 @@ import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
public class MediaServicesAutoConfigurationTest {
@Test

Просмотреть файл

@ -13,7 +13,7 @@ import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
public class ServiceBusAutoConfigurationTest {
@Test

Просмотреть файл

@ -21,9 +21,7 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest

Просмотреть файл

@ -5,9 +5,8 @@
<Bug pattern="NP_NONNULL_PARAM_VIOLATION"/>
<Bug pattern="Unwritten field"/>
<Bug pattern="SIC_INNER_SHOULD_BE_STATIC_ANON"/>
<Bug pattern="SIC_INNER_SHOULD_BE_STATIC_NEEDS_THIS"/>
<Bug pattern="UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD"/>
<Bug pattern="RE_POSSIBLE_UNINTENDED_PATTERN"/>
</FindBugsFilter>