atom.ws.model.ContextService Maven / Gradle / Ivy
/*
* Copyright © 2015 Geeoz, and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Research Projects is dual-licensed under the GNU General Public
* License, version 2.0 (GPLv2) and the Geeoz Commercial License.
*
* Solely for non-commercial purposes. A purpose is non-commercial only if
* it is in no manner primarily intended for or directed toward commercial
* advantage or private monetary compensation.
*
* This Geeoz Software is supplied to you by Geeoz in consideration of your
* agreement to the following terms, and your use, installation, modification
* or redistribution of this Geeoz Software constitutes acceptance of these
* terms. If you do not agree with these terms, please do not use, install,
* modify or redistribute this Geeoz Software.
*
* Neither the name, trademarks, service marks or logos of Geeoz may be used
* to endorse or promote products derived from the Geeoz Software without
* specific prior written permission from Geeoz.
*
* The Geeoz Software is provided by Geeoz on an "AS IS" basis. GEEOZ MAKES NO
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE, REGARDING THE GEEOZ SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
* COMBINATION WITH YOUR PRODUCTS.
*
* IN NO EVENT SHALL GEEOZ BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION
* AND/OR DISTRIBUTION OF THE GEEOZ SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER
* THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR
* OTHERWISE, EVEN IF GEEOZ HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* A copy of the GNU General Public License is included in the distribution in
* the file LICENSE and at
*
* http://www.gnu.org/licenses/gpl-2.0.html
*
* If you are using the Research Projects for commercial purposes, we
* encourage you to visit
*
* http://products.geeoz.com/license
*
* for more details.
*
* This software or hardware and documentation may provide access to
* or information on content, products, and services from third parties.
* Geeoz and its affiliates are not responsible for and expressly disclaim
* all warranties of any kind with respect to third-party content, products,
* and services. Geeoz and its affiliates will not be responsible for any loss,
* costs, or damages incurred due to your access to or use of third-party
* content, products, or services. If a third-party content exists, the
* additional copyright notices and license terms applicable to portions of the
* software are set forth in the THIRD_PARTY_LICENSE_README file.
*
* Please contact Geeoz or visit www.geeoz.com if you need additional
* information or have any questions.
*/
package atom.ws.model;
import atom.app.ActivityList;
import atom.app.ActivityManager;
import atom.app.ActivityThread;
import atom.beans.AbstractPropertyChange;
import atom.beans.ChangeSet;
import atom.content.Context;
import atom.content.Intent;
import atom.metrics.MetricsUtils;
import com.codahale.metrics.Timer;
import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Default implementation of the web context service.
*
* @author Alex Voloshyn
* @author Serge Voloshyn
* @version 1.25 3/1/15
*/
public final class ContextService {
/**
* Prefix that will be used in
* {@link com.codahale.metrics.ScheduledReporter}.
*/
private static final String METRICS_PREFIX = "context-servlet-";
/**
* Metrics timer for {@link #handleEvent(String, java.util.List,
* String, int, atom.beans.ChangeSet,
* atom.ws.model.ClientRequestContext)} method.
*/
private static final Timer CALL_ON_CLICK_TIMER =
MetricsUtils.registerTimer(
ContextService.class, METRICS_PREFIX + "callOnClick");
/**
* Metrics timer for {@link ContextService#startActivity(String,
* java.util.List, atom.content.Intent,
* atom.ws.model.ClientRequestContext)} method.
*/
private static final Timer START_ACTIVITY_TIMER =
MetricsUtils.registerTimer(
ContextService.class, METRICS_PREFIX + "startActivity");
/**
* Current activity session attribute key.
*/
public static final String ACTIVITY_THREAD = "activityThread_";
/**
* Minutes in an hour.
*/
public static final int MINUTES_IN_HOUR = 60;
/**
* Service instance.
*/
private static final ContextService INSTANCE = new ContextService();
/**
* Default constructor.
*/
private ContextService() {
}
/**
* Get service instance.
*
* @return service instance
*/
public static ContextService getInstance() {
return INSTANCE;
}
/**
* Launch an activity for corresponding token.
*
* @param clientId client identifier
* @param layers existing client's layers
* @param intent to be processed
* @param client current client request context
* @return changes that should be applied to synchronize client and server
* state
*/
public List startActivity(final String clientId,
final List layers,
final Intent intent,
final ClientRequestContext client) {
final Timer.Context timer = START_ACTIVITY_TIMER.time();
try {
final ActivityThread thread
= getActivityThread(clientId, client);
final ActivityManager manager =
Context.getSystemService(ActivityManager.class);
manager.startActivity(thread, intent);
setCookies(thread, client);
return ChangeSetFactory.prepareChangeSet(layers, thread);
} finally {
timer.stop();
}
}
/**
* Propagate click event to server.
*
* @param clientId client identifier
* @param layers existing client's layers
* @param identity view identity that fire event
* @param eventType an event type
* @param changes changes that were made on client
* @param client current client request context
* @return list of changes
*/
public List handleEvent(final String clientId,
final List layers,
final String identity,
final int eventType,
final ChangeSet changes,
final ClientRequestContext client) {
final Timer.Context timer = CALL_ON_CLICK_TIMER.time();
try {
final ActivityThread thread
= getActivityThread(clientId, client);
final int eventLayer = changes.getLayer();
final ActivityManager manager =
Context.getSystemService(ActivityManager.class);
manager.handleEvent(thread, eventLayer, identity, eventType,
AbstractPropertyChange.asPropertyChangeEvents(
changes.getDisplayChanges()));
checkChangedActivities(thread);
setCookies(thread, client);
return ChangeSetFactory.prepareChangeSet(layers, thread);
} finally {
timer.stop();
}
}
/**
* Check changed activities and fill with current activities if empty.
*
* @param thread current activity thread
*/
public static void checkChangedActivities(final ActivityThread thread) {
final ActivityList changed = thread.getChangedActivities();
final ActivityList current = thread.getCurrentActivities();
if (changed.isEmpty()) {
for (int index = 0; index < current.length(); index++) {
changed.set(index, current.get(index));
}
}
}
/**
* Send timezone offset from client side.
*
* @param clientId client identifier
* @param minutes timezone offset minutes
* @param client current client request context
*/
public void sendTimezoneOffset(final String clientId, final int minutes,
final ClientRequestContext client) {
final String timeZone =
String.format("Etc/GMT%+d", -1 * (minutes / MINUTES_IN_HOUR));
final ActivityThread thread
= getActivityThread(clientId, client);
thread.putExtra("timezone", timeZone);
}
/**
* Update cookies from the updated ActivityThread.
*
* @param thread latest user's thread
* @param client current client request context
*/
private void setCookies(final ActivityThread thread,
final ClientRequestContext client) {
final Map attributesChanges
= thread.getClientAttributesChanges();
if (!attributesChanges.isEmpty()) {
final Cookie[] newCookies = new Cookie[attributesChanges.size()];
int index = 0;
for (final Map.Entry entry
: attributesChanges.entrySet()) {
final Cookie cookie = new Cookie(entry.getKey(),
entry.getValue());
final int maxAge;
if (entry.getValue() != null) {
maxAge = Integer.MAX_VALUE;
} else {
maxAge = 0;
}
cookie.setMaxAge(maxAge);
newCookies[index++] = cookie;
}
client.setResponseCookies(newCookies);
}
}
/**
* Retrieve corresponding activity thread for this user session.
*
* @param clientId client identifier
* @param context current client request context
* @return an activity thread to use
*/
public static ActivityThread getActivityThread(
final String clientId, final ClientRequestContext context) {
final HttpSession session = context.getSession();
ActivityThread thread =
(ActivityThread) session.getAttribute(
ACTIVITY_THREAD.concat(clientId));
final Map clientAttributes
= getClientAttributes(context);
if (thread == null) {
synchronized (session) {
thread = (ActivityThread) session.getAttribute(
ACTIVITY_THREAD.concat(clientId));
if (thread == null) {
final ActivityThread newThread = new ActivityThread();
session.setAttribute(
ACTIVITY_THREAD.concat(clientId), newThread);
final ActivityThread lastUsedThread =
(ActivityThread)
session.getAttribute(ACTIVITY_THREAD);
if (lastUsedThread == null) {
Locale locale = context.getLocale();
final String languageClientAttribute =
clientAttributes.get(
ActivityThread.
KnownClientAttributes.LANGUAGE);
if (languageClientAttribute != null) {
locale = Locale.forLanguageTag(
languageClientAttribute);
}
newThread.setLocale(locale);
} else {
newThread.setSubject(lastUsedThread.getSubject());
newThread.setLocale(lastUsedThread.getLocale());
newThread.setExtras(lastUsedThread.getExtras());
}
newThread.setClientAttributes(clientAttributes);
session.setAttribute(ACTIVITY_THREAD, newThread);
return newThread;
}
}
}
session.setAttribute(ACTIVITY_THREAD, thread);
thread.setClientAttributes(clientAttributes);
return thread;
}
/**
* Retrieve client attributes from request cookies.
*
* @param context current client request context
* @return map of cookies name/value
*/
public static Map getClientAttributes(
final ClientRequestContext context) {
final Cookie[] cookies = context.getRequestCookies();
if (cookies == null || cookies.length == 0) {
return Collections.emptyMap();
}
final HashMap result = new HashMap<>();
for (final Cookie cookie : cookies) {
result.put(cookie.getName(), cookie.getValue());
}
return result;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy