diff --git a/src/main/java/com/synopsys/integration/phonehome/PhoneHomeClient.java b/src/main/java/com/synopsys/integration/phonehome/PhoneHomeClient.java index 4153741..720a8a6 100644 --- a/src/main/java/com/synopsys/integration/phonehome/PhoneHomeClient.java +++ b/src/main/java/com/synopsys/integration/phonehome/PhoneHomeClient.java @@ -23,7 +23,6 @@ package com.synopsys.integration.phonehome; import java.util.Map; -import java.util.Optional; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; @@ -37,7 +36,6 @@ import com.google.gson.Gson; import com.synopsys.integration.log.IntLogger; import com.synopsys.integration.phonehome.exception.PhoneHomeException; -import com.synopsys.integration.phonehome.google.analytics.GoogleAnalyticsConstants; import com.synopsys.integration.phonehome.google.analytics.GoogleAnalyticsRequestHelper; public class PhoneHomeClient { @@ -46,40 +44,49 @@ public class PhoneHomeClient { public static final String SKIP_PHONE_HOME_VARIABLE = "SYNOPSYS_SKIP_PHONE_HOME"; public static final String PHONE_HOME_URL_OVERRIDE_VARIABLE = "SYNOPSYS_PHONE_HOME_URL_OVERRIDE"; - private final String googleAnalyticsTrackingId; private final HttpClientBuilder httpClientBuilder; private final IntLogger logger; private final Gson gson; - private String phoneHomeBackendUrl; - - public PhoneHomeClient(final String googleAnalyticsTrackingId, final IntLogger logger) { - this(googleAnalyticsTrackingId, logger, createInitialRequestConfigBuilder(10, Optional.empty()).build()); + public PhoneHomeClient(final IntLogger logger) { + this(logger, createInitialRequestConfigBuilder(10).build()); } - public PhoneHomeClient(final String googleAnalyticsTrackingId, final IntLogger logger, final Gson gson) { - this(googleAnalyticsTrackingId, logger, createInitialRequestConfigBuilder(10, Optional.empty()).build(), gson); + public PhoneHomeClient(final IntLogger logger, final Gson gson) { + this(logger, createInitialRequestConfigBuilder(10).build(), gson); } - public PhoneHomeClient(final String googleAnalyticsTrackingId, final IntLogger logger, final RequestConfig httpRequestConfig) { - this(googleAnalyticsTrackingId, logger, httpRequestConfig, new Gson()); + public PhoneHomeClient(final IntLogger logger, final RequestConfig httpRequestConfig) { + this(logger, httpRequestConfig, new Gson()); } - public PhoneHomeClient(final String googleAnalyticsTrackingId, final IntLogger logger, final RequestConfig httpRequestConfig, final Gson gson) { - this(googleAnalyticsTrackingId, logger, HttpClientBuilder.create().setDefaultRequestConfig(httpRequestConfig), gson); + public PhoneHomeClient(final IntLogger logger, final RequestConfig httpRequestConfig, final Gson gson) { + this(logger, HttpClientBuilder.create().setDefaultRequestConfig(httpRequestConfig), gson); } - public PhoneHomeClient(final String googleAnalyticsTrackingId, final IntLogger logger, final HttpClientBuilder httpClientBuilder) { - this(googleAnalyticsTrackingId, logger, httpClientBuilder, new Gson()); + public PhoneHomeClient(final IntLogger logger, final HttpClientBuilder httpClientBuilder) { + this(logger, httpClientBuilder, new Gson()); } - public PhoneHomeClient(final String googleAnalyticsTrackingId, final IntLogger logger, final HttpClientBuilder httpClientBuilder, final Gson gson) { - this.googleAnalyticsTrackingId = googleAnalyticsTrackingId; + public PhoneHomeClient(final IntLogger logger, final HttpClientBuilder httpClientBuilder, final Gson gson) { this.httpClientBuilder = httpClientBuilder; this.logger = logger; this.gson = gson; + } + + public static RequestConfig.Builder createInitialRequestConfigBuilder(final int timeoutSeconds) { + final int timeoutInMillis = timeoutSeconds * 1000; + final RequestConfig.Builder builder = RequestConfig.custom(); + builder.setConnectionRequestTimeout(timeoutInMillis); + builder.setConnectTimeout(timeoutInMillis); + builder.setSocketTimeout(timeoutInMillis); + return builder; + } - this.phoneHomeBackendUrl = GoogleAnalyticsConstants.BASE_URL + GoogleAnalyticsConstants.COLLECT_ENDPOINT; + public static RequestConfig.Builder createInitialRequestConfigBuilder(final int timeoutSeconds, final HttpHost proxyHost) { + final RequestConfig.Builder builder = createInitialRequestConfigBuilder(timeoutSeconds); + builder.setProxy(proxyHost); + return builder; } public void postPhoneHomeRequest(final PhoneHomeRequestBody phoneHomeRequestBody, final Map environmentVariables) throws PhoneHomeException { @@ -90,13 +97,20 @@ public void postPhoneHomeRequest(final PhoneHomeRequestBody phoneHomeRequestBody if (phoneHomeRequestBody == null) { throw new PhoneHomeException("The request body must not be null."); } - checkOverridePhoneHomeUrl(environmentVariables); - logger.debug("Phoning home to " + phoneHomeBackendUrl); + String overrideUrl = checkOverridePhoneHomeUrl(environmentVariables); try (final CloseableHttpClient client = httpClientBuilder.build()) { - final GoogleAnalyticsRequestHelper requestHelper = new GoogleAnalyticsRequestHelper(gson, googleAnalyticsTrackingId, phoneHomeRequestBody); - final HttpUriRequest request = requestHelper.createRequest(phoneHomeBackendUrl); + final GoogleAnalyticsRequestHelper requestHelper = new GoogleAnalyticsRequestHelper(gson); + final HttpUriRequest request; + + if (overrideUrl != null) { + logger.debug("Overriding Phone-Home URL: " + overrideUrl); + request = requestHelper.createRequest(phoneHomeRequestBody, overrideUrl); + } else { + request = requestHelper.createRequest(phoneHomeRequestBody); + } + logger.debug("Phoning home to " + request.getURI()); final HttpResponse response = client.execute(request); logger.trace("Response Code: " + response.getStatusLine().getStatusCode()); } catch (final Exception e) { @@ -104,18 +118,6 @@ public void postPhoneHomeRequest(final PhoneHomeRequestBody phoneHomeRequestBody } } - public static RequestConfig.Builder createInitialRequestConfigBuilder(final int timeoutSeconds, final Optional proxyHost) { - final int timeoutInMillis = timeoutSeconds * 1000; - final RequestConfig.Builder builder = RequestConfig.custom(); - builder.setConnectionRequestTimeout(timeoutInMillis); - builder.setConnectTimeout(timeoutInMillis); - builder.setSocketTimeout(timeoutInMillis); - if (proxyHost.isPresent()) { - builder.setProxy(proxyHost.get()); - } - return builder; - } - private boolean skipPhoneHome(final Map environmentVariables) { if (environmentVariables.containsKey(SKIP_PHONE_HOME_VARIABLE) || environmentVariables.containsKey(BLACKDUCK_SKIP_PHONE_HOME_VARIABLE)) { String valueString = environmentVariables.get(SKIP_PHONE_HOME_VARIABLE); @@ -127,17 +129,15 @@ private boolean skipPhoneHome(final Map environmentVariables) { return false; } - private void checkOverridePhoneHomeUrl(final Map environmentVariables) { - if (environmentVariables.containsKey(PHONE_HOME_URL_OVERRIDE_VARIABLE) || environmentVariables.containsKey(BLACKDUCK_PHONE_HOME_URL_OVERRIDE_VARIABLE)) { - String overrideUrl = environmentVariables.get(PHONE_HOME_URL_OVERRIDE_VARIABLE); - if (StringUtils.isBlank(overrideUrl)) { - overrideUrl = environmentVariables.get(BLACKDUCK_PHONE_HOME_URL_OVERRIDE_VARIABLE); - } - if (StringUtils.isNotBlank(overrideUrl)) { - phoneHomeBackendUrl = overrideUrl; - logger.debug("Overriding Phone-Home URL: " + overrideUrl); - } + private String checkOverridePhoneHomeUrl(final Map environmentVariables) { + String overrideUrl; + + overrideUrl = environmentVariables.get(PHONE_HOME_URL_OVERRIDE_VARIABLE); + if (StringUtils.isBlank(overrideUrl)) { + overrideUrl = environmentVariables.get(BLACKDUCK_PHONE_HOME_URL_OVERRIDE_VARIABLE); } + + return overrideUrl; } } diff --git a/src/main/java/com/synopsys/integration/phonehome/PhoneHomeRequestBody.java b/src/main/java/com/synopsys/integration/phonehome/PhoneHomeRequestBody.java index 0f240c9..b6561bc 100644 --- a/src/main/java/com/synopsys/integration/phonehome/PhoneHomeRequestBody.java +++ b/src/main/java/com/synopsys/integration/phonehome/PhoneHomeRequestBody.java @@ -25,8 +25,10 @@ import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import org.apache.commons.codec.digest.DigestUtils; @@ -45,6 +47,7 @@ public class PhoneHomeRequestBody { private final String artifactVersion; private final ProductIdEnum productId; private final String productVersion; + private final List artifactModules; private final Map metaData; private PhoneHomeRequestBody(final PhoneHomeRequestBody.Builder builder) { @@ -54,6 +57,7 @@ private PhoneHomeRequestBody(final PhoneHomeRequestBody.Builder builder) { artifactVersion = builder.getArtifactVersion(); productId = builder.getProductId(); productVersion = builder.getProductVersion(); + artifactModules = builder.getArtifactModules(); metaData = Collections.unmodifiableMap(builder.getMetaData()); } @@ -85,16 +89,20 @@ public Map getMetaData() { return metaData; } + public List getArtifactModules() { + return artifactModules; + } + public static class Builder { public static final String UNKNOWN_ID = ""; - + private final Map metaData = new HashMap<>(); private String customerId; private String hostName; private String artifactId; private String artifactVersion; private ProductIdEnum productId; private String productVersion; - private final Map metaData = new HashMap<>(); + private List artifactModules; // PhoneHomeRequestBody only has a private constructor to force creation through the builder. public PhoneHomeRequestBody build() throws IllegalStateException { @@ -157,6 +165,14 @@ public void setProductVersion(final String productVersion) { this.productVersion = productVersion; } + public List getArtifactModules() { + return artifactModules; + } + + public void setArtifactModules(final String... artifactModules) { + this.artifactModules = Arrays.asList(artifactModules); + } + public Map getMetaData() { return Collections.unmodifiableMap(new HashMap<>(metaData)); } @@ -180,7 +196,7 @@ public boolean addToMetaData(final String key, final String value) { */ public boolean addAllToMetaData(final Map metadataMap) { return metadataMap.entrySet().stream() - .allMatch(entry -> addToMetaData(entry.getKey(), entry.getValue())); + .allMatch(entry -> addToMetaData(entry.getKey(), entry.getValue())); } public String md5Hash(final String string) throws NoSuchAlgorithmException, UnsupportedEncodingException { @@ -200,7 +216,6 @@ private int charactersInMetaDataMap(final String key, final String value) { final String mapAsString = getMetaData().toString(); return mapEntryWrappingCharacters + mapAsString.length() + key.length() + value.length(); } - } } diff --git a/src/main/java/com/synopsys/integration/phonehome/PhoneHomeResponse.java b/src/main/java/com/synopsys/integration/phonehome/PhoneHomeResponse.java index 563c3cd..d2f1ec9 100644 --- a/src/main/java/com/synopsys/integration/phonehome/PhoneHomeResponse.java +++ b/src/main/java/com/synopsys/integration/phonehome/PhoneHomeResponse.java @@ -31,6 +31,11 @@ public class PhoneHomeResponse { private final Future phoneHomeTask; private final Boolean result; + private PhoneHomeResponse(final Future phoneHomeTask, final Boolean result) { + this.phoneHomeTask = phoneHomeTask; + this.result = result; + } + public static PhoneHomeResponse createResponse(final Boolean result) { return new PhoneHomeResponse(null, result); } @@ -39,11 +44,6 @@ public static PhoneHomeResponse createAsynchronousResponse(final Future return new PhoneHomeResponse(phoneHomeTask, Boolean.FALSE); } - private PhoneHomeResponse(final Future phoneHomeTask, final Boolean result) { - this.phoneHomeTask = phoneHomeTask; - this.result = result; - } - /** * If Phone Home was called asynchronously: If the result is available, it will be returned, otherwise the task will be cancelled and this will return Boolean.FALSE. * If Phone Home was called synchronously: The result of the synchronous call will be returned. @@ -59,7 +59,10 @@ public Boolean awaitResult(final long timeoutInSeconds) { if (phoneHomeTask != null) { try { return phoneHomeTask.get(timeoutInSeconds, TimeUnit.SECONDS); - } catch (final InterruptedException | ExecutionException | TimeoutException e) { + } catch (final ExecutionException | TimeoutException e) { + return Boolean.FALSE; + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); return Boolean.FALSE; } finally { endPhoneHome(); diff --git a/src/main/java/com/synopsys/integration/phonehome/google/analytics/GoogleAnalyticsConstants.java b/src/main/java/com/synopsys/integration/phonehome/google/analytics/GoogleAnalyticsConstants.java index 1a97c01..24d131b 100644 --- a/src/main/java/com/synopsys/integration/phonehome/google/analytics/GoogleAnalyticsConstants.java +++ b/src/main/java/com/synopsys/integration/phonehome/google/analytics/GoogleAnalyticsConstants.java @@ -30,6 +30,7 @@ public class GoogleAnalyticsConstants { // Api Path(s) public static final String BASE_URL = "https://www.google-analytics.com"; public static final String COLLECT_ENDPOINT = "/collect"; + public static final String BATCH_ENDPOINT = "/batch"; public static final String DEBUG_ENDPOINT = "/debug" + COLLECT_ENDPOINT; // Payload Data - Required @@ -48,5 +49,6 @@ public class GoogleAnalyticsConstants { public static final String PRODUCT_VERSION = "cd5"; public static final String META_DATA = "cd6"; public static final String HOST_NAME = "cd7"; + public static final String MODULE_ID = "cd8"; } diff --git a/src/main/java/com/synopsys/integration/phonehome/google/analytics/GoogleAnalyticsRequestHelper.java b/src/main/java/com/synopsys/integration/phonehome/google/analytics/GoogleAnalyticsRequestHelper.java index 325ccf7..a39233c 100644 --- a/src/main/java/com/synopsys/integration/phonehome/google/analytics/GoogleAnalyticsRequestHelper.java +++ b/src/main/java/com/synopsys/integration/phonehome/google/analytics/GoogleAnalyticsRequestHelper.java @@ -24,93 +24,83 @@ import java.io.UnsupportedEncodingException; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URLEncodedUtils; +import org.apache.http.entity.AbstractHttpEntity; +import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicNameValuePair; +import org.apache.http.protocol.HTTP; import com.google.gson.Gson; import com.synopsys.integration.phonehome.PhoneHomeRequestBody; -import com.synopsys.integration.phonehome.enums.ProductIdEnum; public class GoogleAnalyticsRequestHelper { private final Gson gson; - private final String trackingId; - private final String customerId; - private final String hostName; - private final String artifactId; - private final String artifactVersion; - private final ProductIdEnum productId; - private final String productVersion; - private final Map metaData; - - public GoogleAnalyticsRequestHelper(final Gson gson, final String trackingId, final PhoneHomeRequestBody phoneHomeRequestBody) { + public GoogleAnalyticsRequestHelper(final Gson gson) { this.gson = gson; - this.trackingId = trackingId; - - this.customerId = phoneHomeRequestBody.getCustomerId(); - this.hostName = phoneHomeRequestBody.getHostName(); - this.artifactId = phoneHomeRequestBody.getArtifactId(); - this.artifactVersion = phoneHomeRequestBody.getArtifactVersion(); - this.productId = phoneHomeRequestBody.getProductId(); - this.productVersion = phoneHomeRequestBody.getProductVersion(); - this.metaData = phoneHomeRequestBody.getMetaData(); } - public HttpPost createRequest(final String url) throws UnsupportedEncodingException { - final HttpPost post = new HttpPost(url); - - final List parameters = new ArrayList<>(); - for (final Entry entry : getPayloadDataMap().entrySet()) { - final NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue()); - parameters.add(nameValuePair); - } - post.setEntity(new UrlEncodedFormEntity(parameters)); - // TODO post.addHeader(HttpHeaders.ACCEPT, ContentType.TEXT_PLAIN.getMimeType()); - - return post; + public HttpPost createRequest(final PhoneHomeRequestBody phoneHomeRequestBody) throws UnsupportedEncodingException { + return createRequest(phoneHomeRequestBody, null, GoogleAnalyticsConstants.PRODUCTION_INTEGRATIONS_TRACKING_ID); } - private Map getPayloadDataMap() { - final Map payloadData = new HashMap<>(); - - payloadData.put(GoogleAnalyticsConstants.API_VERSION_KEY, "1"); - payloadData.put(GoogleAnalyticsConstants.HIT_TYPE_KEY, "pageview"); - payloadData.put(GoogleAnalyticsConstants.CLIENT_ID_KEY, generateClientId()); - payloadData.put(GoogleAnalyticsConstants.TRACKING_ID_KEY, trackingId); - payloadData.put(GoogleAnalyticsConstants.DOCUMENT_PATH_KEY, "phone-home"); - - // Phone Home Parameters - payloadData.put(GoogleAnalyticsConstants.CUSTOMER_ID, customerId); - payloadData.put(GoogleAnalyticsConstants.HOST_NAME, hostName); - payloadData.put(GoogleAnalyticsConstants.ARTIFACT_ID, artifactId); - payloadData.put(GoogleAnalyticsConstants.ARTIFACT_VERSION, artifactVersion); - payloadData.put(GoogleAnalyticsConstants.PRODUCT_ID, productId.name()); - payloadData.put(GoogleAnalyticsConstants.PRODUCT_VERSION, productVersion); - payloadData.put(GoogleAnalyticsConstants.META_DATA, gson.toJson(metaData)); - - return payloadData; + public HttpPost createRequest(final PhoneHomeRequestBody phoneHomeRequestBody, final String url) throws UnsupportedEncodingException { + return createRequest(phoneHomeRequestBody, url, GoogleAnalyticsConstants.PRODUCTION_INTEGRATIONS_TRACKING_ID); } - private String generateClientId() { - final String clientId; - if (!PhoneHomeRequestBody.Builder.UNKNOWN_ID.equals(customerId)) { - clientId = customerId; - } else if (!PhoneHomeRequestBody.Builder.UNKNOWN_ID.equals(hostName)) { - clientId = hostName; + public HttpPost createRequest(final PhoneHomeRequestBody phoneHomeRequestBody, final String url, final String trackingId) throws UnsupportedEncodingException { + final GoogleAnalyticsRequestTransformer transformer = new GoogleAnalyticsRequestTransformer(gson, trackingId, phoneHomeRequestBody); + final List parameters = transformer.getParameters(); + final AbstractHttpEntity entity; + String requestUrl = url; + + // Not in the transformer because this will likely go away -- rotte 8/6/2019 + final List artifactModules = phoneHomeRequestBody.getArtifactModules(); + + if (artifactModules == null || artifactModules.size() == 0) { + if (StringUtils.isBlank(requestUrl)) { + requestUrl = GoogleAnalyticsConstants.BASE_URL + GoogleAnalyticsConstants.COLLECT_ENDPOINT; + } + + entity = new UrlEncodedFormEntity(parameters); } else { - clientId = PhoneHomeRequestBody.Builder.UNKNOWN_ID; + final String requestString = artifactModules.stream() + .map(module -> createModuleParameters(parameters, module)) + .map(moduleParameters -> URLEncodedUtils.format(moduleParameters, HTTP.DEF_CONTENT_CHARSET.name())) + .collect(Collectors.joining("\n")); + + if (StringUtils.isBlank(requestUrl)) { + requestUrl = GoogleAnalyticsConstants.BASE_URL + GoogleAnalyticsConstants.BATCH_ENDPOINT; + } + + entity = new StringEntity(requestString, HTTP.DEF_CONTENT_CHARSET); } - final byte[] bytesFromString = clientId.getBytes(); - return UUID.nameUUIDFromBytes(bytesFromString).toString(); + return this.createRequest(requestUrl, entity); + + } + + public HttpPost createRequest(final String url, final HttpEntity httpEntity) { + final HttpPost post = new HttpPost(url); + + post.setEntity(httpEntity); + // TODO post.addHeader(HttpHeaders.ACCEPT, ContentType.TEXT_PLAIN.getMimeType()); + + return post; } + private List createModuleParameters(final List parameters, final String module) { + final NameValuePair parameter = new BasicNameValuePair(GoogleAnalyticsConstants.MODULE_ID, module); + final List newParameters = new ArrayList<>(parameters); + newParameters.add(parameter); + return newParameters; + } } diff --git a/src/main/java/com/synopsys/integration/phonehome/google/analytics/GoogleAnalyticsRequestTransformer.java b/src/main/java/com/synopsys/integration/phonehome/google/analytics/GoogleAnalyticsRequestTransformer.java new file mode 100644 index 0000000..d72b0e6 --- /dev/null +++ b/src/main/java/com/synopsys/integration/phonehome/google/analytics/GoogleAnalyticsRequestTransformer.java @@ -0,0 +1,64 @@ +package com.synopsys.integration.phonehome.google.analytics; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.apache.http.NameValuePair; +import org.apache.http.message.BasicNameValuePair; + +import com.google.gson.Gson; +import com.synopsys.integration.phonehome.PhoneHomeRequestBody; + +public class GoogleAnalyticsRequestTransformer { + private final List parameters = new ArrayList<>(); + private final PhoneHomeRequestBody phoneHomeRequestBody; + private final String trackingId; + private final Gson gson; + + public GoogleAnalyticsRequestTransformer(final Gson gson, final String trackingId, final PhoneHomeRequestBody phoneHomeRequestBody) { + this.gson = gson; + this.phoneHomeRequestBody = phoneHomeRequestBody; + this.trackingId = trackingId; + } + + public List getParameters() { + addParameter(GoogleAnalyticsConstants.API_VERSION_KEY, "1"); + addParameter(GoogleAnalyticsConstants.HIT_TYPE_KEY, "pageview"); + + String clientId = generateClientId(phoneHomeRequestBody.getCustomerId(), phoneHomeRequestBody.getHostName()); + addParameter(GoogleAnalyticsConstants.CLIENT_ID_KEY, clientId); + addParameter(GoogleAnalyticsConstants.TRACKING_ID_KEY, trackingId); + addParameter(GoogleAnalyticsConstants.DOCUMENT_PATH_KEY, "phone-home"); + + // Phone Home Parameters + addParameter(GoogleAnalyticsConstants.CUSTOMER_ID, phoneHomeRequestBody.getCustomerId()); + addParameter(GoogleAnalyticsConstants.HOST_NAME, phoneHomeRequestBody.getHostName()); + addParameter(GoogleAnalyticsConstants.ARTIFACT_ID, phoneHomeRequestBody.getArtifactId()); + addParameter(GoogleAnalyticsConstants.ARTIFACT_VERSION, phoneHomeRequestBody.getArtifactVersion()); + addParameter(GoogleAnalyticsConstants.PRODUCT_ID, phoneHomeRequestBody.getProductId().name()); + addParameter(GoogleAnalyticsConstants.PRODUCT_VERSION, phoneHomeRequestBody.getProductVersion()); + addParameter(GoogleAnalyticsConstants.META_DATA, gson.toJson(phoneHomeRequestBody.getMetaData())); + + return parameters; + } + + private void addParameter(final String key, final String value) { + final NameValuePair parameter = new BasicNameValuePair(key, value); + parameters.add(parameter); + } + + private String generateClientId(final String customerId, final String hostName) { + final String clientId; + if (!PhoneHomeRequestBody.Builder.UNKNOWN_ID.equals(customerId)) { + clientId = customerId; + } else if (!PhoneHomeRequestBody.Builder.UNKNOWN_ID.equals(hostName)) { + clientId = hostName; + } else { + clientId = PhoneHomeRequestBody.Builder.UNKNOWN_ID; + } + + final byte[] bytesFromString = clientId.getBytes(); + return UUID.nameUUIDFromBytes(bytesFromString).toString(); + } +} \ No newline at end of file diff --git a/src/test/java/com/synopsys/integration/phonehome/PhoneHomeClientUnitTest.java b/src/test/java/com/synopsys/integration/phonehome/PhoneHomeClientUnitTest.java index 21a9495..26a597f 100644 --- a/src/test/java/com/synopsys/integration/phonehome/PhoneHomeClientUnitTest.java +++ b/src/test/java/com/synopsys/integration/phonehome/PhoneHomeClientUnitTest.java @@ -1,12 +1,12 @@ package com.synopsys.integration.phonehome; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Collections; import java.util.HashMap; import java.util.Map; -import java.util.Optional; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; @@ -23,7 +23,7 @@ import com.synopsys.integration.phonehome.google.analytics.GoogleAnalyticsConstants; public class PhoneHomeClientUnitTest { - private static final RequestConfig DEFAULT_REQUEST_CONFIG = PhoneHomeClient.createInitialRequestConfigBuilder(5, Optional.empty()).build(); + private static final RequestConfig DEFAULT_REQUEST_CONFIG = PhoneHomeClient.createInitialRequestConfigBuilder(5).build(); private Map defaultEnvironmentVariables; private PhoneHomeClient defaultClient; @@ -35,7 +35,7 @@ public void init() { logger.info("Test Class: PhoneHomeClientUnitTest"); defaultEnvironmentVariables = new HashMap<>(); defaultEnvironmentVariables.put(PhoneHomeClient.PHONE_HOME_URL_OVERRIDE_VARIABLE, GoogleAnalyticsConstants.BASE_URL + GoogleAnalyticsConstants.DEBUG_ENDPOINT); - defaultClient = new PhoneHomeClient(GoogleAnalyticsConstants.TEST_INTEGRATIONS_TRACKING_ID, logger); + defaultClient = new PhoneHomeClient(logger); } @Test @@ -55,7 +55,7 @@ public void callHomeIntegrationsTest() throws Exception { @Test public void callHomeSkip() throws Exception { final BufferedIntLogger logger = new BufferedIntLogger(); - final PhoneHomeClient clientWithTrackableLogger = new PhoneHomeClient(GoogleAnalyticsConstants.TEST_INTEGRATIONS_TRACKING_ID, logger, DEFAULT_REQUEST_CONFIG); + final PhoneHomeClient clientWithTrackableLogger = new PhoneHomeClient(logger, DEFAULT_REQUEST_CONFIG); final PhoneHomeRequestBody.Builder phoneHomeRequestBuilder = new PhoneHomeRequestBody.Builder(); phoneHomeRequestBuilder.setCustomerId("customerId"); @@ -122,22 +122,21 @@ public void validatePhoneHomeRequestBuilding() throws Exception { phoneHomeRequestBuilder.setProductVersion("productVersion"); phoneHomeRequestBuilder.addToMetaData("example_meta_data", "data"); - final Map builderMetaData = new HashMap<>(); - builderMetaData.putAll(phoneHomeRequestBuilder.getMetaData()); + final Map builderMetaData = new HashMap<>(phoneHomeRequestBuilder.getMetaData()); final PhoneHomeRequestBody phoneHomeRequest = phoneHomeRequestBuilder.build(); - assertTrue(phoneHomeRequestBuilder.getCustomerId().equals(phoneHomeRequest.getCustomerId())); - assertTrue(phoneHomeRequestBuilder.getArtifactId().equals(phoneHomeRequest.getArtifactId())); - assertTrue(phoneHomeRequestBuilder.getArtifactVersion().equals(phoneHomeRequest.getArtifactVersion())); - assertTrue(phoneHomeRequestBuilder.getProductId().equals(phoneHomeRequest.getProductId())); - assertTrue(phoneHomeRequestBuilder.getProductVersion().equals(phoneHomeRequest.getProductVersion())); - assertTrue(builderMetaData.equals((phoneHomeRequest.getMetaData()))); + assertEquals(phoneHomeRequestBuilder.getCustomerId(), phoneHomeRequest.getCustomerId()); + assertEquals(phoneHomeRequestBuilder.getArtifactId(), phoneHomeRequest.getArtifactId()); + assertEquals(phoneHomeRequestBuilder.getArtifactVersion(), phoneHomeRequest.getArtifactVersion()); + assertEquals(phoneHomeRequestBuilder.getProductId(), phoneHomeRequest.getProductId()); + assertEquals(phoneHomeRequestBuilder.getProductVersion(), phoneHomeRequest.getProductVersion()); + assertEquals(builderMetaData, phoneHomeRequest.getMetaData()); } @Test public void validateBadPhoneHomeBackend() { - PhoneHomeClient phClient = new PhoneHomeClient(null, null); + PhoneHomeClient phClient = new PhoneHomeClient(null); try { phClient.postPhoneHomeRequest(null, Collections.emptyMap()); fail("Phone home exception not thrown"); @@ -145,7 +144,7 @@ public void validateBadPhoneHomeBackend() { // Do nothing } - phClient = new PhoneHomeClient(null, null, (RequestConfig) null); + phClient = new PhoneHomeClient(null, (RequestConfig) null); try { phClient.postPhoneHomeRequest(null, Collections.emptyMap()); fail("Phone home exception not thrown"); @@ -153,7 +152,7 @@ public void validateBadPhoneHomeBackend() { // Do nothing } - phClient = new PhoneHomeClient(null, null, (HttpClientBuilder) null); + phClient = new PhoneHomeClient(null, (HttpClientBuilder) null); try { phClient.postPhoneHomeRequest(null, Collections.emptyMap()); fail("Phone home exception not thrown"); @@ -161,7 +160,7 @@ public void validateBadPhoneHomeBackend() { // Do nothing } - phClient = new PhoneHomeClient(null, null, (RequestConfig) null, (Gson) null); + phClient = new PhoneHomeClient(null, (RequestConfig) null, (Gson) null); try { phClient.postPhoneHomeRequest(null, Collections.emptyMap()); fail("Phone home exception not thrown"); @@ -169,7 +168,7 @@ public void validateBadPhoneHomeBackend() { // Do nothing } - phClient = new PhoneHomeClient(null, null, (HttpClientBuilder) null, (Gson) null); + phClient = new PhoneHomeClient(null, (HttpClientBuilder) null, (Gson) null); try { phClient.postPhoneHomeRequest(null, Collections.emptyMap()); fail("Phone home exception not thrown"); @@ -181,7 +180,7 @@ public void validateBadPhoneHomeBackend() { @Test public void createInitialRequestConfigBuilderWithProxyHostTest() { final HttpHost proxyHost = new HttpHost("localhost:8081"); - PhoneHomeClient.createInitialRequestConfigBuilder(5, Optional.of(proxyHost)); + PhoneHomeClient.createInitialRequestConfigBuilder(5, proxyHost); } } diff --git a/src/test/java/com/synopsys/integration/phonehome/google/analytics/GoogleAnalyticsRequestHelperTest.java b/src/test/java/com/synopsys/integration/phonehome/google/analytics/GoogleAnalyticsRequestHelperTest.java index d8d92dc..58fcc7d 100644 --- a/src/test/java/com/synopsys/integration/phonehome/google/analytics/GoogleAnalyticsRequestHelperTest.java +++ b/src/test/java/com/synopsys/integration/phonehome/google/analytics/GoogleAnalyticsRequestHelperTest.java @@ -45,15 +45,63 @@ public void basicRequestTest() throws IOException { bodyBuilder.addToMetaData("exampleMetaData_3", "special chars: !@#$%^&*()<>?,.;`~\\|{{}[]]-=_+"); bodyBuilder.addToMetaData("example meta data 4", "string \" with \"quotes\" \" \" "); - final GoogleAnalyticsRequestHelper helper = new GoogleAnalyticsRequestHelper(new Gson(), GoogleAnalyticsConstants.TEST_INTEGRATIONS_TRACKING_ID, bodyBuilder.build()); + final GoogleAnalyticsRequestHelper helper = new GoogleAnalyticsRequestHelper(new Gson()); - final HttpPost request = helper.createRequest(debugUrl); + final HttpPost request = helper.createRequest(bodyBuilder.build(), debugUrl, GoogleAnalyticsConstants.TEST_INTEGRATIONS_TRACKING_ID); + final BufferedReader requestReader = new BufferedReader(new InputStreamReader(request.getEntity().getContent())); + + String nextRequestLine; + while ((nextRequestLine = requestReader.readLine()) != null) { + logger.info(nextRequestLine); + } + + final HttpClient client = HttpClientBuilder.create().build(); + + final HttpResponse response = client.execute(request); + int responseCode = response.getStatusLine().getStatusCode(); + logger.info("Response Code: " + responseCode); + + String nextLine; + final BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); + + logger.info("Response String:"); + while ((nextLine = reader.readLine()) != null) { + logger.info(nextLine); + } + + assertEquals(200, responseCode); + } + + @Test + public void batchRequestTest() throws IOException { + final String debugUrl = GoogleAnalyticsConstants.BASE_URL + GoogleAnalyticsConstants.DEBUG_ENDPOINT; + + final PhoneHomeRequestBody.Builder bodyBuilder = new PhoneHomeRequestBody.Builder(); + bodyBuilder.setCustomerId("fake_customer_id"); + bodyBuilder.setHostName("fake_host_name"); + bodyBuilder.setArtifactId("fake_artifact_id"); + bodyBuilder.setArtifactVersion("fake_artifact_version"); + bodyBuilder.setProductId(ProductIdEnum.CODE_CENTER); + bodyBuilder.setProductVersion("fake_product_version"); + bodyBuilder.setArtifactModules("fake_module_1", "fake_module_2", "fake_module_3"); + + bodyBuilder.addToMetaData("exampleMetaData_1", "data"); + bodyBuilder.addToMetaData("exampleMetaData_2", "other Data"); + + final GoogleAnalyticsRequestHelper helper = new GoogleAnalyticsRequestHelper(new Gson()); + + final HttpPost request = helper.createRequest(bodyBuilder.build(), debugUrl, GoogleAnalyticsConstants.TEST_INTEGRATIONS_TRACKING_ID); + final BufferedReader requestReader = new BufferedReader(new InputStreamReader(request.getEntity().getContent())); + + String nextRequestLine; + while ((nextRequestLine = requestReader.readLine()) != null) { + logger.info(nextRequestLine); + } final HttpClient client = HttpClientBuilder.create().build(); - int responseCode = -1; final HttpResponse response = client.execute(request); - responseCode = response.getStatusLine().getStatusCode(); + int responseCode = response.getStatusLine().getStatusCode(); logger.info("Response Code: " + responseCode); String nextLine;