UNOMI-39 - anonymous browsing : do not store anonymous profile, keep only in 
session and event without id and personal data. Handle profile merge with 
anonymous browsing. Keep master profile in event to store personal properties, 
even when using anonymous browsing.


Project: http://git-wip-us.apache.org/repos/asf/incubator-unomi/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-unomi/commit/00761022
Tree: http://git-wip-us.apache.org/repos/asf/incubator-unomi/tree/00761022
Diff: http://git-wip-us.apache.org/repos/asf/incubator-unomi/diff/00761022

Branch: refs/heads/UNOMI-28-ES-2-X-UPGRADE
Commit: 007610226bd9bb92e930e045e7ae632cba5a3db7
Parents: 685f67f
Author: Thomas Draier <dra...@apache.org>
Authored: Mon Aug 22 13:54:31 2016 +0200
Committer: Thomas Draier <dra...@apache.org>
Committed: Mon Aug 22 13:54:31 2016 +0200

----------------------------------------------------------------------
 .../privacy/rest/PrivacyServiceEndPoint.java    |  12 +-
 .../privacy/internal/PrivacyServiceImpl.java    |   4 +-
 .../AllEventToProfilePropertiesAction.java      |   6 +-
 .../actions/EventToProfilePropertyAction.java   |   4 -
 .../actions/MergeProfilesOnPropertyAction.java  |  32 +++-
 .../baseplugin/actions/SendEventAction.java     |   1 +
 .../baseplugin/actions/SetPropertyAction.java   |   5 -
 .../resources/OSGI-INF/blueprint/blueprint.xml  |   1 +
 .../services/services/EventServiceImpl.java     |   2 +-
 .../services/services/ProfileServiceImpl.java   |   6 +
 .../org/apache/unomi/web/ContextServlet.java    | 148 ++++++++++---------
 .../unomi/web/EventsCollectorServlet.java       |  50 ++++---
 12 files changed, 148 insertions(+), 123 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-unomi/blob/00761022/extensions/privacy-extension/rest/src/main/java/org/apache/unomi/privacy/rest/PrivacyServiceEndPoint.java
----------------------------------------------------------------------
diff --git 
a/extensions/privacy-extension/rest/src/main/java/org/apache/unomi/privacy/rest/PrivacyServiceEndPoint.java
 
b/extensions/privacy-extension/rest/src/main/java/org/apache/unomi/privacy/rest/PrivacyServiceEndPoint.java
index 5ef088c..4964275 100644
--- 
a/extensions/privacy-extension/rest/src/main/java/org/apache/unomi/privacy/rest/PrivacyServiceEndPoint.java
+++ 
b/extensions/privacy-extension/rest/src/main/java/org/apache/unomi/privacy/rest/PrivacyServiceEndPoint.java
@@ -71,21 +71,21 @@ public class PrivacyServiceEndPoint {
     }
 
     @GET
