Repository: incubator-unomi
Updated Branches:
  refs/heads/master 877602f2b -> 63aa5a623


http://git-wip-us.apache.org/repos/asf/incubator-unomi/blob/dc1d1520/wab/src/main/java/org/apache/unomi/web/HttpUtils.java
----------------------------------------------------------------------
diff --git a/wab/src/main/java/org/apache/unomi/web/HttpUtils.java 
b/wab/src/main/java/org/apache/unomi/web/HttpUtils.java
new file mode 100644
index 0000000..8afb091
--- /dev/null
+++ b/wab/src/main/java/org/apache/unomi/web/HttpUtils.java
@@ -0,0 +1,159 @@
+/*
+ * 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.apache.unomi.api.Persona;
+import org.apache.unomi.api.Profile;
+
+import javax.servlet.ServletResponse;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.util.Enumeration;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public class HttpUtils {
+
+    private static final int MAX_COOKIE_AGE_IN_SECONDS = 60 * 60 * 24 * 365 * 
10; // 10-years
+
+    private static int cookieAgeInSeconds = MAX_COOKIE_AGE_IN_SECONDS;
+
+    public static void setupCORSHeaders(HttpServletRequest httpServletRequest, 
ServletResponse response) throws IOException {
+        if (response instanceof HttpServletResponse) {
+            HttpServletResponse httpServletResponse = (HttpServletResponse) 
response;
+            if (httpServletRequest != null && 
httpServletRequest.getHeader("Origin") != null) {
+                httpServletResponse.setHeader("Access-Control-Allow-Origin", 
httpServletRequest.getHeader("Origin"));
+            } else {
+                httpServletResponse.setHeader("Access-Control-Allow-Origin", 
"*");
+            }
+            httpServletResponse.setHeader("Access-Control-Allow-Headers", 
"Origin, X-Requested-With, Content-Type, Accept");
+            httpServletResponse.setHeader("Access-Control-Allow-Credentials", 
"true");
+            httpServletResponse.setHeader("Access-Control-Allow-Methods", 
"OPTIONS, POST, GET");
+            // httpServletResponse.setHeader("Access-Control-Max-Age", "600");
+            // 
httpServletResponse.setHeader("Access-Control-Expose-Headers","Access-Control-Allow-Origin");
+            // httpServletResponse.flushBuffer();
+        }
+    }
+
+    public static String dumpRequestInfo(HttpServletRequest 
httpServletRequest) {
+        StringBuilder stringBuilder = new StringBuilder();
+        stringBuilder.append("\n");
+        
stringBuilder.append("======================================================================================\n");
+        stringBuilder.append(dumpBasicRequestInfo(httpServletRequest));
+        stringBuilder.append(dumpRequestHeaders(httpServletRequest));
+        
stringBuilder.append(dumpRequestCookies(httpServletRequest.getCookies()));
+        
stringBuilder.append("======================================================================================\n");
+        return stringBuilder.toString();
+    }
+
+    public static String dumpBasicRequestInfo(HttpServletRequest 
httpServletRequest) {
+        StringBuilder stringBuilder = new StringBuilder();
+        stringBuilder.append(httpServletRequest.getMethod()).append(" 
").append(httpServletRequest.getRequestURI());
+        if (httpServletRequest.getQueryString() != null) {
+            
stringBuilder.append("?").append(httpServletRequest.getQueryString());
+        }
+        stringBuilder.append(" 
serverName=").append(httpServletRequest.getServerName()).append(" 
serverPort=").append(httpServletRequest.getServerPort()).append(" 
remoteAddr=").append(httpServletRequest.getRemoteAddr()).append(" 
remotePort=").append(httpServletRequest.getRemotePort()).append("\n");
+        return stringBuilder.toString();
+    }
+
+
+    public static String dumpRequestCookies(Cookie[] cookies) {
+        StringBuilder stringBuilder = new StringBuilder();
+        stringBuilder.append("Cookies:\n");
+        for (Cookie cookie : cookies) {
+            stringBuilder.append("  
").append(cookie.getName()).append("=").append(cookie.getValue()).append(" 
domain=").append(cookie.getDomain()).append(" 
path=").append(cookie.getPath()).append(" 
maxAge=").append(cookie.getMaxAge()).append(" 
httpOnly=").append(cookie.isHttpOnly()).append(" 
secure=").append(cookie.getSecure()).append(" 
version=").append(cookie.getVersion()).append(" 
comment=").append(cookie.getComment()).append("\n");
+        }
+        return stringBuilder.toString();
+    }
+
+    public static String dumpRequestHeaders(HttpServletRequest 
httpServletRequest) {
+        StringBuilder stringBuilder = new StringBuilder();
+        stringBuilder.append("Headers:\n");
+        Enumeration<String> headerNameEnum = 
httpServletRequest.getHeaderNames();
+        while (headerNameEnum.hasMoreElements()) {
+            String headerName = headerNameEnum.nextElement();
+            stringBuilder.append("  ").append(headerName).append(": 
").append(httpServletRequest.getHeader(headerName)).append("\n");
+        }
+        return stringBuilder.toString();
+    }
+
+    public static String getBaseRequestURL(HttpServletRequest 
httpServletRequest) {
+        String baseRequestURL;
+        baseRequestURL = httpServletRequest.getScheme() + "://" + 
httpServletRequest.getServerName();
+        if (("http".equals(httpServletRequest.getScheme()) && 
(httpServletRequest.getServerPort() == 80)) ||
+                ("https".equals(httpServletRequest.getScheme()) && 
(httpServletRequest.getServerPort() == 443))) {
+            // normal case, don't add the port
+        } else {
+            baseRequestURL += ":" + httpServletRequest.getServerPort();
+        }
+        return baseRequestURL;
+    }
+
+    public static void sendProfileCookie(Profile profile, ServletResponse 
response, String profileIdCookieName, String profileIdCookieDomain) {
+        if (response instanceof HttpServletResponse) {
+            HttpServletResponse httpServletResponse = (HttpServletResponse) 
response;
+            if (!(profile instanceof Persona)) {
+                Cookie profileIdCookie = new Cookie(profileIdCookieName, 
profile.getItemId());
+                profileIdCookie.setPath("/");
+                if (profileIdCookieDomain != null && 
!profileIdCookieDomain.equals("")) {
+                    profileIdCookie.setDomain(profileIdCookieDomain);
+                }
+                profileIdCookie.setMaxAge(cookieAgeInSeconds);
+                httpServletResponse.addCookie(profileIdCookie);
+            }
+        }
+    }
+
+    public static void clearCookie(ServletResponse response, String 
cookieName) {
+        if (response instanceof HttpServletResponse) {
+            HttpServletResponse httpServletResponse = (HttpServletResponse) 
response;
+            Cookie cookie = new Cookie(cookieName, "");
+            cookie.setPath("/");
+            cookie.setMaxAge(0);
+            httpServletResponse.addCookie(cookie);
+        }
+    }
+
+    public static Map<String, Cookie> getCookieMap(Cookie[] cookieArray) {
+        Map<String, Cookie> cookieMap = new LinkedHashMap<String, Cookie>();
+        for (Cookie cookie : cookieArray) {
+            cookieMap.put(cookie.getName(), cookie);
+        }
+        return cookieMap;
+    }
+
+    public static String getPayload(HttpServletRequest request) throws 
IOException {
+        if ("post".equals(request.getMethod().toLowerCase())) {
+            StringBuilder buffer = new StringBuilder();
+            String line;
+            BufferedReader reader = request.getReader();
+            while ((line = reader.readLine()) != null) {
+                buffer.append(line);
+            }
+            if (buffer.length() > 0) {
+                return buffer.toString();
+            }
+        } else if ("get".equals(request.getMethod().toLowerCase()) && 
request.getParameter("payload") != null) {
+            return request.getParameter("payload");
+        }
+        return null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-unomi/blob/dc1d1520/wab/src/main/java/org/oasis_open/contextserver/web/ContextServlet.java
----------------------------------------------------------------------
diff --git 
a/wab/src/main/java/org/oasis_open/contextserver/web/ContextServlet.java 
b/wab/src/main/java/org/oasis_open/contextserver/web/ContextServlet.java
deleted file mode 100644
index 371d240..0000000
--- a/wab/src/main/java/org/oasis_open/contextserver/web/ContextServlet.java
+++ /dev/null
@@ -1,371 +0,0 @@
-/*
- * 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.oasis_open.contextserver.web;
-
-import com.fasterxml.jackson.core.JsonFactory;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import org.apache.commons.io.IOUtils;
-import org.oasis_open.contextserver.api.*;
-import org.oasis_open.contextserver.api.conditions.Condition;
-import org.oasis_open.contextserver.api.services.EventService;
-import org.oasis_open.contextserver.api.services.ProfileService;
-import org.oasis_open.contextserver.api.services.RulesService;
-import org.oasis_open.contextserver.persistence.spi.CustomObjectMapper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Writer;
-import java.util.*;
-
-/**
- * A servlet filter to serve a context-specific Javascript containing the 
current request context object.
- */
-public class ContextServlet extends HttpServlet {
-    private static final Logger logger = 
LoggerFactory.getLogger(ContextServlet.class.getName());
-
-    private static final long serialVersionUID = 2928875830103325238L;
-    public static final String BASE_SCRIPT_LOCATION = "/javascript/base.js";
-    public static final String IMPERSONATE_BASE_SCRIPT_LOCATION = 
"/javascript/impersonateBase.js";
-    public static final String PROFILE_OVERRIDE_MARKER = "---IGNORE---";
-
-
-    private ProfileService profileService;
-    private EventService eventService;
-    private RulesService rulesService;
-
-    private String profileIdCookieName = "context-profile-id";
-    private String profileIdCookieDomain;
-//    private String personaIdCookieName = "context-persona-id";
-
-
-    @Override
-    public void service(ServletRequest request, ServletResponse response) 
throws ServletException, IOException {
-        final Date timestamp = new Date();
-        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);
-
-        if ("options".equals(httpMethod.toLowerCase())) {
-            response.flushBuffer();
-            return;
-        }
-
-        Profile profile = null;
-
-        String cookieProfileId = null;
-        String cookiePersonaId = null;
-        Cookie[] cookies = httpServletRequest.getCookies();
-        for (Cookie cookie : cookies) {
-            if (profileIdCookieName.equals(cookie.getName())) {
-                cookieProfileId = cookie.getValue();
-            }
-        }
-
-        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 with id=" + personaId);
-                profile = null;
-            } else {
-                profile = personaWithSessions.getPersona();
-                session = personaWithSessions.getLastSession();
-            }
-        }
-
-        String sessionId = request.getParameter("sessionId");
-
-        if (cookieProfileId == null && sessionId == null && personaId == null) 
{
-            
((HttpServletResponse)response).sendError(HttpServletResponse.SC_BAD_REQUEST);
-            return;
-        }
-
-        boolean profileCreated = false;
-
-        ContextRequest contextRequest = null;
-        String scope = null;
-        String stringPayload = HttpUtils.getPayload(httpServletRequest);
-        if (stringPayload != null) {
-            ObjectMapper mapper = CustomObjectMapper.getObjectMapper();
-            JsonFactory factory = mapper.getFactory();
-            try {
-                contextRequest = 
mapper.readValue(factory.createParser(stringPayload), ContextRequest.class);
-            } catch (Exception e) {
-                logger.error("Cannot read payload " + stringPayload, e);
-                return;
-            }
-            scope = contextRequest.getSource().getScope();
-        }
-
-        int changes = EventService.NO_CHANGE;
-
-        if (profile == null) {
-            if (sessionId != null) {
-                session = profileService.loadSession(sessionId, timestamp);
-                if (session != null) {
-                    profileId = session.getProfileId();
-                    profile = profileService.load(profileId);
-                    profile = checkMergedProfile(response, profile, session);
-                }
-            }
-            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 = checkMergedProfile(response, profile, 
session);
-                    }
-                }
-
-            } else if (cookieProfileId == null || 
!cookieProfileId.equals(profile.getItemId())) {
-                // 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;
-
-            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);
-        }
-
-        ContextResponse data = new ContextResponse();
-
-        if(contextRequest != null){
-            changes |= handleRequest(contextRequest, profile, session, data, 
request, response, timestamp);
-        }
-
-        if ((changes & EventService.PROFILE_UPDATED) == 
EventService.PROFILE_UPDATED && profile != null) {
-            profileService.save(profile);
-        }
-        if ((changes & EventService.SESSION_UPDATED) == 
EventService.SESSION_UPDATED && session != null) {
-            profileService.saveSession(session);
-        }
-
-
-        String extension = 
httpServletRequest.getRequestURI().substring(httpServletRequest.getRequestURI().lastIndexOf(".")
 + 1);
