Skip to main content
summaryrefslogtreecommitdiffstats
blob: ebddf63dd088b8add04a52c5fa2fb4faf7f3b54e (plain) (blame)
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/*******************************************************************************
 * Copyright (c) 2004, 2007 Boeing.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Boeing - initial API and implementation
 *******************************************************************************/
package org.eclipse.osee.framework.core.server.internal;

import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import org.eclipse.osee.framework.core.data.IOseeUserInfo;
import org.eclipse.osee.framework.core.data.OseeCredential;
import org.eclipse.osee.framework.core.data.OseeSession;
import org.eclipse.osee.framework.core.data.OseeSessionGrant;
import org.eclipse.osee.framework.core.exception.OseeCoreException;
import org.eclipse.osee.framework.core.exception.OseeDataStoreException;
import org.eclipse.osee.framework.core.exception.OseeInvalidSessionException;
import org.eclipse.osee.framework.core.exception.OseeWrappedException;
import org.eclipse.osee.framework.core.server.CoreServerActivator;
import org.eclipse.osee.framework.core.server.IApplicationServerManager;
import org.eclipse.osee.framework.core.server.IAuthenticationManager;
import org.eclipse.osee.framework.core.server.ISessionManager;
import org.eclipse.osee.framework.core.server.OseeServerProperties;
import org.eclipse.osee.framework.core.server.SessionData;
import org.eclipse.osee.framework.core.server.SessionData.SessionState;
import org.eclipse.osee.framework.database.core.ConnectionHandler;
import org.eclipse.osee.framework.database.core.DatabaseInfoManager;
import org.eclipse.osee.framework.database.core.OseeSql;
import org.eclipse.osee.framework.jdk.core.util.GUID;
import org.eclipse.osee.framework.jdk.core.util.HttpProcessor;
import org.eclipse.osee.framework.jdk.core.util.Strings;
import org.eclipse.osee.framework.jdk.core.util.HttpProcessor.AcquireResult;
import org.eclipse.osee.framework.jdk.core.util.time.GlobalTime;
import org.eclipse.osee.framework.logging.OseeLog;

/**
 * @author Roberto E. Escobar
 */
public class SessionManager implements ISessionManager {

   private static final long DATASTORE_UPDATE = 1000 * 5;

   private final Map<String, SessionData> sessionCache;
   private final Timer updateTimer;

   public SessionManager() {
      this.sessionCache = Collections.synchronizedMap(new HashMap<String, SessionData>());
      this.updateTimer = new Timer("Persist Session Data Timer");
      updateTimer.scheduleAtFixedRate(new UpdateDataStore(), DATASTORE_UPDATE, DATASTORE_UPDATE);
   }

   @Override
   public List<SessionData> getSessionByClientAddress(String clientAddress) {
      List<SessionData> toReturn = new ArrayList<SessionData>();
      synchronized (sessionCache) {
         for (SessionData sessionData : sessionCache.values()) {
            if (sessionData.getSession().getClientAddress().equals(clientAddress)) {
               toReturn.add(sessionData);
            }
         }
      }
      return toReturn;
   }

   public boolean isAlive(OseeSession oseeSession) throws OseeCoreException {
      boolean wasAlive = false;
      try {
         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
         URL url =
               new URL(String.format("http://%s:%s/osee/request?cmd=pingId", oseeSession.getClientAddress(),
                     oseeSession.getPort()));
         AcquireResult result = HttpProcessor.acquire(url, outputStream);
         if (result.wasSuccessful()) {
            String sessionId = outputStream.toString(result.getEncoding());
            if (Strings.isValid(sessionId)) {
               wasAlive = sessionId.contains(oseeSession.getSessionId());
            }
         }
      } catch (Exception ex) {
         throw new OseeWrappedException(ex);
      }
      return wasAlive;
   }

   @Override
   public List<SessionData> getAllSessions(boolean includeNonServerManagedSessions) throws OseeDataStoreException {
      List<SessionData> toReturn = null;
      if (includeNonServerManagedSessions) {
         toReturn = SessionDataStore.getAllSessions();
      } else {
         synchronized (sessionCache) {
            toReturn = new ArrayList<SessionData>(sessionCache.values());
         }
      }
      return toReturn;
   }

   @Override
   public List<SessionData> getSessionsByUserId(String userId, boolean includeNonServerManagedSessions) throws OseeCoreException {
      Collection<SessionData> sessions = null;
      if (includeNonServerManagedSessions) {
         sessions = SessionDataStore.getAllSessions();
      } else {
         synchronized (sessionCache) {
            sessions = sessionCache.values();
         }
      }
      List<SessionData> toReturn = new ArrayList<SessionData>();
      for (SessionData sessionData : sessions) {
         if (sessionData.getSession().getUserId().equals(userId)) {
            toReturn.add(sessionData);
         }
      }
      return toReturn;
   }

   @Override
   public SessionData getSessionById(String sessionId) {
      return sessionCache.get(sessionId);
   }

   @Override
   public OseeSessionGrant createSession(OseeCredential credential) throws OseeCoreException {
      OseeSessionGrant sessionGrant = null;

      IAuthenticationManager authenticationManager = CoreServerActivator.getAuthenticationManager();
      boolean isAuthenticated = authenticationManager.authenticate(credential);

      if (isAuthenticated) {
         SessionState sessionState = SessionState.CREATED;
         Timestamp timestamp = GlobalTime.GreenwichMeanTimestamp();

         IOseeUserInfo oseeUserInfo = authenticationManager.asOseeUser(credential);

         OseeSession session =
               new OseeSession(GUID.create(), oseeUserInfo.getUserID(), timestamp, credential.getClientMachineName(),
                     credential.getClientAddress(), credential.getPort(), credential.getVersion(), timestamp,
                     sessionState.name().toLowerCase());

         SessionData sessionData = new SessionData(sessionState, session);
         sessionCache.put(sessionData.getSessionId(), sessionData);
         sessionGrant = new OseeSessionGrant(sessionData.getSessionId());
         sessionGrant.setCreationRequired(oseeUserInfo.isCreationRequired());
         sessionGrant.setOseeUserInfo(oseeUserInfo);
         sessionGrant.setDatabaseInfo(DatabaseInfoManager.getDefault());
         sessionGrant.setSqlProperties(OseeSql.getSqlProperties(ConnectionHandler.getMetaData()));
         sessionGrant.setDataStorePath(OseeServerProperties.getOseeApplicationServerData());
      }
      return sessionGrant;
   }

   @Override
   public void releaseSession(String sessionId) {
      SessionData sessionData = getSessionById(sessionId);
      if (sessionData != null) {
         sessionData.setSessionState(SessionState.DELETED);
      }
   }

   @Override
   public void updateSessionActivity(String sessionId, String interactionName) throws OseeInvalidSessionException {
      SessionData sessionData = getSessionById(sessionId);
      if (sessionData != null) {
         if (sessionData.getSessionState() == SessionState.CURRENT) {
            sessionData.setSessionState(SessionState.UPDATED);
         }
         sessionData.getSession().setLastInteraction(Strings.isValid(interactionName) ? interactionName : "");
         sessionData.getSession().setLastInteractionDate(GlobalTime.GreenwichMeanTimestamp());
      } else {
         throw new OseeInvalidSessionException(String.format("Session was invalid: [%s]", sessionId));
      }
   }

   public void releaseSessionImmediate(String... sessionIds) throws OseeCoreException {
      if (sessionIds != null && sessionIds.length > 0) {
         SessionDataStore.deleteSession(sessionIds);
         synchronized (sessionCache) {
            for (String session : sessionIds) {
               sessionCache.remove(session);
            }
         }
      }
   }

   public void shutdown() {
      updateTimer.cancel();
   }

   private final class UpdateDataStore extends TimerTask {

      private boolean firstTimeThrough = true;

      @Override
      public void run() {
         if (firstTimeThrough) {
            firstTimeThrough = false;
            if (SessionDataStore.isSessionTableAvailable()) {
               recoverSessions();
            }
         }

         List<String> deleteIds = new ArrayList<String>();
         List<OseeSession> createData = new ArrayList<OseeSession>();
         List<OseeSession> updateData = new ArrayList<OseeSession>();
         synchronized (sessionCache) {
            for (SessionData sessionData : sessionCache.values()) {
               if (sessionData != null) {
                  switch (sessionData.getSessionState()) {
                     case CREATED:
                        createData.add(sessionData.getSession());
                        break;
                     case DELETED:
                        deleteIds.add(sessionData.getSessionId());
                        break;
                     case UPDATED:
                        updateData.add(sessionData.getSession());
                        break;
                     default:
                        break;
                  }
               }
            }

            createItems(createData);
            updateItems(updateData);
            deleteItems(deleteIds);
         }
      }

      private void recoverSessions() {
         try {
            IApplicationServerManager manager = CoreServerActivator.getApplicationServerManager();
            if (manager != null) {
               String serverId = manager.getId();
               SessionDataStore.loadSessions(serverId, sessionCache);
            }
         } catch (OseeDataStoreException ex) {
            OseeLog.log(CoreServerActivator.class, Level.WARNING, "Error loading sessions.", ex);
         }
      }

      private void updateItems(List<OseeSession> sessionsList) {
         createUpdateHelper(sessionsList, false);
      }

      private void createItems(List<OseeSession> sessionsList) {
         createUpdateHelper(sessionsList, true);
      }

      private void createUpdateHelper(List<OseeSession> sessionsList, boolean isCreate) {
         try {
            if (!sessionsList.isEmpty()) {
               IApplicationServerManager manager = CoreServerActivator.getApplicationServerManager();
               if (manager != null) {
                  String serverId = manager.getId();
                  OseeSession[] sessionsArray = sessionsList.toArray(new OseeSession[sessionsList.size()]);
                  SessionState stateToSet = isCreate ? SessionState.CREATED : SessionState.UPDATED;
                  if (isCreate) {
                     SessionDataStore.createSessions(serverId, sessionsArray);
                  } else {
                     SessionDataStore.updateSessions(serverId, sessionsArray);
                  }
                  for (OseeSession session : sessionsArray) {
                     SessionData sessionData = sessionCache.get(session.getSessionId());
                     if (sessionData.getSessionState() == stateToSet) {
                        sessionData.setSessionState(SessionState.CURRENT);
                     }
                  }
               }
            }
         } catch (OseeDataStoreException ex) {
            // Do Nothing
         }
      }

      private void deleteItems(List<String> sessionIds) {
         try {
            if (!sessionIds.isEmpty()) {
               SessionDataStore.deleteSession(sessionIds.toArray(new String[sessionIds.size()]));
               for (String ids : sessionIds) {
                  sessionCache.remove(ids);
               }
            }
         } catch (OseeDataStoreException ex) {
            // Do Nothing
         }
      }
   }

}

Back to the top