summaryrefslogtreecommitdiffstats
path: root/server/src/com/vaadin/util/CurrentInstance.java
blob: a2cfd4fff7379fd84a3d9bcb3d3abc6b3e02468f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
/*
 * Copyright 2000-2013 Vaadin Ltd.
 * 
 * Licensed 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 com.vaadin.util;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.vaadin.server.VaadinPortlet;
import com.vaadin.server.VaadinPortletService;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinResponse;
import com.vaadin.server.VaadinService;
import com.vaadin.server.VaadinServlet;
import com.vaadin.server.VaadinServletService;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.UI;

/**
 * Keeps track of various thread local instances used by the framework.
 * <p>
 * Currently the framework uses the following instances:
 * </p>
 * <p>
 * Inheritable: {@link UI}, {@link VaadinPortlet}, {@link VaadinService},
 * {@link VaadinServlet}, {@link VaadinSession}.
 * </p>
 * <p>
 * Non-inheritable: {@link VaadinRequest}, {@link VaadinResponse}.
 * </p>
 * 
 * @author Vaadin Ltd
 * @version @VERSION@
 * @since 7.0.0
 */
public class CurrentInstance implements Serializable {
    private final Object instance;
    private final boolean inheritable;

    private static boolean portletAvailable = false;
    {
        try {
            /*
             * VaadinPortlet depends on portlet API which is available only if
             * running in a portal.
             */
            portletAvailable = (VaadinPortlet.class.getName() != null);
        } catch (Throwable t) {
        }
    }

    private static InheritableThreadLocal<Map<Class<?>, CurrentInstance>> instances = new InheritableThreadLocal<Map<Class<?>, CurrentInstance>>() {
        @Override
        protected Map<Class<?>, CurrentInstance> childValue(
                Map<Class<?>, CurrentInstance> parentValue) {
            Map<Class<?>, CurrentInstance> value = new HashMap<Class<?>, CurrentInstance>();

            // Copy all inheritable values to child map
            for (Entry<Class<?>, CurrentInstance> e : parentValue.entrySet()) {
                if (e.getValue().inheritable) {
                    value.put(e.getKey(), e.getValue());
                }
            }

            return value;
        }

        @Override
        protected Map<java.lang.Class<?>, CurrentInstance> initialValue() {
            return new HashMap<Class<?>, CurrentInstance>();
        }
    };

    private CurrentInstance(Object instance, boolean inheritable) {
        this.instance = instance;
        this.inheritable = inheritable;
    }

    /**
     * Gets the current instance of a specific type if available.
     * 
     * @param type
     *            the class to get an instance of
     * @return the current instance or the provided type, or <code>null</code>
     *         if there is no current instance.
     */
    public static <T> T get(Class<T> type) {
        CurrentInstance currentInstance = instances.get().get(type);
        if (currentInstance != null) {
            return type.cast(currentInstance.instance);
        } else {
            return null;
        }
    }

    /**
     * Sets the current instance of the given type.
     * 
     * @see #setInheritable(Class, Object)
     * @see ThreadLocal
     * 
     * @param type
     *            the class that should be used when getting the current
     *            instance back
     * @param instance
     *            the actual instance
     */
    public static <T> void set(Class<T> type, T instance) {
        set(type, instance, false);
    }

    /**
     * Sets the current inheritable instance of the given type. A current
     * instance that is inheritable will be available for child threads.
     * 
     * @see #set(Class, Object)
     * @see InheritableThreadLocal
     * 
     * @param type
     *            the class that should be used when getting the current
     *            instance back
     * @param instance
     *            the actual instance
     */
    public static <T> void setInheritable(Class<T> type, T instance) {
        set(type, instance, true);
    }

    private static <T> void set(Class<T> type, T instance, boolean inheritable) {
        if (instance == null) {
            instances.get().remove(type);
        } else {
            assert type.isInstance(instance) : "Invald instance type";
            CurrentInstance previousInstance = instances.get().put(type,
                    new CurrentInstance(instance, inheritable));
            if (previousInstance != null) {
                assert previousInstance.inheritable == inheritable : "Inheritable status mismatch for "
                        + type
                        + " (previous was "
                        + previousInstance.inheritable
                        + ", new is "
                        + inheritable + ")";
            }
        }
    }

    /**
     * Clears all current instances.
     */
    public static void clearAll() {
        instances.get().clear();
    }

    /**
     * Restores the given thread locals to the given values. Note that this
     * should only be used internally to restore Vaadin classes.
     * 
     * @param old
     *            A Class -> Object map to set as thread locals
     */
    public static void restoreThreadLocals(Map<Class<?>, CurrentInstance> old) {
        for (Class c : old.keySet()) {
            CurrentInstance ci = old.get(c);
            set(c, ci.instance, ci.inheritable);
        }
    }

    /**
     * Sets thread locals for the UI and all related classes
     * 
     * @param ui
     *            The UI
     * @return A map containing the old values of the thread locals this method
     *         updated.
     */
    public static Map<Class<?>, CurrentInstance> setThreadLocals(UI ui) {
        Map<Class<?>, CurrentInstance> old = new HashMap<Class<?>, CurrentInstance>();
        old.put(UI.class, new CurrentInstance(UI.getCurrent(), true));
        UI.setCurrent(ui);
        old.putAll(setThreadLocals(ui.getSession()));
        return old;
    }

    /**
     * Sets thread locals for the {@link VaadinSession} and all related classes
     * 
     * @param session
     *            The VaadinSession
     * @return A map containing the old values of the thread locals this method
     *         updated.
     */
    public static Map<Class<?>, CurrentInstance> setThreadLocals(
            VaadinSession session) {
        Map<Class<?>, CurrentInstance> old = new HashMap<Class<?>, CurrentInstance>();
        old.put(VaadinSession.class,
                new CurrentInstance(VaadinSession.getCurrent(), true));
        old.put(VaadinService.class,
                new CurrentInstance(VaadinService.getCurrent(), true));
        VaadinService service = null;
        if (session != null) {
            service = session.getService();
        }

        VaadinSession.setCurrent(session);
        VaadinService.setCurrent(service);

        if (service instanceof VaadinServletService) {
            old.put(VaadinServlet.class,
                    new CurrentInstance(VaadinServlet.getCurrent(), true));
            VaadinServlet.setCurrent(((VaadinServletService) service)
                    .getServlet());
        } else if (portletAvailable && service instanceof VaadinPortletService) {
            old.put(VaadinPortlet.class,
                    new CurrentInstance(VaadinPortlet.getCurrent(), true));
            VaadinPortlet.setCurrent(((VaadinPortletService) service)
                    .getPortlet());
        }

        return old;
    }
}