-        boolean noScript = "json".equals(extension);
-        String contextAsJSONString = 
CustomObjectMapper.getObjectMapper().writeValueAsString(data);
-        Writer responseWriter;
-        if(noScript){
-            response.setCharacterEncoding("UTF-8");
-            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");
-
-            // now we copy the base script source code
-            InputStream baseScriptStream = 
getServletContext().getResourceAsStream(profile instanceof Persona ? 
IMPERSONATE_BASE_SCRIPT_LOCATION : BASE_SCRIPT_LOCATION);
-            IOUtils.copy(baseScriptStream, responseWriter);
-        }
-
-        responseWriter.flush();
-    }
-
-    private Profile checkMergedProfile(ServletResponse response, Profile 
profile, Session session) {
-        String profileId;
-        if (profile != null && profile.getMergedWith() != null) {
-            profileId = profile.getMergedWith();
-            Profile profileToDelete = profile;
-            profile = profileService.load(profileId);
-            if (profile != null) {
-                logger.debug("Session profile was merged with profile " + 
profileId + ", replacing profile in session");
-                if (session != null) {
-                    session.setProfile(profile);
-                    profileService.saveSession(session);
-                }
-                HttpUtils.sendProfileCookie(profile, response, 
profileIdCookieName, profileIdCookieDomain);
-            } else {
-                logger.warn("Couldn't find merged profile" + profileId + ", 
falling back to profile " + profileToDelete.getItemId());
-                profile = profileToDelete;
-                profile.setMergedWith(null);
-                profileService.save(profile);
-            }
-        }
-        return profile;
-    }
-
-    private int handleRequest(ContextRequest contextRequest, Profile profile, 
Session session, ContextResponse data, ServletRequest request, ServletResponse 
response, Date timestamp)
-            throws IOException {
-        int changes = EventService.NO_CHANGE;
-        // execute provided events if any
-        if(contextRequest.getEvents() != null && !(profile instanceof 
Persona)) {
-            for (Event event : contextRequest.getEvents()){
-                if(event.getEventType() != null) {
-                    Event eventToSend;
-                    if(event.getProperties() != null){
-                        eventToSend = new Event(event.getEventType(), session, 
profile, contextRequest.getSource().getScope(), event.getSource(), 
event.getTarget(), event.getProperties(), timestamp);
-                    } else {
-                        eventToSend = new Event(event.getEventType(), session, 
profile, contextRequest.getSource().getScope(), event.getSource(), 
event.getTarget(), 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(eventToSend);
-                }
-            }
-        }
-
-        data.setProfileId(profile.getItemId());
-
-        if (contextRequest.isRequireSegments()) {
-            data.setProfileSegments(profile.getSegments());
-        }
-
-        if (contextRequest.getRequiredProfileProperties() != null) {
-            Map<String, Object> profileProperties = new HashMap<String, 
Object>(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<String, 
Object>(session.getProperties());
-                if 
(!contextRequest.getRequiredSessionProperties().contains("*")) {
-                    
sessionProperties.keySet().retainAll(contextRequest.getRequiredSessionProperties());
-                }
-                data.setSessionProperties(sessionProperties);
-            }
-        }
-
-        processOverrides(contextRequest, profile, session);
-
-        List<ContextRequest.FilteredContent> filterNodes = 
contextRequest.getFilters();
-        if (filterNodes != null) {
-            data.setFilteringResults(new HashMap<String, Boolean>());
-            for (ContextRequest.FilteredContent filteredContent : filterNodes) 
{
-                boolean result = true;
-                for (ContextRequest.Filter filter : 
filteredContent.getFilters()) {
-                    Condition condition = filter.getCondition();
-                    result &= profileService.matchCondition(condition, 
profile, session);
-                }
-                data.getFilteringResults().put(filteredContent.getFilterid(), 
result);
-            }
-        }
-
-        if(!(profile instanceof Persona)) {
-            
data.setTrackedConditions(rulesService.getTrackedConditions(contextRequest.getSource()));
-        } else {
-            data.setTrackedConditions(Collections.<Condition>emptySet());
-        }
-
-        return changes;
-    }
-
-    private void processOverrides(ContextRequest contextRequest, Profile 
profile, Session session) {
-        if (contextRequest.getSegmentOverrides() != null) {
-            profile.setSegments(contextRequest.getSegmentOverrides());
-        }
-
-        if (contextRequest.getProfilePropertiesOverrides() != null) {
-            
profile.setProperties(contextRequest.getProfilePropertiesOverrides());
-        }
-
-        if (contextRequest.getSessionPropertiesOverrides() != null) {
-            
session.setProperties(contextRequest.getSessionPropertiesOverrides()); // we do 
this just in case a cache is behind this
-        }
-    }
-
-    private Profile createNewProfile(String existingProfileId, ServletResponse 
response, Date timestamp) {
-        Profile profile;
-        String profileId = existingProfileId;
-        if (profileId == null) {
-            profileId = UUID.randomUUID().toString();
-        }
-        profile = new Profile(profileId);
-        profile.setProperty("firstVisit", timestamp);
-        HttpUtils.sendProfileCookie(profile, response, profileIdCookieName, 
profileIdCookieDomain);
-        return profile;
-    }
-
-
-    public void destroy() {
-    }
-
-    public void setProfileService(ProfileService profileService) {
-        this.profileService = profileService;
-    }
-
-    public void setEventService(EventService eventService) {
-        this.eventService = eventService;
-    }
-
-    public void setRulesService(RulesService rulesService) {
-        this.rulesService = rulesService;
-    }
-
-    public void setProfileIdCookieDomain(String profileIdCookieDomain) {
-        this.profileIdCookieDomain = profileIdCookieDomain;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-unomi/blob/dc1d1520/wab/src/main/java/org/oasis_open/contextserver/web/EventsCollectorServlet.java
----------------------------------------------------------------------
diff --git 
a/wab/src/main/java/org/oasis_open/contextserver/web/EventsCollectorServlet.java
 
b/wab/src/main/java/org/oasis_open/contextserver/web/EventsCollectorServlet.java
deleted file mode 100644
index 50963a3..0000000
--- 
a/wab/src/main/java/org/oasis_open/contextserver/web/EventsCollectorServlet.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * 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.oasis_open.contextserver.web;
-
-import com.fasterxml.jackson.core.JsonFactory;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import org.oasis_open.contextserver.api.*;
-import org.oasis_open.contextserver.api.services.EventService;
-import org.oasis_open.contextserver.api.services.PrivacyService;
-import org.oasis_open.contextserver.api.services.ProfileService;
-import org.oasis_open.contextserver.persistence.spi.CustomObjectMapper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.Date;
-import java.util.List;
-
-public class EventsCollectorServlet extends HttpServlet {
-    private static final Logger logger = 
LoggerFactory.getLogger(EventsCollectorServlet.class.getName());
-
-    private static final long serialVersionUID = 2008054804885122957L;
-
-    private EventService eventService;
-    private ProfileService profileService;
-    private PrivacyService privacyService;
-
-    @Override
-    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {
-
-        doEvent(req, resp);
-    }
-
-    @Override
-    protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {
-
-        doEvent(req, resp);
-    }
-
-    @Override
-    protected void doOptions(HttpServletRequest request, HttpServletResponse 
response) throws ServletException, IOException {
-//        logger.debug(HttpUtils.dumpRequestInfo(request));
-        HttpUtils.setupCORSHeaders(request, response);
-        response.flushBuffer();
-    }
-
-    private void doEvent(HttpServletRequest request, HttpServletResponse 
response) throws IOException {
-        Date timestamp = new Date();
-        if (request.getParameter("timestamp") != null) {
-            
timestamp.setTime(Long.parseLong(request.getParameter("timestamp")));
-        }
-
-//        logger.debug(HttpUtils.dumpRequestInfo(request));
-
-        HttpUtils.setupCORSHeaders(request, response);
-
-        Profile profile = null;
-
-        String sessionId = request.getParameter("sessionId");
-        if (sessionId == null) {
-            return;
-        }
-
-        Session session = profileService.loadSession(sessionId, timestamp);
-        if (session == null) {
-            return;
-        }
-
-        String profileId = session.getProfileId();
-        if (profileId == null) {
-            return;
-        }
-
-        profile = profileService.load(profileId);
-        if (profile == null || profile instanceof Persona) {
-            return;
-        }
-
-        String payload = HttpUtils.getPayload(request);
-        if(payload == null){
-            return;
-        }
-
-        Profile realProfile = profile;
-        Boolean profileIsAnonymous = 
privacyService.isAnonymous(profile.getItemId());
-        if (profileIsAnonymous != null && profileIsAnonymous.booleanValue()) {
-            // we are surfing anonymously, we must use the global anonymous 
profile if it exists, or create it if
-            // it doesn't.
-            Profile anonymousProfile = 
profileService.load(PrivacyService.GLOBAL_ANONYMOUS_PROFILE_ID);
-            if (anonymousProfile == null) {
-                anonymousProfile = new 
Profile(PrivacyService.GLOBAL_ANONYMOUS_PROFILE_ID);
-                profileService.save(profile);
-            }
-            realProfile = profile;
-            profile = anonymousProfile;
-        }
-
-        List<String> filteredEventTypes = 
privacyService.getFilteredEventTypes(profile.getItemId());
-
-        ObjectMapper mapper = CustomObjectMapper.getObjectMapper();
-        JsonFactory factory = mapper.getFactory();
-        EventsCollectorRequest events = null;
-        try {
-            events = mapper.readValue(factory.createParser(payload), 
EventsCollectorRequest.class);
-        } catch (Exception e) {
-            logger.error("Cannot read payload " + payload,e);
-            return;
-        }
-        if (events == null || events.getEvents() == null) {
-            return;
-        }
-
-        int changes = 0;
-        for (Event event : events.getEvents()){
-            if(event.getEventType() != null){
-                Event eventToSend;
-                if(event.getProperties() != null){
-                    eventToSend = new Event(event.getEventType(), session, 
profile, event.getScope(), event.getSource(), event.getTarget(), 
event.getProperties(), timestamp);
-                } else {
-                    eventToSend = new Event(event.getEventType(), session, 
profile, event.getScope(), event.getSource(), event.getTarget(), timestamp);
-                }
-
-                if (filteredEventTypes != null && 
filteredEventTypes.contains(event.getEventType())) {
-                    logger.debug("Profile is filtering event type {}", 
event.getEventType());
-                    continue;
-                }
-
-                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);
-                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;
-            }
-        }
-
-        if ((changes & EventService.PROFILE_UPDATED) == 
EventService.PROFILE_UPDATED) {
-            profileService.save(profile);
-        }
-        if ((changes & EventService.SESSION_UPDATED) == 
EventService.SESSION_UPDATED) {
-            profileService.saveSession(session);
-        }
-
-
-        PrintWriter responseWriter = response.getWriter();
-        responseWriter.append("{\"updated\":" + changes + "}");
-        responseWriter.flush();
-    }
-
-    public void setEventService(EventService eventService) {
-        this.eventService = eventService;
-    }
-
-    public void setProfileService(ProfileService profileService) {
-        this.profileService = profileService;
-    }
-
-    public void setPrivacyService(PrivacyService privacyService) {
-        this.privacyService = privacyService;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-unomi/blob/dc1d1520/wab/src/main/java/org/oasis_open/contextserver/web/HttpUtils.java
----------------------------------------------------------------------
diff --git a/wab/src/main/java/org/oasis_open/contextserver/web/HttpUtils.java 
b/wab/src/main/java/org/oasis_open/contextserver/web/HttpUtils.java
deleted file mode 100644
index ea85284..0000000
--- a/wab/src/main/java/org/oasis_open/contextserver/web/HttpUtils.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * 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.oasis_open.contextserver.web;
-
-import org.oasis_open.contextserver.api.Persona;
-import org.oasis_open.contextserver.api.Profile;
-
-import javax.servlet.ServletResponse;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.util.Enumeration;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-public class HttpUtils {
-
-    private static final int MAX_COOKIE_AGE_IN_SECONDS = 60 * 60 * 24 * 365 * 
10; // 10-years
-
-    private static int cookieAgeInSeconds = MAX_COOKIE_AGE_IN_SECONDS;
-
-    public static void setupCORSHeaders(HttpServletRequest httpServletRequest, 
ServletResponse response) throws IOException {
-        if (response instanceof HttpServletResponse) {
-            HttpServletResponse httpServletResponse = (HttpServletResponse) 
response;
-            if (httpServletRequest != null && 
httpServletRequest.getHeader("Origin") != null) {
-                httpServletResponse.setHeader("Access-Control-Allow-Origin", 
httpServletRequest.getHeader("Origin"));
-            } else {
-                httpServletResponse.setHeader("Access-Control-Allow-Origin", 
"*");
-            }
-            httpServletResponse.setHeader("Access-Control-Allow-Headers", 
"Origin, X-Requested-With, Content-Type, Accept");
-            httpServletResponse.setHeader("Access-Control-Allow-Credentials", 
"true");
-            httpServletResponse.setHeader("Access-Control-Allow-Methods", 
"OPTIONS, POST, GET");
-            // httpServletResponse.setHeader("Access-Control-Max-Age", "600");
-            // 
httpServletResponse.setHeader("Access-Control-Expose-Headers","Access-Control-Allow-Origin");
-            // httpServletResponse.flushBuffer();
-        }
-    }
-
-    public static String dumpRequestInfo(HttpServletRequest 
httpServletRequest) {
-        StringBuilder stringBuilder = new StringBuilder();
-        stringBuilder.append("\n");
-        
stringBuilder.append("======================================================================================\n");
-        stringBuilder.append(dumpBasicRequestInfo(httpServletRequest));
-        stringBuilder.append(dumpRequestHeaders(httpServletRequest));
-        
stringBuilder.append(dumpRequestCookies(httpServletRequest.getCookies()));
-        
stringBuilder.append("======================================================================================\n");
-        return stringBuilder.toString();
-    }
-
-    public static String dumpBasicRequestInfo(HttpServletRequest 
httpServletRequest) {
-        StringBuilder stringBuilder = new StringBuilder();
-        stringBuilder.append(httpServletRequest.getMethod()).append(" 
").append(httpServletRequest.getRequestURI());
-        if (httpServletRequest.getQueryString() != null) {
-            
stringBuilder.append("?").append(httpServletRequest.getQueryString());
-        }
-        stringBuilder.append(" 
serverName=").append(httpServletRequest.getServerName()).append(" 
serverPort=").append(httpServletRequest.getServerPort()).append(" 
remoteAddr=").append(httpServletRequest.getRemoteAddr()).append(" 
remotePort=").append(httpServletRequest.getRemotePort()).append("\n");
-        return stringBuilder.toString();
-    }
-
-
-    public static String dumpRequestCookies(Cookie[] cookies) {
-        StringBuilder stringBuilder = new StringBuilder();
-        stringBuilder.append("Cookies:\n");
-        for (Cookie cookie : cookies) {
-            stringBuilder.append("  
").append(cookie.getName()).append("=").append(cookie.getValue()).append(" 
domain=").append(cookie.getDomain()).append(" 
path=").append(cookie.getPath()).append(" 
maxAge=").append(cookie.getMaxAge()).append(" 
httpOnly=").append(cookie.isHttpOnly()).append(" 
secure=").append(cookie.getSecure()).append(" 
version=").append(cookie.getVersion()).append(" 
comment=").append(cookie.getComment()).append("\n");
-        }
-        return stringBuilder.toString();
-    }
-
-    public static String dumpRequestHeaders(HttpServletRequest 
httpServletRequest) {
-        StringBuilder stringBuilder = new StringBuilder();
-        stringBuilder.append("Headers:\n");
-        Enumeration<String> headerNameEnum = 
httpServletRequest.getHeaderNames();
-        while (headerNameEnum.hasMoreElements()) {
-            String headerName = headerNameEnum.nextElement();
-            stringBuilder.append("  ").append(headerName).append(": 
").append(httpServletRequest.getHeader(headerName)).append("\n");
-        }
-        return stringBuilder.toString();
-    }
-
-    public static String getBaseRequestURL(HttpServletRequest 
httpServletRequest) {
-        String baseRequestURL;
-        baseRequestURL = httpServletRequest.getScheme() + "://" + 
httpServletRequest.getServerName();
-        if (("http".equals(httpServletRequest.getScheme()) && 
(httpServletRequest.getServerPort() == 80)) ||
-                ("https".equals(httpServletRequest.getScheme()) && 
(httpServletRequest.getServerPort() == 443))) {
-            // normal case, don't add the port
-        } else {
-            baseRequestURL += ":" + httpServletRequest.getServerPort();
-        }
-        return baseRequestURL;
-    }
-
-    public static void sendProfileCookie(Profile profile, ServletResponse 
response, String profileIdCookieName, String profileIdCookieDomain) {
-        if (response instanceof HttpServletResponse) {
-            HttpServletResponse httpServletResponse = (HttpServletResponse) 
response;
-            if (!(profile instanceof Persona)) {
-                Cookie profileIdCookie = new Cookie(profileIdCookieName, 
profile.getItemId());
-                profileIdCookie.setPath("/");
-                if (profileIdCookieDomain != null && 
!profileIdCookieDomain.equals("")) {
-                    profileIdCookie.setDomain(profileIdCookieDomain);
-                }
-                profileIdCookie.setMaxAge(cookieAgeInSeconds);
-                httpServletResponse.addCookie(profileIdCookie);
-            }
-        }
-    }
-
-    public static void clearCookie(ServletResponse response, String 
cookieName) {
-        if (response instanceof HttpServletResponse) {
-            HttpServletResponse httpServletResponse = (HttpServletResponse) 
response;
-            Cookie cookie = new Cookie(cookieName, "");
-            cookie.setPath("/");
-            cookie.setMaxAge(0);
-            httpServletResponse.addCookie(cookie);
-        }
-    }
-
-    public static Map<String, Cookie> getCookieMap(Cookie[] cookieArray) {
-        Map<String, Cookie> cookieMap = new LinkedHashMap<String, Cookie>();
-        for (Cookie cookie : cookieArray) {
-            cookieMap.put(cookie.getName(), cookie);
-        }
-        return cookieMap;
-    }
-
-    public static String getPayload(HttpServletRequest request) throws 
IOException {
-        if ("post".equals(request.getMethod().toLowerCase())) {
-            StringBuilder buffer = new StringBuilder();
-            String line;
-            BufferedReader reader = request.getReader();
-            while ((line = reader.readLine()) != null) {
-                buffer.append(line);
-            }
-            if (buffer.length() > 0) {
-                return buffer.toString();
-            }
-        } else if ("get".equals(request.getMethod().toLowerCase()) && 
request.getParameter("payload") != null) {
-            return request.getParameter("payload");
-        }
-        return null;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-unomi/blob/dc1d1520/wab/src/main/resources/OSGI-INF/blueprint/blueprint.xml
----------------------------------------------------------------------
diff --git a/wab/src/main/resources/OSGI-INF/blueprint/blueprint.xml 
b/wab/src/main/resources/OSGI-INF/blueprint/blueprint.xml
index 2de07b8..eab2e9a 100644
--- a/wab/src/main/resources/OSGI-INF/blueprint/blueprint.xml
+++ b/wab/src/main/resources/OSGI-INF/blueprint/blueprint.xml
@@ -16,15 +16,16 @@
   ~ limitations under the License.
   -->
 
-<blueprint xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"; 
xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0";
+<blueprint xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
            
xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0";
+           xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0";
            xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 
http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
            http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0 
http://aries.apache.org/schemas/blueprint-cm/blueprint-cm-1.1.0.xsd";>
 
-    <reference id="profileService" 
interface="org.oasis_open.contextserver.api.services.ProfileService"/>
-    <reference id="eventService" 
interface="org.oasis_open.contextserver.api.services.EventService"/>
-    <reference id="rulesService" 
interface="org.oasis_open.contextserver.api.services.RulesService"/>
-    <reference id="privacyService" 
interface="org.oasis_open.contextserver.api.services.PrivacyService"/>
+    <reference id="profileService" 
interface="org.apache.unomi.api.services.ProfileService"/>
+    <reference id="eventService" 
interface="org.apache.unomi.api.services.EventService"/>
+    <reference id="rulesService" 
interface="org.apache.unomi.api.services.RulesService"/>
+    <reference id="privacyService" 
interface="org.apache.unomi.api.services.PrivacyService"/>
 
     <cm:property-placeholder persistent-id="org.apache.unomi.web"
                              update-strategy="reload" 
placeholder-prefix="${web.">
@@ -33,7 +34,7 @@
         </cm:default-properties>
     </cm:property-placeholder>
 
-    <bean id="contextServlet" 
class="org.oasis_open.contextserver.web.ContextServlet">
+    <bean id="contextServlet" class="org.apache.unomi.web.ContextServlet">
         <property name="profileService" ref="profileService"/>
         <property name="eventService" ref="eventService"/>
         <property name="rulesService" ref="rulesService"/>
@@ -51,7 +52,7 @@
         </service-properties>
     </service>
 
-    <bean id="eventsCollectorServlet" 
class="org.oasis_open.contextserver.web.EventsCollectorServlet">
+    <bean id="eventsCollectorServlet" 
class="org.apache.unomi.web.EventsCollectorServlet">
         <property name="profileService" ref="profileService"/>
         <property name="eventService" ref="eventService"/>
         <property name="privacyService" ref="privacyService" />


Reply via email to