Skip to main content
summaryrefslogtreecommitdiffstats
blob: 7b94a645e26cec94b25d74240baac5d09f9fa1fe (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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*
 * Copyright (c) 2012 Robert Bosch Engineering and Business Solutions Ltd India. 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
 */
package org.eclipse.osee.doors.connector.core.oauth;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.util.URIUtil;
import org.eclipse.osee.framework.logging.OseeLog;
import org.scribe.extractors.TokenExtractorImpl;
import org.scribe.model.OAuthConstants;
import org.scribe.model.Token;
import org.scribe.utils.StreamUtils;

/**
 * Class to get request Token, do authentication and to get the access token
 *
 * @author Swapna R
 */
public class DWAOAuthService {

   private String consumer_key;
   private String consumer_secret;

   private static final String VERSION = "1.0";

   private IDWAOSLCProviderInfo config;

   private HttpClient httpClient;

   /**
    * Default Constructor
    */
   public DWAOAuthService() {
      //
   }

   /**
    * Constructor to set the consumer key and secret
    *
    * @param config : OSLCDWAProvider object
    * @param consumer_key :
    * @param consumer_secret :
    */
   public DWAOAuthService(final IDWAOSLCProviderInfo config, final String consumer_key, final String consumer_secret) {
      this.consumer_key = consumer_key;
      this.consumer_secret = consumer_secret;
      this.config = config;

   }

   /**
    * Method to create the session
    */
   public void createSession() {
      if (this.httpClient == null) {
         this.httpClient = new HttpClient();
      }
   }

   /**
    * Method to get the request token
    *
    * @return request token
    */
   public Token getRequestToken() {
      createSession();
      PostMethod requestPostMethod = new PostMethod(this.config.getRequestTokenURL());
      signRequest(OAuthConstants.EMPTY_TOKEN, requestPostMethod, false);

      int requestTokenResponse = -1;

      try {
         requestTokenResponse = this.httpClient.executeMethod(requestPostMethod);
      } catch (HttpException e1) {
         OseeLog.log(DWAOAuthService.class, Level.WARNING, "Failed to obtain valid authentication response");
      } catch (IOException e1) {
         OseeLog.log(DWAOAuthService.class, Level.WARNING, "Failed to obtain valid authentication response");
      }

      Token requestToken = null;
      try {
         OseeLog.log(DWAOAuthService.class, Level.INFO, "requestTokenResponse: " + requestTokenResponse);
         OseeLog.log(DWAOAuthService.class, Level.INFO, "Request Token" + requestPostMethod.getResponseBodyAsString());
         InputStream responseBodyAsStream = requestPostMethod.getResponseBodyAsStream();

         TokenExtractorImpl tokenextractor = new TokenExtractorImpl();
         requestToken = tokenextractor.extract(StreamUtils.getStreamContents(responseBodyAsStream));

      } catch (IOException e1) {
         OseeLog.log(DWAOAuthService.class, Level.WARNING, "Failed to obtain valid authentication response");
      }

      return requestToken;
   }

   /**
    * Method to return the authorizationURL
    *
    * @param requestToken :
    * @return the authorizationURL
    */
   public String getAuthorizeURL(final Token requestToken) {
      String authorizationURL = this.config.getAuthorizeTokenURL() + "?oauth_token=%s";
      return String.format(authorizationURL, requestToken.getToken());
   }

   /**
    * Method to add all the outh parameters and signature to the request
    *
    * @param token : request token to add to teh request
    * @param requestMethod : request method to which parameters are added
    * @param isTokenRequired : boolean to check whether token is added to the request or not
    */
   public void signRequest(final Token token, final HttpMethodBase requestMethod, final boolean isTokenRequired) {
      // add OAuth parameters
      // generate signature
      // create the OAuth Authorization header
      // return the method
      Map<String, String> oauth_parameters = new HashMap<>();
      if (isTokenRequired) {
         oauth_parameters.put(OAuthConstants.TOKEN, token.getToken());
      }
      oauth_parameters.put(OAuthConstants.TIMESTAMP, this.config.getTimestampService().getTimestampInSeconds());
      oauth_parameters.put(OAuthConstants.NONCE, this.config.getTimestampService().getNonce());
      oauth_parameters.put(OAuthConstants.CONSUMER_KEY, this.consumer_key);
      oauth_parameters.put(OAuthConstants.SIGN_METHOD, this.config.getSignatureService().getSignatureMethod());
      oauth_parameters.put(OAuthConstants.VERSION, getVersion());
      oauth_parameters.put(OAuthConstants.TIMESTAMP, this.config.getTimestampService().getTimestampInSeconds());

      oauth_parameters.put(OAuthConstants.SIGNATURE, getSignature(requestMethod, token, oauth_parameters));

      appendSignature(requestMethod, oauth_parameters);

   }

   /**
    * @return version
    */
   public String getVersion() {
      return VERSION;
   }

   /**
    * Method to get access token from the request token
    *
    * @param requestToken : token to generate access token
    * @return access token
    */
   public Token getAccessToken(final Token requestToken) {

      PostMethod accessTokenPostMethod = new PostMethod(this.config.getAccessTokenURL());
      signRequest(requestToken, accessTokenPostMethod, true);

      int accessTokenRequestResponse = -1;

      try {
         accessTokenRequestResponse = this.httpClient.executeMethod(accessTokenPostMethod);
         OseeLog.log(DWAOAuthService.class, Level.INFO, "Response: " + accessTokenRequestResponse);
      } catch (HttpException e1) {
         OseeLog.log(getClass(), Level.SEVERE, e1);
      } catch (IOException e1) {
         OseeLog.log(getClass(), Level.SEVERE, e1);
      }

      Token accessToken = null;
      try {
         if ((accessTokenRequestResponse != 200)) {
            return null;
         }
         OseeLog.log(DWAOAuthService.class, Level.INFO, "Response: " + accessTokenRequestResponse);
         OseeLog.log(DWAOAuthService.class, Level.INFO,
            "Access Token" + accessTokenPostMethod.getResponseBodyAsString());
         InputStream responseBodyAsStream = accessTokenPostMethod.getResponseBodyAsStream();

         TokenExtractorImpl tokenextractor = new TokenExtractorImpl();
         accessToken = tokenextractor.extract(StreamUtils.getStreamContents(responseBodyAsStream));

      } catch (IOException e1) {

         OseeLog.log(getClass(), Level.SEVERE, e1);
      }
      return accessToken;
   }

   /**
    * Method to do authentication
    *
    * @param authorizationURL to authenticate
    * @param token : to sign request
    * @param username to authenticate
    * @param password to authenticate
    */
   public void doAuthentication(final String authorizationURL, final Token token, final String username, final String password) {
      createSession();

      GetMethod authorizeGetMethod = new GetMethod(authorizationURL);

      signRequest(token, authorizeGetMethod, true);
      int authorizeResponse = -1;
      try {
         authorizeResponse = this.httpClient.executeMethod(authorizeGetMethod);
      } catch (HttpException e) {
         OseeLog.log(getClass(), Level.SEVERE, e);
      } catch (IOException e) {
         OseeLog.log(getClass(), Level.SEVERE, e);
      }
      OseeLog.log(DWAOAuthService.class, Level.INFO, "Response: " + authorizeResponse);
      try {
         OseeLog.log(DWAOAuthService.class, Level.INFO, "Response: " + authorizeGetMethod.getResponseBodyAsString());
      } catch (IOException e) {
         OseeLog.log(getClass(), Level.SEVERE, e);
      }
      // POST method to request token url
      // construct Authorization header for oauth params
      PostMethod authenticateMethod =
         new PostMethod(this.config.getOSLCProviderAuthenticationURL() + "?oauth_token=" + token.getToken());
      authenticateMethod.addParameter("j_username", username);
      authenticateMethod.addParameter("j_password", password);
      authenticateMethod.addParameter("loginButton", "Login");

      authenticateMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");

      int authenticateResponse = -1;
      try {
         authenticateResponse = this.httpClient.executeMethod(authenticateMethod);

      } catch (HttpException e) {
         OseeLog.log(getClass(), Level.SEVERE, e);
      } catch (IOException e) {
         OseeLog.log(getClass(), Level.SEVERE, e);
      }
      OseeLog.log(DWAOAuthService.class, Level.INFO, "Response: " + authenticateResponse);

      Header[] responseHeaders = authenticateMethod.getResponseHeaders();
      String url = null;
      for (Header header : responseHeaders) {
         if (header.getName().equals("Location")) {
            url = header.getValue();
            break;
         }
      }

      GetMethod getAuthorisetoken = new GetMethod(url);
      try {
         int executeMethod = this.httpClient.executeMethod(getAuthorisetoken);
         OseeLog.log(DWAOAuthService.class, Level.INFO, "executeMethod: " + executeMethod);

      } catch (HttpException e) {
         OseeLog.log(getClass(), Level.SEVERE, e);
      } catch (IOException e) {
         OseeLog.log(getClass(), Level.SEVERE, e);
      }
   }

   private String getSignature(final HttpMethodBase request, final Token token, final Map<String, String> oauth_params) {
      String baseString = this.config.getBaseStringExtractor().extract(request, oauth_params);
      String signature =
         this.config.getSignatureService().getSignature(baseString, this.consumer_secret, token.getSecret());

      return signature;
   }

   private void appendSignature(final HttpMethodBase request, final Map<String, String> oauth_params) {
      String oauthHeader = this.config.getHeaderExtractor().extract(request, oauth_params);
      request.addRequestHeader(OAuthConstants.HEADER, oauthHeader);
   }

   /**
    * Method to release the connection
    *
    * @param uri : Url to release the connection
    */
   public void releaseConnection(final String uri) {
      if (this.httpClient != null) {
         DeleteMethod deleteMethod = new DeleteMethod(uri);
         try {
            this.httpClient.executeMethod(deleteMethod);
         } catch (HttpException e) {
            OseeLog.log(getClass(), Level.SEVERE, e);
         } catch (IOException e) {
            OseeLog.log(getClass(), Level.SEVERE, e);
         }
      }
   }

   /**
    * Method to get the response from the access token from path
    *
    * @param accessToken to sign the request
    * @param path to get response
    * @param queryString to get the query response
    * @return the response
    */
   public String getResponse(final Token accessToken, final String path, final String queryString) {
      GetMethod authorizeGetMethod = new GetMethod(path);

      authorizeGetMethod.addRequestHeader("Content-Type", "application/x-oslc-rm-requirement-collection-1.0+xml");
      authorizeGetMethod.addRequestHeader("OSLC-Core-Version", "2.0");
      authorizeGetMethod.addRequestHeader("Accept", "application/rdf+xml");
      authorizeGetMethod.addRequestHeader("Accept-Charset", "UTF-8");
      if ((queryString != null) && !queryString.isEmpty()) {
         try {
            authorizeGetMethod.setQueryString(URIUtil.encodeQuery(queryString));
         } catch (URIException e) {
            OseeLog.log(getClass(), Level.SEVERE, e);
         }
      }
      signRequest(accessToken, authorizeGetMethod, true);
      String responseBodyAsString = "";
      @SuppressWarnings("unused")
      int accessTokenRequestResponse = -1;

      try {
         accessTokenRequestResponse = this.httpClient.executeMethod(authorizeGetMethod);
         responseBodyAsString = authorizeGetMethod.getResponseBodyAsString();
      } catch (IOException e) {
         OseeLog.log(getClass(), Level.SEVERE, e);
      }
      return responseBodyAsString;
   }

   /**
    * @return :
    */
   public String getResourceUrl() {
      return this.config.ResourceUrl();

   }

   /**
    * @return
    */
   public HttpClient getHttpClient() {
      return this.httpClient;
   }
}

Back to the top