Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Event endpoint to handle notifications was implemented #296

Merged
merged 6 commits into from
Mar 7, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package org.prebid.server.analytics.model;

import lombok.AllArgsConstructor;
import lombok.Value;

@AllArgsConstructor(staticName = "of")
@Value
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use static factory of method for consistency

public class NotificationEvent {
String type;

String bidId;

String bidder;
}
143 changes: 143 additions & 0 deletions src/main/java/org/prebid/server/handler/NotificationEventHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
package org.prebid.server.handler;

import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpHeaders;
import io.vertx.ext.web.RoutingContext;
import lombok.AllArgsConstructor;
import lombok.Value;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.prebid.server.analytics.AnalyticsReporter;
import org.prebid.server.analytics.model.HttpContext;
import org.prebid.server.analytics.model.NotificationEvent;
import org.prebid.server.exception.InvalidRequestException;
import org.prebid.server.util.ResourceUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
* Accepts notifications from browsers and mobile application for further processing by {@link AnalyticsReporter}
* and responding with tracking pixel when requested.
*/
public class NotificationEventHandler implements Handler<RoutingContext> {

private static final String TRACKING_PIXEL_PNG = "static/tracking-pixel.png";
private static final String TRACKING_PIXEL_JPG = "static/tracking-pixel.jpg";
private static final String VIEW_TYPE = "view";
private static final String WIN_TYPE = "win";
private static final String FORMAT_PARAMETER = "format";
private static final String TYPE_PARAMETER = "type";
private static final String BID_ID_PARAMETER = "bidid";
private static final String BIDDER_PARAMETER = "bidder";
private static final String JPG_FORMAT = "jpg";
private static final String PNG_FORMAT = "png";
private static final String JPG_CONTENT_TYPE = "image/jpeg";
private static final String PNG_CONTENT_TYPE = "image/png";

private final AnalyticsReporter analyticsReporter;
private final Map<String, TrackingPixel> trackingPixels;

private NotificationEventHandler(AnalyticsReporter analyticsReporter, Map<String, TrackingPixel> trackingPixels) {
this.analyticsReporter = analyticsReporter;
this.trackingPixels = trackingPixels;
}

public static NotificationEventHandler create(AnalyticsReporter analyticsReporter) {
final Map<String, TrackingPixel> trackingPixels = new HashMap<>();
trackingPixels.put(JPG_FORMAT, TrackingPixel.of(JPG_CONTENT_TYPE, readTrackingPixel(TRACKING_PIXEL_JPG)));
trackingPixels.put(PNG_FORMAT, TrackingPixel.of(PNG_CONTENT_TYPE, readTrackingPixel(TRACKING_PIXEL_PNG)));
return new NotificationEventHandler(Objects.requireNonNull(analyticsReporter), trackingPixels);
}

@Override
public void handle(RoutingContext context) {
final MultiMap queryParameters = context.request().params();

final NotificationEvent notificationEvent;
try {
notificationEvent = makeNotificationEvent(queryParameters);
} catch (InvalidRequestException ex) {
respondWithBadStatus(context, ex.getMessage());
return;
}

analyticsReporter.processEvent(notificationEvent);

final Map<String, String> queryParams = HttpContext.from(context).getQueryParams();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is not need to create HttpContext for the sake of just reading a query parameter - it could be read from context directly.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Has this been addressed somehow?

final String format = queryParams.get(FORMAT_PARAMETER);

try {
validateEventRequestQueryParams(format);
} catch (InvalidRequestException ex) {
respondWithBadStatus(context, ex.getMessage());
return;
}

respondWithOkStatus(context, format);
}

private static byte[] readTrackingPixel(String path) {
try {
return ResourceUtil.readByteArrayFromClassPath(path);
} catch (IOException e) {
throw new IllegalArgumentException(String.format("Failed to load pixel image at %s", path), e);
}
}

private NotificationEvent makeNotificationEvent(MultiMap queryParameters) {
final String type = queryParameters.get(TYPE_PARAMETER);
if (ObjectUtils.notEqual(type, VIEW_TYPE) && ObjectUtils.notEqual(type, WIN_TYPE)) {
throw new InvalidRequestException(String.format(
"Type is required query parameter. Possible values are win and view, but was %s", type));
}

final String bidId = queryParameters.get(BID_ID_PARAMETER);
if (StringUtils.isBlank(bidId)) {
throw new InvalidRequestException("bidid is required query parameter and can't be empty.");
}

final String bidder = queryParameters.get(BIDDER_PARAMETER);
if (StringUtils.isBlank(bidder)) {
throw new InvalidRequestException("bidder is required query parameter and can't be empty.");
}
return NotificationEvent.of(type, bidId, bidder);
}

private void validateEventRequestQueryParams(String format) {
if (format != null && ObjectUtils.notEqual(format, JPG_FORMAT) && ObjectUtils.notEqual(format, PNG_FORMAT)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is better to be replaced with if( format != null && trackingPixels.containsKey(format))

throw new InvalidRequestException("format when defined should has value of png or jpg.");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's better to pull format parameter values from trackingPixels map

}
}

private void respondWithBadStatus(RoutingContext context, String message) {
context.response().setStatusCode(HttpResponseStatus.BAD_REQUEST.code())
.end(String.format("Request is invalid: %s", message));
}

private void respondWithOkStatus(RoutingContext context, String format) {
if (format != null) {
final TrackingPixel trackingPixel = trackingPixels.get(format);
context.response()
.putHeader(HttpHeaders.CONTENT_TYPE, trackingPixel.getContentType())
.end(Buffer.buffer(trackingPixel.getContent()));
} else {
context.response().end();
}
}

/**
* Internal class for holding pixels content type to its value
*/
@AllArgsConstructor(staticName = "of")
@Value
private static class TrackingPixel {
String contentType;
byte[] content;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import org.prebid.server.handler.CurrencyRatesHandler;
import org.prebid.server.handler.ExceptionHandler;
import org.prebid.server.handler.NoCacheHandler;
import org.prebid.server.handler.NotificationEventHandler;
import org.prebid.server.handler.OptoutHandler;
import org.prebid.server.handler.SettingsCacheNotificationHandler;
import org.prebid.server.handler.SetuidHandler;
Expand Down Expand Up @@ -146,6 +147,7 @@ Router router(CookieHandler cookieHandler,
BidderParamHandler bidderParamHandler,
BiddersHandler biddersHandler,
BidderDetailsHandler bidderDetailsHandler,
NotificationEventHandler notificationEventHandler,
StaticHandler staticHandler) {

final Router router = Router.router(vertx);
Expand All @@ -164,6 +166,7 @@ Router router(CookieHandler cookieHandler,
router.get("/bidders/params").handler(bidderParamHandler);
router.get("/info/bidders").handler(biddersHandler);
router.get("/info/bidders/:bidderName").handler(bidderDetailsHandler);
router.get("/event").handler(notificationEventHandler);
router.get("/static/*").handler(staticHandler);
router.get("/").handler(staticHandler); // serves index.html by default

Expand Down Expand Up @@ -307,6 +310,11 @@ BidderDetailsHandler bidderDetailsHandler(BidderCatalog bidderCatalog) {
return new BidderDetailsHandler(bidderCatalog);
}

@Bean
NotificationEventHandler eventNotificationHandler(CompositeAnalyticsReporter compositeAnalyticsReporter) {
return NotificationEventHandler.create(compositeAnalyticsReporter);
}

@Bean
StaticHandler staticHandler() {
return StaticHandler.create("static").setCachingEnabled(false);
Expand Down
13 changes: 13 additions & 0 deletions src/main/java/org/prebid/server/util/ResourceUtil.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.prebid.server.util;

import org.apache.commons.compress.utils.IOUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
Expand Down Expand Up @@ -30,4 +32,15 @@ public static String readFromClasspath(String path) throws IOException {
return reader.lines().collect(Collectors.joining("\n"));
}
}

/**
* Reads files from classpath as array of bytes. Throws {@link IllegalArgumentException} if file was not found.
*/
public static byte[] readByteArrayFromClassPath(String path) throws IOException {
final InputStream resourceAsStream = ResourceUtil.class.getClassLoader().getResourceAsStream(path);
if (resourceAsStream == null) {
throw new IllegalArgumentException(String.format("Could not find file at path: %s", path));
}
return IOUtils.toByteArray(resourceAsStream);
}
}
Binary file added src/main/resources/static/tracking-pixel.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/main/resources/static/tracking-pixel.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
19 changes: 19 additions & 0 deletions src/test/java/org/prebid/server/ApplicationTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.prebid.server.proto.response.BidderUsersyncStatus;
import org.prebid.server.proto.response.CookieSyncResponse;
import org.prebid.server.proto.response.UsersyncInfo;
import org.prebid.server.util.ResourceUtil;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.springframework.boot.test.context.SpringBootTest;
Expand All @@ -47,8 +48,10 @@
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
Expand Down Expand Up @@ -1694,6 +1697,22 @@ public void infoBidderDetailsShouldReturnMetadataForBidder() throws IOException
.body(Matchers.equalTo(jsonFrom("info-bidders/test-info-bidder-details-response.json")));
}

@Test
public void eventHandlerShouldRespondWithJPGTrackingPixel() throws IOException {
given(spec)
.queryParam("type", "win")
.queryParam("bidid", "bidId")
.queryParam("bidder", "rubicon")
.queryParam("format", "jpg")
.get("/event")
.then()
.assertThat()
.statusCode(200)
.header("content-type", "image/jpeg")
.body(Matchers.equalTo(
Buffer.buffer(ResourceUtil.readByteArrayFromClassPath("static/tracking-pixel.jpg")).toString()));
}

@Test
public void shouldAskExchangeWithUpdatedSettingsFromCache() throws IOException, JSONException {
// given
Expand Down
Loading