-    @Path("/profiles/{profileId}/anonymous")
-    public Boolean isAnonymous(@PathParam("profileId") String profileId) {
+    @Path("/profiles/{profileId}/anonymousBrowsing")
+    public Boolean isAnonymousBrowsing(@PathParam("profileId") String 
profileId) {
         return privacyService.isRequireAnonymousBrowsing(profileId);
     }
 
     @POST
-    @Path("/profiles/{profileId}/anonymous")
-    public Response activateAnonymousSurfing(@PathParam("profileId") String 
profileId) {
+    @Path("/profiles/{profileId}/anonymousBrowsing")
+    public Response activateAnonymousBrowsing(@PathParam("profileId") String 
profileId) {
         Boolean r = privacyService.setRequireAnonymousBrowsing(profileId, 
true);
         return r ? Response.ok().build() : Response.serverError().build();
     }
 
     @DELETE
-    @Path("/profiles/{profileId}/anonymous")
-    public Response deactivateAnonymousSurfing(@PathParam("profileId") String 
profileId) {
+    @Path("/profiles/{profileId}/anonymousBrowsing")
+    public Response deactivateAnonymousBrowsing(@PathParam("profileId") String 
profileId) {
         Boolean r = privacyService.setRequireAnonymousBrowsing(profileId, 
false);
         return r ? Response.ok().build() : Response.serverError().build();
     }

http://git-wip-us.apache.org/repos/asf/incubator-unomi/blob/00761022/extensions/privacy-extension/services/src/main/java/org/apache/unomi/privacy/internal/PrivacyServiceImpl.java
----------------------------------------------------------------------
diff --git 
a/extensions/privacy-extension/services/src/main/java/org/apache/unomi/privacy/internal/PrivacyServiceImpl.java
 
b/extensions/privacy-extension/services/src/main/java/org/apache/unomi/privacy/internal/PrivacyServiceImpl.java
index 22ec95a..ef2f03b 100644
--- 
a/extensions/privacy-extension/services/src/main/java/org/apache/unomi/privacy/internal/PrivacyServiceImpl.java
+++ 
b/extensions/privacy-extension/services/src/main/java/org/apache/unomi/privacy/internal/PrivacyServiceImpl.java
@@ -158,11 +158,11 @@ public class PrivacyServiceImpl implements PrivacyService 
{
     }
 
     public Profile getAnonymousProfile(Profile profile) {
-        Profile anonymousProfile = new Profile(UUID.randomUUID().toString());
+        Profile anonymousProfile = new Profile();
         anonymousProfile.getSystemProperties().put("isAnonymousProfile", true);
         anonymousProfile.getProperties().putAll(profile.getProperties());
         
anonymousProfile.getProperties().keySet().removeAll(getDeniedProperties(profile.getItemId()));
-        profileService.save(anonymousProfile);
+//        profileService.save(anonymousProfile);
         return anonymousProfile;
     }
 

http://git-wip-us.apache.org/repos/asf/incubator-unomi/blob/00761022/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/AllEventToProfilePropertiesAction.java
----------------------------------------------------------------------
diff --git 
a/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/AllEventToProfilePropertiesAction.java
 
b/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/AllEventToProfilePropertiesAction.java
index 850e489..e11478f 100644
--- 
a/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/AllEventToProfilePropertiesAction.java
+++ 
b/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/AllEventToProfilePropertiesAction.java
@@ -62,10 +62,8 @@ public class AllEventToProfilePropertiesAction implements 
ActionExecutor {
             if (event.getProfile().getProperty(entry.getKey()) == null || 
!event.getProfile().getProperty(entry.getKey()).equals(event.getProperty(entry.getKey())))
 {
                 String propertyMapping = 
profileService.getPropertyTypeMapping(entry.getKey());
                 String propertyName = (propertyMapping != null) ? 
propertyMapping : entry.getKey();
-                if (!event.getProfile().isAnonymousProfile() || 
!privacyService.getDeniedProperties(event.getProfileId()).contains(propertyName))
 {
-                    event.getProfile().setProperty(propertyName, 
entry.getValue());
-                    changed = true;
-                }
+                event.getProfile().setProperty(propertyName, entry.getValue());
+                changed = true;
             }
         }
         return changed ? EventService.PROFILE_UPDATED : EventService.NO_CHANGE;

http://git-wip-us.apache.org/repos/asf/incubator-unomi/blob/00761022/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/EventToProfilePropertyAction.java
----------------------------------------------------------------------
diff --git 
a/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/EventToProfilePropertyAction.java
 
b/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/EventToProfilePropertyAction.java
index 8efb43e..19dc57c 100644
--- 
a/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/EventToProfilePropertyAction.java
+++ 
b/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/EventToProfilePropertyAction.java
@@ -38,10 +38,6 @@ public class EventToProfilePropertyAction implements 
ActionExecutor {
         String eventPropertyName = (String) 
action.getParameterValues().get("eventPropertyName");
         String profilePropertyName = (String) 
action.getParameterValues().get("profilePropertyName");
 
-        if (event.getProfile().isAnonymousProfile() && 
privacyService.getDeniedProperties(event.getProfileId()).contains(profilePropertyName))
 {
-            return EventService.NO_CHANGE;
-        }
-
         if (event.getProfile().getProperty(profilePropertyName) == null || 
!event.getProfile().getProperty(profilePropertyName).equals(event.getProperty(eventPropertyName)))
 {
             event.getProfile().setProperty(profilePropertyName, 
event.getProperty(eventPropertyName));
             return EventService.PROFILE_UPDATED;

http://git-wip-us.apache.org/repos/asf/incubator-unomi/blob/00761022/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/MergeProfilesOnPropertyAction.java
----------------------------------------------------------------------
diff --git 
a/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/MergeProfilesOnPropertyAction.java
 
b/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/MergeProfilesOnPropertyAction.java
index 2edc98b..12def48 100644
--- 
a/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/MergeProfilesOnPropertyAction.java
+++ 
b/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/MergeProfilesOnPropertyAction.java
@@ -28,6 +28,7 @@ import org.apache.unomi.api.actions.ActionPostExecutor;
 import org.apache.unomi.api.conditions.Condition;
 import org.apache.unomi.api.services.DefinitionsService;
 import org.apache.unomi.api.services.EventService;
+import org.apache.unomi.api.services.PrivacyService;
 import org.apache.unomi.api.services.ProfileService;
 import org.apache.unomi.persistence.spi.PersistenceService;
 import org.slf4j.Logger;
@@ -56,6 +57,8 @@ public class MergeProfilesOnPropertyAction implements 
ActionExecutor {
 
     private DefinitionsService definitionsService;
 
+    private PrivacyService privacyService;
+
     public void setCookieAgeInSeconds(int cookieAgeInSeconds) {
         this.cookieAgeInSeconds = cookieAgeInSeconds;
     }
@@ -88,6 +91,10 @@ public class MergeProfilesOnPropertyAction implements 
ActionExecutor {
         return definitionsService;
     }
 
+    public void setPrivacyService(PrivacyService privacyService) {
+        this.privacyService = privacyService;
+    }
+
     public void setDefinitionsService(DefinitionsService definitionsService) {
         this.definitionsService = definitionsService;
     }
@@ -152,9 +159,9 @@ public class MergeProfilesOnPropertyAction implements 
ActionExecutor {
             event.setProfileId(profile.getItemId());
             event.setProfile(profile);
 
-            event.getSession().setProfile(profile);
+            currentSession.setProfile(profile);
 
-            eventService.send(new Event("sessionReassigned", 
event.getSession(), profile, event.getScope(), event, event.getSession(), 
event.getTimeStamp()));
+            eventService.send(new Event("sessionReassigned", currentSession, 
profile, event.getScope(), event, currentSession, event.getTimeStamp()));
 
             return EventService.PROFILE_UPDATED + EventService.SESSION_UPDATED;
         } else {
@@ -175,19 +182,28 @@ public class MergeProfilesOnPropertyAction implements 
ActionExecutor {
             }
 
             // Use oldest profile for master profile
-            Profile masterProfile = 
profileService.mergeProfiles(profiles.get(0), profiles);
+            final Profile masterProfile = 
profileService.mergeProfiles(profiles.get(0), profiles);
 
             // Profile has changed
             if (!masterProfile.getItemId().equals(profileId)) {
                 HttpServletResponse httpServletResponse = 
(HttpServletResponse) event.getAttributes().get(Event.HTTP_RESPONSE_ATTRIBUTE);
-                sendProfileCookie(event.getSession().getProfile(), 
httpServletResponse);
+                sendProfileCookie(currentSession.getProfile(), 
httpServletResponse);
                 final String masterProfileId = masterProfile.getItemId();
 
                 // At the end of the merge, we must set the merged profile as 
profile event to process other Actions
                 event.setProfileId(masterProfileId);
                 event.setProfile(masterProfile);
 
-                event.getSession().setProfile(masterProfile);
+                currentSession.setProfile(masterProfile);
+                if (privacyService.isRequireAnonymousBrowsing(profileId)) {
+                    
privacyService.setRequireAnonymousBrowsing(masterProfileId, true);
+                }
+                final Boolean anonymousBrowsing = 
privacyService.isRequireAnonymousBrowsing(masterProfileId);
+                if (anonymousBrowsing) {
+                    
currentSession.setProfile(privacyService.getAnonymousProfile(masterProfile));
+                    event.setProfileId(null);
+                    persistenceService.save(event);
+                }
 
                 event.getActionPostExecutors().add(new ActionPostExecutor() {
                     @Override
@@ -197,16 +213,16 @@ public class MergeProfilesOnPropertyAction implements 
ActionExecutor {
                                 String profileId = profile.getItemId();
                                 if (!StringUtils.equals(profileId, 
masterProfileId)) {
                                     List<Session> sessions = 
persistenceService.query("profileId", profileId, null, Session.class);
-                                    if 
(currentSession.getProfileId().equals(profileId) && 
!sessions.contains(currentSession)) {
+                                    if (masterProfileId.equals(profileId) && 
!sessions.contains(currentSession)) {
                                         sessions.add(currentSession);
                                     }
                                     for (Session session : sessions) {
-                                        
persistenceService.update(session.getItemId(), session.getTimeStamp(), 
Session.class, "profileId", masterProfileId);
+                                        
persistenceService.update(session.getItemId(), session.getTimeStamp(), 
Session.class, "profileId", anonymousBrowsing ? null : masterProfileId);
                                     }
 
                                     List<Event> events = 
persistenceService.query("profileId", profileId, null, Event.class);
                                     for (Event event : events) {
-                                        
persistenceService.update(event.getItemId(), event.getTimeStamp(), Event.class, 
"profileId", masterProfileId);
+                                        
persistenceService.update(event.getItemId(), event.getTimeStamp(), Event.class, 
"profileId", anonymousBrowsing ? null : masterProfileId);
                                     }
                                     // we must mark all the profiles that we 
merged into the master as merged with the master, and they will
                                     // be deleted upon next load

http://git-wip-us.apache.org/repos/asf/incubator-unomi/blob/00761022/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/SendEventAction.java
----------------------------------------------------------------------
diff --git 
a/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/SendEventAction.java
 
b/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/SendEventAction.java
index f94851e..9f52246 100644
--- 
a/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/SendEventAction.java
+++ 
b/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/SendEventAction.java
@@ -45,6 +45,7 @@ public class SendEventAction implements ActionExecutor {
 //            BeanUtils.populate(targetItem, target);
 
         Event subEvent = new Event(eventType, event.getSession(), 
event.getProfile(), event.getScope(), event, target, event.getTimeStamp());
+        subEvent.setProfileId(event.getProfileId());
         subEvent.getAttributes().putAll(event.getAttributes());
         subEvent.getProperties().putAll(eventProperties);
 

http://git-wip-us.apache.org/repos/asf/incubator-unomi/blob/00761022/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/SetPropertyAction.java
----------------------------------------------------------------------
diff --git 
a/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/SetPropertyAction.java
 
b/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/SetPropertyAction.java
index e384960..a731468 100644
--- 
a/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/SetPropertyAction.java
+++ 
b/plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/SetPropertyAction.java
@@ -40,11 +40,6 @@ public class SetPropertyAction implements ActionExecutor {
 
         String propertyName = (String) 
action.getParameterValues().get("setPropertyName");
 
-        if (event.getProfile().isAnonymousProfile() && !storeInSession
-                && 
privacyService.getDeniedProperties(event.getProfileId()).contains(propertyName))
 {
-            return EventService.NO_CHANGE;
-        }
-
         Object propertyValue = 
action.getParameterValues().get("setPropertyValue");
         Object propertyValueInteger = 
action.getParameterValues().get("setPropertyValueInteger");
 

http://git-wip-us.apache.org/repos/asf/incubator-unomi/blob/00761022/plugins/baseplugin/src/main/resources/OSGI-INF/blueprint/blueprint.xml
----------------------------------------------------------------------
diff --git 
a/plugins/baseplugin/src/main/resources/OSGI-INF/blueprint/blueprint.xml 
b/plugins/baseplugin/src/main/resources/OSGI-INF/blueprint/blueprint.xml
index 73144ec..d6c1b10 100644
--- a/plugins/baseplugin/src/main/resources/OSGI-INF/blueprint/blueprint.xml
+++ b/plugins/baseplugin/src/main/resources/OSGI-INF/blueprint/blueprint.xml
@@ -216,6 +216,7 @@
             <property name="eventService" ref="eventService"/>
             <property name="persistenceService" ref="persistenceService"/>
             <property name="definitionsService" ref="definitionsService"/>
+            <property name="privacyService" ref="privacyService"/>
         </bean>
     </service>
 

http://git-wip-us.apache.org/repos/asf/incubator-unomi/blob/00761022/services/src/main/java/org/apache/unomi/services/services/EventServiceImpl.java
----------------------------------------------------------------------
diff --git 
a/services/src/main/java/org/apache/unomi/services/services/EventServiceImpl.java
 
b/services/src/main/java/org/apache/unomi/services/services/EventServiceImpl.java
index d6f0da4..70bd06d 100644
--- 
a/services/src/main/java/org/apache/unomi/services/services/EventServiceImpl.java
+++ 
b/services/src/main/java/org/apache/unomi/services/services/EventServiceImpl.java
@@ -153,7 +153,7 @@ public class EventServiceImpl implements EventService {
                 profileUpdated.setPersistent(false);
                 profileUpdated.getAttributes().putAll(event.getAttributes());
                 changes |= send(profileUpdated);
-                if (session != null) {
+                if (session != null && session.getProfileId() != null) {
                     changes |= SESSION_UPDATED;
                     session.setProfile(event.getProfile());
                 }

http://git-wip-us.apache.org/repos/asf/incubator-unomi/blob/00761022/services/src/main/java/org/apache/unomi/services/services/ProfileServiceImpl.java
----------------------------------------------------------------------
diff --git 
a/services/src/main/java/org/apache/unomi/services/services/ProfileServiceImpl.java
 
b/services/src/main/java/org/apache/unomi/services/services/ProfileServiceImpl.java
index bc716fb..22e6227 100644
--- 
a/services/src/main/java/org/apache/unomi/services/services/ProfileServiceImpl.java
+++ 
b/services/src/main/java/org/apache/unomi/services/services/ProfileServiceImpl.java
@@ -390,6 +390,9 @@ public class ProfileServiceImpl implements ProfileService, 
SynchronousBundleList
     }
 
     public Profile save(Profile profile) {
+        if (profile.getItemId() == null) {
+            return null;
+        }
         persistenceService.save(profile);
         return persistenceService.load(profile.getItemId(), Profile.class);
     }
@@ -527,6 +530,9 @@ public class ProfileServiceImpl implements ProfileService, 
SynchronousBundleList
     }
 
     public Session saveSession(Session session) {
+        if (session.getItemId() == null) {
+            return null;
+        }
         return persistenceService.save(session) ? session : null;
     }
 

http://git-wip-us.apache.org/repos/asf/incubator-unomi/blob/00761022/wab/src/main/java/org/apache/unomi/web/ContextServlet.java
----------------------------------------------------------------------
diff --git a/wab/src/main/java/org/apache/unomi/web/ContextServlet.java 
b/wab/src/main/java/org/apache/unomi/web/ContextServlet.java
index 5051780..7bedb67 100644
--- a/wab/src/main/java/org/apache/unomi/web/ContextServlet.java
+++ b/wab/src/main/java/org/apache/unomi/web/ContextServlet.java
@@ -66,13 +66,9 @@ public class ContextServlet extends HttpServlet {
         if (request.getParameter("timestamp") != null) {
             
timestamp.setTime(Long.parseLong(request.getParameter("timestamp")));
         }
-        // first we must retrieve the context for the current visitor, and 
build a Javascript object to attach to the
-        // script output.
-        String profileId;
 
         HttpServletRequest httpServletRequest = (HttpServletRequest) request;
         String httpMethod = httpServletRequest.getMethod();
-//        logger.debug(HttpUtils.dumpRequestInfo(httpServletRequest));
 
         // set up CORS headers as soon as possible so that errors are not 
misconstrued on the client for CORS errors
         HttpUtils.setupCORSHeaders(httpServletRequest, response);
@@ -84,6 +80,7 @@ public class ContextServlet extends HttpServlet {
         }
 
         Profile profile = null;
+        Profile sessionProfile = null;
 
         String cookieProfileId = null;
         Cookie[] cookies = httpServletRequest.getCookies();
@@ -118,8 +115,6 @@ public class ContextServlet extends HttpServlet {
             return;
         }
 
-        boolean profileCreated = false;
-
         ContextRequest contextRequest = null;
         String scope = null;
         String stringPayload = HttpUtils.getPayload(httpServletRequest);
@@ -138,78 +133,94 @@ public class ContextServlet extends HttpServlet {
         int changes = EventService.NO_CHANGE;
 
         if (profile == null) {
+            boolean profileCreated = false;
+
+            // Not a persona, resolve profile now
+            if (cookieProfileId == null) {
+                // no profileId cookie was found, we generate a new one and 
create the profile in the profile service
+                profile = createNewProfile(null, response, timestamp);
+                profileCreated = true;
+            } else {
+                profile = profileService.load(cookieProfileId);
+                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(null, response, timestamp);
+                    profileCreated = true;
+                } else {
+                    profile = checkMergedProfile(response, profile, session);
+                }
+            }
+
             if (sessionId != null) {
                 session = profileService.loadSession(sessionId, timestamp);
                 if (session != null) {
-                    profileId = session.getProfileId();
-                    profile = profileService.load(profileId);
-                    profile = checkMergedOrAnonymizedProfile(response, 
profile, session);
+                    sessionProfile = session.getProfile();
+
+                    if 
(privacyService.isRequireAnonymousBrowsing(profile.getItemId()) && 
sessionProfile.isAnonymousProfile()) {
+                        // User wants to browse anonymously, anonymous profile 
is already set.
+                    } else if 
(privacyService.isRequireAnonymousBrowsing(profile.getItemId()) && 
!sessionProfile.isAnonymousProfile()) {
+                        // User wants to browse anonymously, update the 
sessionProfile to anonymous profile
+                        sessionProfile = 
privacyService.getAnonymousProfile(profile);
+                        session.setProfile(sessionProfile);
+                        changes = EventService.SESSION_UPDATED;
+                    } else if 
(!privacyService.isRequireAnonymousBrowsing(profile.getItemId()) && 
sessionProfile.isAnonymousProfile()) {
+                        // 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 
(!privacyService.isRequireAnonymousBrowsing(profile.getItemId()) && 
!sessionProfile.isAnonymousProfile()) {
+                        // 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())) {
+                            session.setProfile(sessionProfile);
+                            changes = EventService.SESSION_UPDATED;
+                        }
+                    }
                 }
             }
-            if (profile == null) {
-                // profile not stored in session
-                if (cookieProfileId == null) {
-                    // no profileId cookie was found, we generate a new one 
and create the profile in the profile service
-                    profile = createNewProfile(null, response, timestamp);
-                    profileCreated = true;
-                } else {
-                    profile = profileService.load(cookieProfileId);
-                    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(null, response, timestamp);
-                        profileCreated = true;
-                        HttpUtils.sendProfileCookie(profile, response, 
profileIdCookieName, profileIdCookieDomain);
-                    } else {
-                        profile = checkMergedOrAnonymizedProfile(response, 
profile, session);
+
+            if (session == null) {
+                sessionProfile = 
privacyService.isRequireAnonymousBrowsing(profile.getItemId()) ? 
privacyService.getAnonymousProfile(profile) : profile;
+                session = new Session(sessionId, sessionProfile, timestamp, 
scope);
+
+                if (sessionId != null) {
+                    // Only save session and send event if a session id was 
provided, otherise keep transient session
+                    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);
+                    logger.debug("Received event " + event.getEventType() + " 
for profile=" + profile.getItemId() + " session=" + session.getItemId() + " 
target=" + event.getTarget() + " timestamp=" + timestamp);
+                    changes |= eventService.send(event);
                 }
-            } else if ((cookieProfileId == null || 
!cookieProfileId.equals(profile.getItemId())) && !profile.isAnonymousProfile()) 
{
-                // profile if stored in session but not in cookie
-                HttpUtils.sendProfileCookie(profile, response, 
profileIdCookieName, profileIdCookieDomain);
             }
-            // associate profile with session
-            if (sessionId != null && session == null) {
-                session = new Session(sessionId, profile, timestamp, scope);
-                changes |= EventService.SESSION_UPDATED;
-                Event event = new Event("sessionCreated", session, profile, 
scope, null, session, timestamp);
-
-                event.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, 
request);
-                event.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, 
response);
-                logger.debug("Received event " + event.getEventType() + " for 
profile=" + profile.getItemId() + " session=" + session.getItemId() + " 
target=" + event.getTarget() + " timestamp=" + timestamp);
-                changes |= eventService.send(event);
-            }
-        }
 
-        if (profileCreated) {
-            changes |= EventService.PROFILE_UPDATED;
+            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);
+                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);
 
-            logger.debug("Received event {} for profile={} {} target={} 
timestamp={}", profileUpdated.getEventType(), profile.getItemId(),
-                    session != null ? " session=" + session.getItemId() : "", 
profileUpdated.getTarget(), timestamp);
-            changes |= eventService.send(profileUpdated);
+                logger.debug("Received event {} for profile={} {} target={} 
timestamp={}", profileUpdated.getEventType(), profile.getItemId(),
+                        session != null ? " session=" + session.getItemId() : 
"", profileUpdated.getTarget(), timestamp);
+                changes |= eventService.send(profileUpdated);
+            }
         }
 
         ContextResponse data = new ContextResponse();
-        data.setProfileId(profile.isAnonymousProfile() ? cookieProfileId : 
profile.getItemId());
-
-        if (privacyService.isRequireAnonymousBrowsing(profile.getItemId())) {
-            if (!session.getProfile().isAnonymousProfile()) {
-                profile = privacyService.getAnonymousProfile(profile);
-                session.setProfile(profile);
-                changes = EventService.SESSION_UPDATED;
-            }
-        }
+        data.setProfileId(profile.getItemId());
 
-        if(contextRequest != null){
+        if (contextRequest != null){
             changes |= handleRequest(contextRequest, profile, session, data, 
request, response, timestamp);
         }
 
-        if ((changes & EventService.PROFILE_UPDATED) == 
EventService.PROFILE_UPDATED && profile != null) {
+        if ((changes & EventService.PROFILE_UPDATED) == 
EventService.PROFILE_UPDATED) {
             profileService.save(profile);
         }
         if ((changes & EventService.SESSION_UPDATED) == 
EventService.SESSION_UPDATED && session != null) {
@@ -241,8 +252,8 @@ public class ContextServlet extends HttpServlet {
         responseWriter.flush();
     }
 
-    private Profile checkMergedOrAnonymizedProfile(ServletResponse response, 
Profile profile, Session session) {
-        if (profile != null && profile.getMergedWith() != null && 
!profile.isAnonymousProfile()) {
+    private Profile checkMergedProfile(ServletResponse response, Profile 
profile, Session session) {
+        if (profile.getMergedWith() != null && 
!privacyService.isRequireAnonymousBrowsing(profile.getItemId()) && 
!profile.isAnonymousProfile()) {
             String profileId = profile.getMergedWith();
             Profile profileToDelete = profile;
             profile = profileService.load(profileId);
@@ -260,15 +271,6 @@ public class ContextServlet extends HttpServlet {
                 profileService.save(profile);
             }
         }
-        if (profile != null && !profile.isAnonymousProfile() && 
privacyService.isRequireAnonymousBrowsing(profile.getItemId())) {
-            if (session == null || !session.getProfile().isAnonymousProfile()) 
{
-                profile = privacyService.getAnonymousProfile(profile);
-                if (session != null) {
-                    session.setProfile(profile);
-                    profileService.saveSession(session);
-                }
-            }
-        }
 
         return profile;
     }
@@ -284,7 +286,7 @@ public class ContextServlet extends HttpServlet {
         if(contextRequest.getEvents() != null && !(profile instanceof 
Persona)) {
             for (Event event : contextRequest.getEvents()){
                 if(event.getEventType() != null) {
-                    Event eventToSend = new Event(event.getEventType(), 
session, profile, contextRequest.getSource().getScope(), event.getSource(), 
event.getTarget(), event.getProperties(), timestamp);
+                    Event eventToSend = new Event(event.getEventType(), 
session, session.getProfile(), contextRequest.getSource().getScope(), 
event.getSource(), event.getTarget(), event.getProperties(), timestamp);
                     if (!eventService.isEventAllowed(event, thirdPartyId)) {
                         logger.debug("Event is not allowed : {}", 
event.getEventType());
                         continue;
@@ -296,7 +298,7 @@ public class ContextServlet extends HttpServlet {
 
                     event.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, 
request);
                     event.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, 
response);
-                    logger.debug("Received event " + event.getEventType() + " 
for profile=" + profile.getItemId() + " session=" + session.getItemId() + " 
target=" + event.getTarget() + " timestamp=" + timestamp);
+                    logger.debug("Received event " + event.getEventType() + " 
for profile=" + session.getProfileId() + " session=" + session.getItemId() + " 
target=" + event.getTarget() + " timestamp=" + timestamp);
                     changes |= eventService.send(eventToSend);
                 }
             }

http://git-wip-us.apache.org/repos/asf/incubator-unomi/blob/00761022/wab/src/main/java/org/apache/unomi/web/EventsCollectorServlet.java
----------------------------------------------------------------------
diff --git a/wab/src/main/java/org/apache/unomi/web/EventsCollectorServlet.java 
b/wab/src/main/java/org/apache/unomi/web/EventsCollectorServlet.java
index 8d2cb3b..2b97f56 100644
--- a/wab/src/main/java/org/apache/unomi/web/EventsCollectorServlet.java
+++ b/wab/src/main/java/org/apache/unomi/web/EventsCollectorServlet.java
@@ -28,6 +28,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import javax.servlet.ServletException;
+import javax.servlet.http.Cookie;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
@@ -74,8 +75,6 @@ public class EventsCollectorServlet extends HttpServlet {
 
         HttpUtils.setupCORSHeaders(request, response);
 
-        Profile profile = null;
-
         String sessionId = request.getParameter("sessionId");
         if (sessionId == null) {
             logger.error("No sessionId found in incoming request, aborting 
processing. See debug level for more information");
@@ -91,21 +90,34 @@ public class EventsCollectorServlet extends HttpServlet {
             return;
         }
 
-        String profileId = session.getProfileId();
-        if (profileId == null) {
-            logger.error("No profileId found in session={}, aborting request 
!", session.getItemId());
-            return;
-        }
+        String profileIdCookieName = "context-profile-id";
 
-        profile = profileService.load(profileId);
-        if (profile == null || profile instanceof Persona) {
-            logger.error("No valid profile found or persona found for 
profileId={}, aborting request !", profileId);
-            return;
+        Profile sessionProfile = session.getProfile();
+        Profile profile = null;
+        if (sessionProfile.getItemId() != null) {
+            // Reload up-to-date profile
+            profile = profileService.load(sessionProfile.getItemId());
+            if (profile == null || profile instanceof Persona) {
+                logger.error("No valid profile found or persona found for 
profileId={}, aborting request !", session.getProfileId());
+                return;
+            }
+        } else {
+            // Session uses anonymous profile, try to find profile from cookie
+            Cookie[] cookies = request.getCookies();
+            for (Cookie cookie : cookies) {
+                if (profileIdCookieName.equals(cookie.getName())) {
+                    profile = profileService.load(cookie.getValue());
+                }
+            }
+            if (profile == null) {
+                logger.error("No valid profile found or persona found for 
profileId={}, aborting request !", session.getProfileId());
+                return;
+            }
         }
 
         String payload = HttpUtils.getPayload(request);
         if (payload == null){
-            logger.error("No event payload found for request, aborting !", 
profileId);
+            logger.error("No event payload found for request, aborting !");
             return;
         }
 
@@ -127,17 +139,16 @@ public class EventsCollectorServlet extends HttpServlet {
 
         int changes = 0;
 
-        if (privacyService.isRequireAnonymousBrowsing(profile.getItemId())) {
-            profile = privacyService.getAnonymousProfile(profile);
-            session.setProfile(profile);
-            changes = EventService.SESSION_UPDATED;
-        }
-
         List<String> filteredEventTypes = 
privacyService.getFilteredEventTypes(profile.getItemId());
 
         for (Event event : events.getEvents()){
             if(event.getEventType() != null){
                 Event eventToSend = new Event(event.getEventType(), session, 
profile, event.getScope(), event.getSource(), event.getTarget(), 
event.getProperties(), timestamp);
+                if (sessionProfile.isAnonymousProfile()) {
+                    // Do not keep track of profile in event
+                    eventToSend.setProfileId(null);
+                }
+
                 if (!eventService.isEventAllowed(event, thirdPartyId)) {
                     logger.debug("Event is not allowed : {}", 
event.getEventType());
                     continue;
@@ -149,12 +160,11 @@ public class EventsCollectorServlet extends HttpServlet {
 
                 eventToSend.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, 
request);
                 eventToSend.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, 
response);
-                logger.debug("Received event " + event.getEventType() + " for 
profile=" + profile.getItemId() + " session=" + session.getItemId() + " 
target=" + event.getTarget() + " timestamp=" + timestamp);
+                logger.debug("Received event " + event.getEventType() + " for 
profile=" + sessionProfile.getItemId() + " session=" + session.getItemId() + " 
target=" + event.getTarget() + " timestamp=" + timestamp);
                 int eventChanged = eventService.send(eventToSend);
                 //if the event execution changes the profile
                 if ((eventChanged & EventService.PROFILE_UPDATED) == 
EventService.PROFILE_UPDATED) {
                     profile = eventToSend.getProfile();
-                    session.setProfile(profile);
                 }
                 changes |= eventChanged;
             }


Reply via email to