Skip to main content
summaryrefslogtreecommitdiffstats
blob: e4f66640db11d829bb94af56e1f75d1aaf3d37ee (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
/*******************************************************************************
 * 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.client.internal;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.eclipse.osee.framework.core.client.BaseCredentialProvider;
import org.eclipse.osee.framework.core.client.GuestCredentialProvider;
import org.eclipse.osee.framework.core.client.ICredentialProvider;
import org.eclipse.osee.framework.core.client.OseeClientProperties;
import org.eclipse.osee.framework.core.client.OseeClientSession;
import org.eclipse.osee.framework.core.client.server.HttpServer;
import org.eclipse.osee.framework.core.client.server.HttpUrlBuilderClient;
import org.eclipse.osee.framework.core.data.IDatabaseInfo;
import org.eclipse.osee.framework.core.data.OseeClientInfo;
import org.eclipse.osee.framework.core.data.OseeCodeVersion;
import org.eclipse.osee.framework.core.data.OseeCredential;
import org.eclipse.osee.framework.core.data.OseeServerContext;
import org.eclipse.osee.framework.core.data.OseeSessionGrant;
import org.eclipse.osee.framework.core.enums.SystemUser;
import org.eclipse.osee.framework.core.exception.OseeAuthenticationRequiredException;
import org.eclipse.osee.framework.core.exception.OseeCoreException;
import org.eclipse.osee.framework.core.exception.OseeExceptions;
import org.eclipse.osee.framework.core.util.HttpProcessor;
import org.eclipse.osee.framework.core.util.HttpProcessor.AcquireResult;
import org.eclipse.osee.framework.jdk.core.util.Strings;
import org.eclipse.osee.framework.logging.BaseStatus;
import org.eclipse.osee.framework.logging.OseeLog;

/**
 * @author Roberto E. Escobar
 */
public class InternalClientSessionManager {
   public static final String STATUS_ID = "Session Manager";
   private static final InternalClientSessionManager instance = new InternalClientSessionManager();

   private final OseeClientInfo clientInfo;
   private OseeSessionGrant oseeSessionGrant;
   private OseeClientSession oseeSession;

   private InternalClientSessionManager() {
      clearData();
      this.clientInfo = new OseeClientInfo();
      clientInfo.setClientAddress(HttpServer.getServerAddressForExternalCommunication(),
         HttpServer.getDefaultServicePort());
      clientInfo.setClientVersion(OseeCodeVersion.getVersion());
      try {
         clientInfo.setClientMachineName(InetAddress.getLocalHost().getHostName());
      } catch (Exception ex) {
         clientInfo.setClientMachineName(clientInfo.getClientAddress());
      }
   }

   public static InternalClientSessionManager getInstance() {
      return instance;
   }

   public boolean isSessionValid() {
      return oseeSession != null;
   }

   public IDatabaseInfo getDatabaseInfo() throws OseeAuthenticationRequiredException {
      return getOseeSessionGrant().getDatabaseInfo();
   }

   public OseeSessionGrant getOseeSessionGrant() throws OseeAuthenticationRequiredException {
      ensureSessionCreated();
      if (isSessionValid()) {
         return oseeSessionGrant;
      }
      throw new OseeAuthenticationRequiredException("Session is invalid - authentication is required");
   }

   public OseeClientSession getOseeSession() throws OseeAuthenticationRequiredException {
      ensureSessionCreated();
      if (isSessionValid()) {
         return oseeSession;
      }
      throw new OseeAuthenticationRequiredException("Session is invalid - authentication is required");
   }

   public void authenticateAsGuest() throws OseeCoreException {
      authenticate(new GuestCredentialProvider());
   }

   public synchronized OseeClientSession authenticate(ICredentialProvider credentialProvider) throws OseeCoreException {
      if (!OseeApplicationServer.isApplicationServerAlive()) {
         OseeLog.reportStatus(new BaseStatus(STATUS_ID, Level.SEVERE, "Application Server not Available"));
         return null;
      }
      if (!isSessionValid()) {
         try {
            OseeCredential credential = credentialProvider.getCredential();
            clearData();
            oseeSessionGrant = internalAcquireSession(credential);
            oseeSession =
               new OseeClientSession(oseeSessionGrant.getSessionId(), clientInfo.getClientMachineName(),
                  oseeSessionGrant.getUserToken().getUserId(), clientInfo.getClientAddress(), clientInfo.getPort(),
                  clientInfo.getVersion(), credential.getAuthenticationProtocol());
         } catch (Exception ex) {
            OseeLog.reportStatus(new BaseStatus(STATUS_ID, Level.SEVERE, ex));
            OseeExceptions.wrapAndThrow(ex);
         }
         OseeLog.reportStatus(new BaseStatus(STATUS_ID, Level.INFO, "%s BuildType:[%s]", oseeSession,
            oseeSessionGrant.getClientBuildDesignation()));
      }
      return oseeSession;
   }

   public void ensureSessionCreated() {
      if (!isSessionValid()) {
         try {
            authenticate(new BaseCredentialProvider() {
               @Override
               public OseeCredential getCredential() {
                  OseeCredential credential = super.getCredential();
                  String userName =
                     OseeClientProperties.isInDbInit() ? SystemUser.BootStrap.getName() : System.getProperty(
                        "user.name").toLowerCase();
                  credential.setUserName(userName);
                  credential.setDomain("");
                  credential.setPassword("");
                  credential.setAuthenticationProtocol(OseeClientProperties.getAuthenticationProtocol());
                  return credential;
               }
            });
         } catch (Exception ex) {
            OseeLog.log(CoreClientActivator.class, Level.SEVERE, ex);
            try {
               authenticateAsGuest();
            } catch (Exception ex1) {
               OseeLog.log(CoreClientActivator.class, Level.SEVERE, ex1);
            }
         }
      }
   }

   public void releaseSession() throws OseeCoreException {
      if (isSessionValid()) {
         internalReleaseSession(getOseeSessionGrant().getSessionId());
      }
   }

   private void internalReleaseSession(String sessionId) throws OseeCoreException {
      Map<String, String> parameters = new HashMap<String, String>();
      parameters.put("operation", "release");
      parameters.put("sessionId", sessionId);
      try {
         String url =
            HttpUrlBuilderClient.getInstance().getOsgiServletServiceUrl(OseeServerContext.SESSION_CONTEXT, parameters);
         String reponse = HttpProcessor.post(new URL(url));
         OseeLog.log(CoreClientActivator.class, Level.INFO, reponse);
         clearData();
      } catch (Exception ex) {
         OseeExceptions.wrapAndThrow(ex);
      }
   }

   public List<String> getAuthenticationProtocols() {
      List<String> toReturn = new ArrayList<String>();
      try {
         Map<String, String> parameters = new HashMap<String, String>();
         String url =
            HttpUrlBuilderClient.getInstance().getOsgiServletServiceUrl(OseeServerContext.SESSION_CONTEXT, parameters);
         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
         AcquireResult result = HttpProcessor.acquire(new URL(url), outputStream);
         if (result.getCode() == HttpURLConnection.HTTP_OK) {
            String protocols = outputStream.toString("UTF-8");
            if (Strings.isValid(protocols)) {
               String[] results = protocols.split("[\\[\\]\\s,]+");
               for (String entry : results) {
                  if (Strings.isValid(entry)) {
                     toReturn.add(entry);
                  }
               }
            }
         }
      } catch (Exception ex) {
         OseeLog.log(CoreClientActivator.class, Level.SEVERE, ex);
      }
      return toReturn;
   }

   private void clearData() {
      this.oseeSession = null;
      this.oseeSessionGrant = null;
   }

   private OseeSessionGrant internalAcquireSession(OseeCredential credential) throws OseeCoreException, MalformedURLException {
      OseeSessionGrant session = null;
      Map<String, String> parameters = new HashMap<String, String>();
      parameters.put("operation", "create");
      String url =
         HttpUrlBuilderClient.getInstance().getOsgiServletServiceUrl(OseeServerContext.SESSION_CONTEXT, parameters);

      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      AcquireResult result =
         HttpProcessor.post(new URL(url), asInputStream(credential), "text/xml", "UTF-8", outputStream);
      if (result.getCode() == HttpURLConnection.HTTP_ACCEPTED) {
         session = fromEncryptedBytes(outputStream.toByteArray());
      } else {
         throw new OseeCoreException("Error during create session request - code [%s]\n%s", result.getCode(),
            outputStream.toString());
      }
      return session;
   }

   private static ByteArrayInputStream asInputStream(OseeCredential credential) throws OseeCoreException {
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      credential.write(outputStream);

      //TODO ENCRYPT DATA

      return new ByteArrayInputStream(outputStream.toByteArray());
   }

   private static OseeSessionGrant fromEncryptedBytes(byte[] rawData) throws OseeCoreException {
      OseeSessionGrant session = null;
      InputStream inputStream = null;
      try {
         //TODO DECRYPT DATA
         inputStream = new ByteArrayInputStream(rawData);
         session = OseeSessionGrant.fromXml(inputStream);
      } finally {
         if (inputStream != null) {
            try {
               inputStream.close();
            } catch (IOException ex) {
               OseeExceptions.wrapAndThrow(ex);
            }
         }
      }
      return session;
   }
}

Back to the top