summaryrefslogtreecommitdiffstats
path: root/sca-java-1.x/tags/1.6.1-TUSCANY-3909/core/src/main/java/org/apache/tuscany/sca/core/conversation/ConversationManagerImpl.java
blob: 3bea79b076fa31c48eb99705067066d810fd7eac (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
/*
 * 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.tuscany.sca.core.conversation;

import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @version $Rev$ $Date$
 */
public class ConversationManagerImpl implements ConversationManager {

    private List<ConversationListener> listeners = Collections.synchronizedList(new ArrayList<ConversationListener>());
    private Map<Object, ExtendedConversation> conversations = new ConcurrentHashMap<Object, ExtendedConversation>();

    /**
     * the default max age. this is set to 1 hour
     */
    private static final long DEFAULT_MAX_AGE = 60 * 60 * 1000; ;

    /**
     * the default max idle time. this is set to 1 hour
     */
    private static final long DEFAULT_MAX_IDLE_TIME = 60 * 60 * 1000;

    /**
     * the globally used max age
     */
    private final long maxAge;

    /**
     * the globally used max idle time
     */
    private final long maxIdleTime;

    /**
     * the reaper thread
     */
    private final ScheduledExecutorService scheduler;

    /**
     * constructor
     */
    public ConversationManagerImpl() {
    	long mit = DEFAULT_MAX_IDLE_TIME;
    	long ma = DEFAULT_MAX_AGE;

    	scheduler = Executors.newSingleThreadScheduledExecutor();

    	// Allow privileged access to read system property. Requires PropertyPermission in security
        // policy.
        String aProperty = AccessController.doPrivileged(new PrivilegedAction<String>() {
            public String run() {
                return System.getProperty("org.apache.tuscany.sca.core.scope.ConversationalScopeContainer.MaxIdleTime");
            }
        });
    	if (aProperty != null) {
    		try {
    			mit = (new Long(aProperty) * 1000);
    		} catch (NumberFormatException nfe) {
    			// Ignore
    		}
    	}

    	// Allow privileged access to read system property. Requires PropertyPermission in security
        // policy.
        aProperty = AccessController.doPrivileged(new PrivilegedAction<String>() {
            public String run() {
                return System.getProperty("org.apache.tuscany.sca.core.scope.ConversationalScopeContainer.MaxAge");
            }
        });
        if (aProperty != null) {
            try {
                ma = (new Long(aProperty) * 1000);
            } catch (NumberFormatException nfe) {
                // Ignore
            }
        }

        maxAge = ma;
        maxIdleTime = mit;
    }

    /**
     * @see org.apache.tuscany.sca.core.conversation.ConversationManager#addListener(org.apache.tuscany.sca.core.conversation.ConversationListener)
     */
    public void addListener(ConversationListener listener) {
        listeners.add(listener);
    }

    /**
     * @see org.apache.tuscany.sca.core.conversation.ConversationManager#endConversation(org.apache.tuscany.sca.core.conversation.ExtendedConversation)
     */
    public void endConversation(Object conversationID) {
        ExtendedConversation conv = getConversation(conversationID);
        if (conv != null) {
            conv.setState(ConversationState.ENDED);
            for (ConversationListener listener : listeners) {
                listener.conversationEnded(conv);
            }
            conv.setConversationID(null);
            conversations.remove(conversationID);
        } else {
            throw new IllegalStateException("Conversation " + conversationID + " doesn't exist.");
        }
    }

    public void expireConversation(Object conversationID) {
        ExtendedConversation conv = getConversation(conversationID);
        if (conv != null) {
            for (ConversationListener listener : listeners) {
                listener.conversationExpired(conv);
            }
            conversations.remove(conversationID);
        } else {
            throw new IllegalStateException("Conversation " + conversationID + " doesn't exist.");
        }

    }

    /**
     * @see org.apache.tuscany.sca.core.conversation.ConversationManager#getConversation(java.lang.Object)
     */
    public ExtendedConversation getConversation(Object conversationID) {
        // ConcurrentHashMap cannot take null key
        return conversationID == null ? null : conversations.get(conversationID);
    }

    /**
     * @see org.apache.tuscany.sca.core.conversation.ConversationManager#removeListener(org.apache.tuscany.sca.core.conversation.ConversationListener)
     */
    public void removeListener(ConversationListener listener) {
        listeners.remove(listener);
    }

    /**
     * starts the reaper thread
     */
    public void scheduleConversation(ExtendedConversationImpl aConversation, long time)
    {
    	this.scheduler.schedule(aConversation, time, TimeUnit.MILLISECONDS);
    }

    /**
     * stops the reaper thread
     */
    public synchronized void stopReaper() {

        // Prevent the scheduler from submitting any additional reapers,
    	// initiate an orderly shutdown if a reaper task is in progress.
    	this.scheduler.shutdown();
    }


    /**
     * @see org.apache.tuscany.sca.core.conversation.ConversationManager#startConversation(java.lang.Object)
     */
    public ExtendedConversation startConversation(Object conversationID) {

        if (conversationID == null) {
            conversationID = UUID.randomUUID().toString();
        }
        ExtendedConversation conversation = getConversation(conversationID);
        if (conversation != null && conversation.getState() != ConversationState.ENDED) {
            throw new IllegalStateException(conversation + " already exists.");
        }

        conversation = new ExtendedConversationImpl(
        		this, conversationID, ConversationState.STARTED);
        conversations.put(conversationID, conversation);
        for (ConversationListener listener : listeners) {
            listener.conversationStarted(conversation);
        }
        return conversation;
    }

    /**
     * return the default max idle time
     * @param impProvider the implementation Provider to extract any ConversationAttribute details
     */
    public long getMaxIdleTime() {
        return maxIdleTime;
    }

    /**
     * returns the default max age
     * @param impProvider the implementation Provider to extract any ConversationAttribute details
     */
    public long getMaxAge(){
        return maxAge;
    }

    public void destroy() {
        // REVIEW: A more graceful way?
        scheduler.shutdownNow();
        this.listeners.clear();
        this.conversations.clear();
    }
}