EventApiClient { @Nullable EventResponse sendEvents(@NonNull Collection<String> events, @NonNull Map<String, String> headers) { if (events.isEmpty()) { Logger.verbose("EventApiClient - No analytics events to send."); return null; } URL url = runtimeConfig.getUrlConfig() .analyticsUrl() .appendEncodedPath(WARP9_PATH) .build(); if (url == null) { Logger.debug("Analytics URL is null, unable to send events."); return null; } List<JsonValue> eventJSON = new ArrayList<>(); for (String eventPayload : events) { try { eventJSON.add(JsonValue.parseString(eventPayload)); } catch (JsonException e) { Logger.error(e, "EventApiClient - Invalid eventPayload."); } } String payload = new JsonList(eventJSON).toString(); double sentAt = System.currentTimeMillis() / 1000.0; Request request = requestFactory.createRequest("POST", url) .setRequestBody(payload, "application/json") .setCompressRequestBody(true) .setHeader("X-UA-Sent-At", String.format(Locale.US, "%.3f", sentAt)) .addHeaders(headers); Logger.debug("EventApiClient - Sending analytics events. Request: %s Events: %s", request, events); Response<Void> response = request.safeExecute(); Logger.debug("EventApiClient - Analytics event response: %s", response); return response == null ? null : new EventResponse(response); } EventApiClient(@NonNull AirshipRuntimeConfig runtimeConfig); @VisibleForTesting  EventApiClient(@NonNull AirshipRuntimeConfig runtimeConfig,
                   @NonNull RequestFactory requestFactory);   }
@Test public void testSendEmptyEvents() { assertNull(client.sendEvents(new ArrayList<String>(), Collections.<String, String>emptyMap())); }
@Test public void testSendBody() throws IOException { testRequest.response = new Response.Builder<Void>(HttpURLConnection.HTTP_OK) .setResponseBody(events.toString()) .build(); EventResponse response = client.sendEvents(events, Collections.<String, String>emptyMap()); assertEquals("Event request body should match", testRequest.getRequestBody(), events.toString()); assertNotNull("Event response should not be null", response); assertEquals("Event response status should be 200", HttpURLConnection.HTTP_OK, response.getStatus()); }
@Test public void testRequestHeaders() { testRequest.response = new Response.Builder<Void>(HttpURLConnection.HTTP_OK) .setResponseBody(events.toString()) .build(); Map<String, String> headers = new HashMap<>(); headers.put("foo", "bar"); client.sendEvents(events, headers); Map<String, String> requestHeaders = testRequest.getRequestHeaders(); assertEquals("bar", requestHeaders.get("foo")); }
@Test public void testNullResponse() { testRequest.response = null; EventResponse response = client.sendEvents(events, Collections.<String, String>emptyMap()); assertNull(response); }