You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@unomi.apache.org by GitBox <gi...@apache.org> on 2021/03/31 10:34:04 UTC

[GitHub] [unomi] dgriffon opened a new pull request #273: UNOMI-449 : forward existing endpoints to jax-rs endpoints

dgriffon opened a new pull request #273:
URL: https://github.com/apache/unomi/pull/273


   see https://issues.apache.org/jira/browse/UNOMI-449 for details


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [unomi] jkevan commented on a change in pull request #273: UNOMI-449 : forward existing endpoints to jax-rs endpoints

Posted by GitBox <gi...@apache.org>.
jkevan commented on a change in pull request #273:
URL: https://github.com/apache/unomi/pull/273#discussion_r604981886



##########
File path: wab/src/main/java/org/apache/unomi/web/EventsCollectorServlet.java
##########
@@ -61,182 +44,23 @@ public void destroy() {
     }
 
     @Override
-    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
-        try {
-            doEvent(req, resp);
-        } catch (Throwable t) { // Here in order to return generic message instead of the whole stack trace in case of not caught exception
-            logger.error("EventsCollectorServlet failed to execute get", t);
-            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
-        }
+    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+        HttpServletRequestForwardWrapper.forward(request, response);
     }
 
     @Override
-    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
-        try {
-            doEvent(req, resp);
-        } catch (Throwable t) { // Here in order to return generic message instead of the whole stack trace in case of not caught exception
-            logger.error("EventsCollectorServlet failed to execute post", t);
-            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
-        }
+    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+        HttpServletRequestForwardWrapper.forward(request, response);
     }
 
     @Override
     protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

Review comment:
       Why not using the options implem of the endpoint by just forwarding the request here ?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [unomi] Taybou commented on a change in pull request #273: UNOMI-449 : forward existing endpoints to jax-rs endpoints

Posted by GitBox <gi...@apache.org>.
Taybou commented on a change in pull request #273:
URL: https://github.com/apache/unomi/pull/273#discussion_r604830197



##########
File path: rest/src/main/java/org/apache/unomi/rest/EventsCollectorEndpoint.java
##########
@@ -154,11 +139,13 @@ private EventCollectorResponse doEvent(String eventsCollectorRequestAsString, Lo
             */
         } else {
             Profile sessionProfile = session.getProfile();
+            final String errorMessage = String.format("No valid profile found or persona found for profileId=%s, aborting request !", session.getProfileId());
             if (sessionProfile.getItemId() != null) {
                 // Reload up-to-date profile
                 profile = profileService.load(sessionProfile.getItemId());
                 if (profile == null || profile instanceof Persona) {
-                    throw new InternalServerErrorException(String.format("No valid profile found or persona found for profileId=%s, aborting request !", session.getProfileId()));
+                    logger.error(errorMessage);

Review comment:
       maybe protect this message with "if (logger.isDebugEnabled()) {"
   




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [unomi] jkevan commented on a change in pull request #273: UNOMI-449 : forward existing endpoints to jax-rs endpoints

Posted by GitBox <gi...@apache.org>.
jkevan commented on a change in pull request #273:
URL: https://github.com/apache/unomi/pull/273#discussion_r604959127



##########
File path: rest/src/main/java/org/apache/unomi/rest/ContextJsonEndpoint.java
##########
@@ -82,9 +78,22 @@
     @Reference
     private ConfigSharingService configSharingService;
 
+    @OPTIONS
+    @Path("/context.json")
+    public Response options() {
+        return Response.status(Response.Status.NO_CONTENT).header("Access-Control-Allow-Origin", "*").build();
+    }
+
     @POST
     @Path("/context.json")
-    public ContextResponse getContextJSON(String contextRequestAsString, @QueryParam("timestamp") Long timestampAsLong, @CookieParam("context-profile-id") String cookieProfileId) {
+    public ContextResponse getContextJSON(

Review comment:
       We should also support @GET




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [unomi] dgriffon commented on a change in pull request #273: UNOMI-449 : forward existing endpoints to jax-rs endpoints

Posted by GitBox <gi...@apache.org>.
dgriffon commented on a change in pull request #273:
URL: https://github.com/apache/unomi/pull/273#discussion_r605538220



##########
File path: rest/src/main/java/org/apache/unomi/rest/EventsCollectorEndpoint.java
##########
@@ -154,11 +139,13 @@ private EventCollectorResponse doEvent(String eventsCollectorRequestAsString, Lo
             */
         } else {
             Profile sessionProfile = session.getProfile();
+            final String errorMessage = String.format("No valid profile found or persona found for profileId=%s, aborting request !", session.getProfileId());
             if (sessionProfile.getItemId() != null) {
                 // Reload up-to-date profile
                 profile = profileService.load(sessionProfile.getItemId());
                 if (profile == null || profile instanceof Persona) {
-                    throw new InternalServerErrorException(String.format("No valid profile found or persona found for profileId=%s, aborting request !", session.getProfileId()));
+                    logger.error(errorMessage);

Review comment:
       This one will be protected higher in the chain, meaning we can keep it as it is




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [unomi] dgriffon merged pull request #273: UNOMI-449 : forward existing endpoints to jax-rs endpoints

Posted by GitBox <gi...@apache.org>.
dgriffon merged pull request #273:
URL: https://github.com/apache/unomi/pull/273


   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [unomi] dgriffon commented on a change in pull request #273: UNOMI-449 : forward existing endpoints to jax-rs endpoints

Posted by GitBox <gi...@apache.org>.
dgriffon commented on a change in pull request #273:
URL: https://github.com/apache/unomi/pull/273#discussion_r604850532



##########
File path: rest/src/main/java/org/apache/unomi/rest/EventsCollectorEndpoint.java
##########
@@ -154,11 +139,13 @@ private EventCollectorResponse doEvent(String eventsCollectorRequestAsString, Lo
             */
         } else {
             Profile sessionProfile = session.getProfile();
+            final String errorMessage = String.format("No valid profile found or persona found for profileId=%s, aborting request !", session.getProfileId());
             if (sessionProfile.getItemId() != null) {
                 // Reload up-to-date profile
                 profile = profileService.load(sessionProfile.getItemId());
                 if (profile == null || profile instanceof Persona) {
-                    throw new InternalServerErrorException(String.format("No valid profile found or persona found for profileId=%s, aborting request !", session.getProfileId()));
+                    logger.error(errorMessage);

Review comment:
       Thanks for the comment, you're right, we should protect the `session.getProfileId()` displayed in the logs




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [unomi] dgriffon commented on a change in pull request #273: UNOMI-449 : forward existing endpoints to jax-rs endpoints

Posted by GitBox <gi...@apache.org>.
dgriffon commented on a change in pull request #273:
URL: https://github.com/apache/unomi/pull/273#discussion_r606203663



##########
File path: rest/src/main/java/org/apache/unomi/rest/ContextJsonEndpoint.java
##########
@@ -82,9 +78,22 @@
     @Reference
     private ConfigSharingService configSharingService;
 
+    @OPTIONS
+    @Path("/context.json")
+    public Response options() {
+        return Response.status(Response.Status.NO_CONTENT).header("Access-Control-Allow-Origin", "*").build();
+    }
+
     @POST
     @Path("/context.json")
-    public ContextResponse getContextJSON(String contextRequestAsString, @QueryParam("timestamp") Long timestampAsLong, @CookieParam("context-profile-id") String cookieProfileId) {
+    public ContextResponse getContextJSON(

Review comment:
       done




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [unomi] jkevan commented on a change in pull request #273: UNOMI-449 : forward existing endpoints to jax-rs endpoints

Posted by GitBox <gi...@apache.org>.
jkevan commented on a change in pull request #273:
URL: https://github.com/apache/unomi/pull/273#discussion_r604961632



##########
File path: rest/src/main/java/org/apache/unomi/rest/ContextJsonEndpoint.java
##########
@@ -256,11 +244,9 @@ public ContextResponse getContextJSON(String contextRequestAsString, @QueryParam
             contextResponse.setSessionId(sessionId);
         }
 
-        if (contextRequest != null) {
-            Changes changesObject = handleRequest(contextRequest, session, profile, contextResponse, request, response, timestamp);
-            changes |= changesObject.getChangeType();
-            profile = changesObject.getProfile();
-        }
+        Changes changesObject = handleRequest(contextRequest, session, profile, contextResponse, request, response, timestamp);

Review comment:
       Thes servlet was able to answer even if contextRequest was null, it should be still possible.

##########
File path: wab/src/main/java/org/apache/unomi/web/HttpServletRequestForwardWrapper.java
##########
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.unomi.web;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletRequestWrapper;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.Enumeration;
+
+/**
+ * Http wrapper that force the content type to be "application/json"
+ */
+class HttpServletRequestForwardWrapper extends HttpServletRequestWrapper {
+
+    private static final Logger logger = LoggerFactory.getLogger(HttpServletRequestForwardWrapper.class.getName());
+    private static final String JSON_CONTENT_TYPE = "application/json";
+
+    public HttpServletRequestForwardWrapper(HttpServletRequest request) {
+        super(request);
+    }
+
+    /**
+     * Forward servlet request to jax-rs endpoints. For a given path, forward to /cxs + path.
+     *
+     * @param request  initial request
+     * @param response initial response
+     */
+    public static void forward(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+        try {
+            HttpServletRequest requestWrapper = new HttpServletRequestForwardWrapper(request);
+            requestWrapper.getServletContext().getContext("/cxs").getRequestDispatcher("/cxs" + request.getRequestURI()).forward(requestWrapper, response);
+        } catch (Exception t) { // Here in order to return generic message instead of the whole stack trace in case of not caught exception
+            logger.error("EventsCollectorServlet failed to execute request", t);

Review comment:
       Log doesnt seem's correct

##########
File path: wab/src/main/java/org/apache/unomi/web/ContextServlet.java
##########
@@ -71,396 +53,21 @@ public void init(ServletConfig config) throws ServletException {
     }
 
     @Override
-    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
-        try {
-            final Date timestamp = new Date();
-            if (request.getParameter("timestamp") != null) {
-                try {
-                    timestamp.setTime(Long.parseLong(request.getParameter("timestamp")));
-                } catch (NumberFormatException e) {
-                    // catch to avoid logging the error with the timestamp value to avoid potential log injection
-                    logger.error("Invalid timestamp parameter");
-                    return;
-                }
-            }
-
-            // set up CORS headers as soon as possible so that errors are not misconstrued on the client for CORS errors
+    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+        if ("options".equalsIgnoreCase(request.getMethod())) {
             HttpUtils.setupCORSHeaders(request, response);
-
-            // Handle OPTIONS request
-            String httpMethod = request.getMethod();
-            if ("options".equals(httpMethod.toLowerCase())) {
-                response.flushBuffer();
-                if (logger.isDebugEnabled()) {
-                    logger.debug("OPTIONS request received. No context will be returned.");
-                }
-                return;
-            }
-
-            // Handle persona
-            Profile profile = null;
-            Session session = null;
-            String personaId = request.getParameter("personaId");
-            if (personaId != null) {
-                PersonaWithSessions personaWithSessions = profileService.loadPersonaWithSessions(personaId);
-                if (personaWithSessions == null) {
-                    logger.error("Couldn't find persona, please check your personaId parameter");
-                    profile = null;
-                } else {
-                    profile = personaWithSessions.getPersona();
-                    session = personaWithSessions.getLastSession();
-                }
-            }
-
-            // Extract payload
-            ContextRequest contextRequest = null;
-            String scope = null;
-            String sessionId = null;
-            String profileId = null;
-            String stringPayload = HttpUtils.getPayload(request);
-            if (stringPayload != null) {
-                ObjectMapper mapper = CustomObjectMapper.getObjectMapper();
-                JsonFactory factory = mapper.getFactory();
-                try {
-                    contextRequest = mapper.readValue(factory.createParser(stringPayload), ContextRequest.class);
-                } catch (Exception e) {
-                    ((HttpServletResponse)response).sendError(HttpServletResponse.SC_BAD_REQUEST, "Check logs for more details");
-                    logger.error("Cannot deserialize the context request payload. See debug level for more information");
-                    if (logger.isDebugEnabled()) {
-                        logger.debug("Cannot deserialize the context request payload: {}", stringPayload, e);
-                    }
-                    return;
-                }
-                if (contextRequest.getSource() != null) {
-                    scope = contextRequest.getSource().getScope();
-                }
-                sessionId = contextRequest.getSessionId();
-                profileId = contextRequest.getProfileId();
-            }
-
-            if (sessionId == null) {
-                sessionId = request.getParameter("sessionId");
-            }
-
-            if (profileId == null) {
-                // Get profile id from the cookie
-                profileId = ServletCommon.getProfileIdCookieValue(request, profileIdCookieName);
-            }
-
-            if (profileId == null && sessionId == null && personaId == null) {
-                ((HttpServletResponse)response).sendError(HttpServletResponse.SC_BAD_REQUEST, "Check logs for more details");
-                logger.error("Couldn't find profileId, sessionId or personaId in incoming request! Stopped processing request. See debug level for more information");
-                if (logger.isDebugEnabled()) {
-                    logger.debug("Request dump: {}", HttpUtils.dumpRequestInfo(request));
-                }
-                return;
-            }
-
-            int changes = EventService.NO_CHANGE;
-            if (profile == null) {
-                // Not a persona, resolve profile now
-                boolean profileCreated = false;
-
-                boolean invalidateProfile = request.getParameter("invalidateProfile") != null ?
-                        new Boolean(request.getParameter("invalidateProfile")) : false;
-                if (profileId == null || invalidateProfile) {
-                    // no profileId cookie was found or the profile has to be invalidated, we generate a new one and create the profile in the profile service
-                    profile = createNewProfile(null, response, timestamp);
-                    profileCreated = true;
-                } else {
-                    profile = profileService.load(profileId);
-                    if (profile == null) {
-                        // this can happen if we have an old cookie but have reset the server,
-                        // or if we merged the profiles and somehow this cookie didn't get updated.
-                        profile = createNewProfile(profileId, response, timestamp);
-                        profileCreated = true;
-                    } else {
-                        Changes changesObject = checkMergedProfile(response, profile, session);
-                        changes |= changesObject.getChangeType();
-                        profile = changesObject.getProfile();
-                    }
-                }
-
-                Profile sessionProfile;
-                boolean invalidateSession = request.getParameter("invalidateSession") != null ?
-                        new Boolean(request.getParameter("invalidateSession")) : false;
-                if (StringUtils.isNotBlank(sessionId) && !invalidateSession) {
-                    session = profileService.loadSession(sessionId, timestamp);
-                    if (session != null) {
-                        sessionProfile = session.getProfile();
-
-                        boolean anonymousSessionProfile = sessionProfile.isAnonymousProfile();
-                        if (!profile.isAnonymousProfile() && !anonymousSessionProfile && !profile.getItemId().equals(sessionProfile.getItemId())) {
-                            // Session user has been switched, profile id in cookie is not up to date
-                            // We must reload the profile with the session ID as some properties could be missing from the session profile
-                            // #personalIdentifier
-                            profile = profileService.load(sessionProfile.getItemId());
-                            if (profile != null) {
-                                HttpUtils.sendProfileCookie(profile, response, profileIdCookieName, profileIdCookieDomain, profileIdCookieMaxAgeInSeconds);
-                            } else {
-                                logger.warn("Couldn't load profile {} referenced in session {}", sessionProfile.getItemId(), session.getItemId());
-                            }
-                        }
-
-                        // Handle anonymous situation
-                        Boolean requireAnonymousBrowsing = privacyService.isRequireAnonymousBrowsing(profile);
-                        if (requireAnonymousBrowsing && anonymousSessionProfile) {
-                            // User wants to browse anonymously, anonymous profile is already set.
-                        } else if (requireAnonymousBrowsing && !anonymousSessionProfile) {
-                            // User wants to browse anonymously, update the sessionProfile to anonymous profile
-                            sessionProfile = privacyService.getAnonymousProfile(profile);
-                            session.setProfile(sessionProfile);
-                            changes |= EventService.SESSION_UPDATED;
-                        } else if (!requireAnonymousBrowsing && anonymousSessionProfile) {
-                            // User does not want to browse anonymously anymore, update the sessionProfile to real profile
-                            sessionProfile = profile;
-                            session.setProfile(sessionProfile);
-                            changes |= EventService.SESSION_UPDATED;
-                        } else if (!requireAnonymousBrowsing && !anonymousSessionProfile) {
-                            // User does not want to browse anonymously, use the real profile. Check that session contains the current profile.
-                            sessionProfile = profile;
-                            if (!session.getProfileId().equals(sessionProfile.getItemId())) {
-                                changes |= EventService.SESSION_UPDATED;
-                            }
-                            session.setProfile(sessionProfile);
-                        }
-                    }
-                }
-
-                if (session == null || invalidateSession) {
-                    sessionProfile = privacyService.isRequireAnonymousBrowsing(profile) ? privacyService.getAnonymousProfile(profile) : profile;
-
-                    if (StringUtils.isNotBlank(sessionId)) {
-                        // Only save session and send event if a session id was provided, otherwise keep transient session
-                        session = new Session(sessionId, sessionProfile, timestamp, scope);
-                        changes |= EventService.SESSION_UPDATED;
-                        Event event = new Event("sessionCreated", session, profile, scope, null, session, timestamp);
-                        if (sessionProfile.isAnonymousProfile()) {
-                            // Do not keep track of profile in event
-                            event.setProfileId(null);
-                        }
-                        event.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request);
-                        event.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response);
-                        if (logger.isDebugEnabled()) {
-                            logger.debug("Received event {} for profile={} session={} target={} timestamp={}",
-                                    event.getEventType(), profile.getItemId(), session.getItemId(), event.getTarget(), timestamp);
-                        }
-                        changes |= eventService.send(event);
-                    }
-                }
-
-                if (profileCreated) {
-                    changes |= EventService.PROFILE_UPDATED;
-
-                    Event profileUpdated = new Event("profileUpdated", session, profile, scope, null, profile, timestamp);
-                    profileUpdated.setPersistent(false);
-                    profileUpdated.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request);
-                    profileUpdated.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response);
-
-                    if (logger.isDebugEnabled()) {
-                        logger.debug("Received event {} for profile={} {} target={} timestamp={}", profileUpdated.getEventType(), profile.getItemId(),
-                                " session=" + (session != null ? session.getItemId() : null), profileUpdated.getTarget(), timestamp);
-                    }
-                    changes |= eventService.send(profileUpdated);
-                }
-            }
-
-            ContextResponse contextResponse = new ContextResponse();
-            contextResponse.setProfileId(profile.getItemId());
-            if (session != null) {
-                contextResponse.setSessionId(session.getItemId());
-            } else if (sessionId != null) {
-                contextResponse.setSessionId(sessionId);
-            }
-
-            if (contextRequest != null) {
-                Changes changesObject = handleRequest(contextRequest, session, profile, contextResponse, request, response, timestamp);
-                changes |= changesObject.getChangeType();
-                profile = changesObject.getProfile();
-            }
-
-            if ((changes & EventService.PROFILE_UPDATED) == EventService.PROFILE_UPDATED) {
-                profileService.save(profile);
-                contextResponse.setProfileId(profile.getItemId());
-            }
-            if ((changes & EventService.SESSION_UPDATED) == EventService.SESSION_UPDATED && session != null) {
-                profileService.saveSession(session);
-                contextResponse.setSessionId(session.getItemId());
-            }
-
-            if ((changes & EventService.ERROR) == EventService.ERROR) {
-                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
-            }
-
-            String extension = request.getRequestURI().substring(request.getRequestURI().lastIndexOf(".") + 1);
-            boolean noScript = "json".equals(extension);
-            String contextAsJSONString = CustomObjectMapper.getObjectMapper().writeValueAsString(contextResponse);
-            Writer responseWriter;
-            response.setCharacterEncoding("UTF-8");
-            if (noScript) {
-                responseWriter = response.getWriter();
-                response.setContentType("application/json");
-                IOUtils.write(contextAsJSONString, responseWriter);
-            } else {
-                responseWriter = response.getWriter();
-                responseWriter.append("window.digitalData = window.digitalData || {};\n")
-                        .append("var cxs = ")
-                        .append(contextAsJSONString)
-                        .append(";\n");
-            }
-
-            responseWriter.flush();
-        } catch (Throwable t) { // Here in order to return generic message instead of the whole stack trace in case of not caught exception
-            logger.error("ContextServlet failed to execute request", t);
-            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
-        }
-    }
-
-    private Changes checkMergedProfile(ServletResponse response, Profile profile, Session session) {
-        int changes = EventService.NO_CHANGE;
-        if (profile.getMergedWith() != null && !privacyService.isRequireAnonymousBrowsing(profile) && !profile.isAnonymousProfile()) {
-            Profile currentProfile = profile;
-            String masterProfileId = profile.getMergedWith();
-            Profile masterProfile = profileService.load(masterProfileId);
-            if (masterProfile != null) {
-                logger.info("Current profile {} was merged with profile {}, replacing profile in session", currentProfile.getItemId(), masterProfileId);
-                profile = masterProfile;
-                if (session != null) {
-                    session.setProfile(profile);
-                    changes = EventService.SESSION_UPDATED;
-                }
-                HttpUtils.sendProfileCookie(profile, response, profileIdCookieName, profileIdCookieDomain, profileIdCookieMaxAgeInSeconds);
-            } else {
-                logger.warn("Couldn't find merged profile {}, falling back to profile {}", masterProfileId, currentProfile.getItemId());
-                profile = currentProfile;
-                profile.setMergedWith(null);
-                changes = EventService.PROFILE_UPDATED;
-            }
-        }
-
-        return new Changes(changes, profile);
-    }
-
-    private Changes handleRequest(ContextRequest contextRequest, Session session, Profile profile, ContextResponse data,
-                                  ServletRequest request, ServletResponse response, Date timestamp) {
-        Changes changes = ServletCommon.handleEvents(contextRequest.getEvents(), session, profile, request, response, timestamp,
-                privacyService, eventService);
-        data.setProcessedEvents(changes.getProcessedItems());
-
-        profile = changes.getProfile();
-
-        if (contextRequest.isRequireSegments()) {
-            data.setProfileSegments(profile.getSegments());
-        }
-
-        if (contextRequest.getRequiredProfileProperties() != null) {
-            Map<String, Object> profileProperties = new HashMap<>(profile.getProperties());
-            if (!contextRequest.getRequiredProfileProperties().contains("*")) {
-                profileProperties.keySet().retainAll(contextRequest.getRequiredProfileProperties());
-            }
-            data.setProfileProperties(profileProperties);
-        }
-
-        if (session != null) {
-            data.setSessionId(session.getItemId());
-            if (contextRequest.getRequiredSessionProperties() != null) {
-                Map<String, Object> sessionProperties = new HashMap<>(session.getProperties());
-                if (!contextRequest.getRequiredSessionProperties().contains("*")) {
-                    sessionProperties.keySet().retainAll(contextRequest.getRequiredSessionProperties());
-                }
-                data.setSessionProperties(sessionProperties);
-            }
-        }
-
-        processOverrides(contextRequest, profile, session);
-
-        List<PersonalizationService.PersonalizedContent> filterNodes = contextRequest.getFilters();
-        if (filterNodes != null) {
-            data.setFilteringResults(new HashMap<>());
-            for (PersonalizationService.PersonalizedContent personalizedContent : sanitizePersonalizedContentObjects(filterNodes)) {
-                data.getFilteringResults().put(personalizedContent.getId(), personalizationService.filter(profile,
-                        session, personalizedContent));
-            }
-        }
-
-        List<PersonalizationService.PersonalizationRequest> personalizations = contextRequest.getPersonalizations();
-        if (personalizations != null) {
-            data.setPersonalizations(new HashMap<>());
-            for (PersonalizationService.PersonalizationRequest personalization : sanitizePersonalizations(personalizations)) {
-                data.getPersonalizations().put(personalization.getId(), personalizationService.personalizeList(profile,
-                        session, personalization));
-            }
-        }
-
-        if (!(profile instanceof Persona)) {
-            data.setTrackedConditions(rulesService.getTrackedConditions(contextRequest.getSource()));
-        } else {
-            data.setTrackedConditions(Collections.emptySet());
-        }
-
-        data.setAnonymousBrowsing(privacyService.isRequireAnonymousBrowsing(profile));
-        data.setConsents(profile.getConsents());
-
-        return changes;
-    }
-
-    /**
-     * This function will update the profile if it is from Persona instance.
-     * The profile will be updated using the overrides attributes :
-     * - profileOverrides for profile properties, segments and scores
-     * - sessionPropertiesOverrides for session properties
-     * @param contextRequest
-     * @param profile
-     * @param session
-     */
-    private void processOverrides(ContextRequest contextRequest, Profile profile, Session session) {
-        if (profile instanceof Persona) {
-            if (contextRequest.getProfileOverrides() != null) {
-                if (contextRequest.getProfileOverrides().getScores()!=null) {
-                    profile.setScores(contextRequest.getProfileOverrides().getScores());
-                }
-                if (contextRequest.getProfileOverrides().getSegments()!=null) {
-                    profile.setSegments(contextRequest.getProfileOverrides().getSegments());
-                }
-                if (contextRequest.getProfileOverrides().getProperties()!=null) {
-                    profile.setProperties(contextRequest.getProfileOverrides().getProperties());
-                }
-                if (contextRequest.getSessionPropertiesOverrides()!=null && session != null) {
-                    session.setProperties(contextRequest.getSessionPropertiesOverrides());
-                }
-            }
+            response.flushBuffer();
+            logger.debug("OPTIONS request received. No context will be returned.");
+            return;

Review comment:
       Options should also be implemented in the REST endpoint, so like the event collector, we could just forward the request and implement the option in the endpoint




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org