-
Notifications
You must be signed in to change notification settings - Fork 36
/
RestUtils.java
472 lines (434 loc) · 16.8 KB
/
RestUtils.java
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/*
* 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.directory.fortress.core.rest;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.directory.fortress.core.GlobalErrIds;
import org.apache.directory.fortress.core.RestException;
import org.apache.directory.fortress.core.model.FortRequest;
import org.apache.directory.fortress.core.model.FortResponse;
import org.apache.directory.fortress.core.model.ObjectFactory;
import org.apache.directory.fortress.core.model.Props;
import org.apache.directory.fortress.core.util.Config;
import org.apache.directory.fortress.core.util.EncryptUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This utility class provides methods that wrap Apache's HTTP Client APIs. This class is thread safe.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public final class RestUtils
{
private static final String CLS_NM = RestUtils.class.getName();
private static final Logger LOG = LoggerFactory.getLogger( CLS_NM );
private static final String HTTP_PW_PROP = "http.pw";
private static final int HTTP_OK = 200;
private static final int HTTP_401_UNAUTHORIZED = 401;
private static final int HTTP_403_FORBIDDEN = 403;
private static final int HTTP_404_NOT_FOUND = 404;
private static CachedJaxbContext cachedJaxbContext = new CachedJaxbContext();
// static member contains this
private static volatile RestUtils sINSTANCE = null;
// These members contain the http coordinates to a running fortress-rest instance:
private String httpUid, httpPw, httpHost, httpPort, httpProtocol, fortressRestVersion, serviceName, uri;
/**
* create a new request and set its tenant id.
* @param szContextId contains the tenant id
* @return a brand new FortRequest
*/
static FortRequest getRequest( String szContextId )
{
FortRequest request = new FortRequest();
request.setContextId(szContextId);
return request;
}
public static RestUtils getInstance()
{
if(sINSTANCE == null)
{
synchronized (RestUtils.class)
{
if(sINSTANCE == null)
{
sINSTANCE = new RestUtils();
}
}
}
return sINSTANCE;
}
private void init()
{
httpUid = Config.getInstance().getProperty( "http.user" );
httpPw = ( ( EncryptUtil.isEnabled() ) ? EncryptUtil.getInstance().decrypt( Config
.getInstance().getProperty( HTTP_PW_PROP ) ) : Config.getInstance().getProperty( HTTP_PW_PROP ) );
httpHost = Config.getInstance().getProperty( "http.host" );
httpPort = Config.getInstance().getProperty( "http.port" );
httpProtocol = Config.getInstance().getProperty( "http.protocol", "http" );
fortressRestVersion = System.getProperty( "version" );
serviceName = "fortress-rest-" + fortressRestVersion;
uri = httpProtocol + "://" + httpHost + ":" + httpPort + "/" + serviceName + "/";
}
private RestUtils(){
init();
}
/**
* Marshall the request into an XML String.
*
* @param request
* @return String containing xml request
* @throws RestException
*/
public static String marshal( FortRequest request ) throws RestException
{
String szRetValue;
try
{
// Create a JAXB context passing in the class of the object we want to marshal/unmarshal
final JAXBContext context = cachedJaxbContext.getJaxbContext( FortRequest.class );
// =============================================================================================================
// Marshalling OBJECT to XML
// =============================================================================================================
// Create the marshaller, that will transform the object into XML
final Marshaller marshaller = context.createMarshaller();
// Create a stringWriter to hold the XML
final StringWriter stringWriter = new StringWriter();
// Marshal the javaObject and write the XML to the stringWriter
marshaller.marshal( request, stringWriter );
szRetValue = stringWriter.toString();
}
catch ( JAXBException je )
{
String error = "marshal caught JAXBException=" + je;
throw new RestException( GlobalErrIds.REST_MARSHALL_ERR, error, je );
}
return szRetValue;
}
/**
* Unmarshall the XML response into its associated Java objects.
*
* @param szResponse
* @return FortResponse
* @throws RestException
*/
public static FortResponse unmarshall( String szResponse ) throws RestException
{
FortResponse response;
try
{
// Create a JAXB context passing in the class of the object we want to marshal/unmarshal
final JAXBContext context = cachedJaxbContext.getJaxbContext( FortResponse.class );
// Create the unmarshaller, that will transform the XML back into an object
final Unmarshaller unmarshaller = context.createUnmarshaller();
response = ( FortResponse ) unmarshaller.unmarshal( new StringReader( szResponse ) );
}
catch ( JAXBException je )
{
String error = "unmarshall caught JAXBException=" + je;
throw new RestException( GlobalErrIds.REST_UNMARSHALL_ERR, error, je );
}
return response;
}
/**
* Perform HTTP Get REST request.
*
* @param userId
* @param password
* @param id
* @param id2
* @param id3
* @param function
* @return String containing response
* @throws RestException
*/
public String get( String userId, String password, String id, String id2, String id3, String function )
throws RestException
{
String url = uri + function + "/" + id;
if ( id2 != null )
{
url += "/" + id2;
}
if ( id3 != null )
{
url += "/" + id3;
}
LOG.debug( "get function1:{}, id1:{}, id2:{}, id3:{}, url:{}", function, id, id2, id3, url );
HttpGet get = new HttpGet(url);
setMethodHeaders( get );
return handleHttpMethod( get ,HttpClientBuilder.create()
.setDefaultCredentialsProvider(getCredentialProvider(userId, password)).build() );
}
/**
* Perform HTTP Get REST request.
*
* @param id
* @param id2
* @param id3
* @param function
* @return String containing response
* @throws RestException
*/
public String get( String id, String id2, String id3, String function ) throws RestException
{
return get( null, null, id, id2, id3, function );
}
/**
* Perform an HTTP Post REST operation.
*
* @param userId
* @param password
* @param szInput
* @param function
* @return String containing response
* @throws RestException
*/
public String post( String userId, String password, String szInput, String function ) throws RestException
{
LOG.debug( "post uri=[{}], function=[{}], request=[{}]", uri, function, szInput );
String szResponse = null;
HttpPost post = new HttpPost( uri + function);
post.addHeader( "Accept", "text/xml" );
setMethodHeaders( post );
try
{
HttpEntity entity = new StringEntity( szInput, ContentType.TEXT_XML );
post.setEntity( entity );
org.apache.http.client.HttpClient httpclient = HttpClientBuilder.create()
.setDefaultCredentialsProvider(getCredentialProvider(userId, password)).build();
HttpResponse response = httpclient.execute( post );
String error;
switch ( response.getStatusLine().getStatusCode() )
{
case HTTP_OK :
szResponse = IOUtils.toString( response.getEntity().getContent(), "UTF-8" );
LOG.debug( "post uri=[{}], function=[{}], response=[{}]", uri, function, szResponse );
break;
case HTTP_401_UNAUTHORIZED :
error = "post uri=[" + uri + "], function=[" + function
+ "], 401 function unauthorized on host";
LOG.error( error );
throw new RestException( GlobalErrIds.REST_UNAUTHORIZED_ERR, error );
case HTTP_403_FORBIDDEN :
error = "post uri=[" + uri + "], function=[" + function
+ "], 403 function forbidden on host";
LOG.error( error );
throw new RestException( GlobalErrIds.REST_FORBIDDEN_ERR, error );
case HTTP_404_NOT_FOUND :
error = "post uri=[" + uri + "], function=[" + function + "], 404 not found from host";
LOG.error( error );
throw new RestException( GlobalErrIds.REST_NOT_FOUND_ERR, error );
default :
error = "post uri=[" + uri + "], function=[" + function
+ "], error received from host: " + response.getStatusLine().getStatusCode();
LOG.error( error );
throw new RestException( GlobalErrIds.REST_UNKNOWN_ERR, error );
}
}
catch ( IOException ioe )
{
String error = "post uri=[" + uri + "], function=[" + function + "] caught IOException=" + ioe;
LOG.error( error );
throw new RestException( GlobalErrIds.REST_IO_ERR, error, ioe );
}
catch ( WebApplicationException we )
{
String error = "post uri=[" + uri + "], function=[" + function
+ "] caught WebApplicationException=" + we;
LOG.error( error );
throw new RestException( GlobalErrIds.REST_WEB_ERR, error, we );
}
catch ( java.lang.NoSuchMethodError e )
{
String error = "post uri=[" + uri + "], function=[" + function
+ "] caught Exception=" + e;
LOG.error( error );
e.printStackTrace();
throw new RestException( GlobalErrIds.REST_UNKNOWN_ERR, error );
}
finally
{
// Release current connection to the connection pool.
post.releaseConnection();
}
return szResponse;
}
/**
* Perform an HTTP Post REST operation.
*
* @param szInput
* @param function
* @return String containing response
* @throws RestException
*/
public String post( String szInput, String function ) throws RestException
{
return post(null,null,szInput, function);
}
private CredentialsProvider getCredentialProvider(String uid, String password) {
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials( new AuthScope( httpHost,Integer.valueOf( httpPort )),
new UsernamePasswordCredentials(uid==null? httpUid :uid,password==null? httpPw :password) );
return credentialsProvider;
}
/**
* Set these params into their associated HTTP header vars.
*
* @param httpRequest
*/
private static void setMethodHeaders( HttpRequest httpRequest )
{
if ( httpRequest instanceof HttpPost || httpRequest instanceof HttpPut)
{
httpRequest.addHeader( "Content-Type", "application/xml" );
httpRequest.addHeader( "Accept", "application/xml" );
}
}
/**
* Convert from non-Base64 to Base64 encoded.
*
* @param value
* @return String contains encoded data
*/
private static String base64Encode( String value )
{
return new String ( Base64.encodeBase64( value.getBytes() ) );
}
/* private static String base64Encode( String value )
{
return Base64Utility.encode( value.getBytes() );
}*/
/**
* Process the HTTP method request.
*
* @param httpGetRequest
* @return String containing response
* @throws Exception
*/
private static String handleHttpMethod( HttpRequestBase httpGetRequest ,org.apache.http.client.HttpClient client ) throws RestException
{
String szResponse = null;
try
{
HttpResponse response = client.execute( httpGetRequest );
LOG.debug( "handleHttpMethod Response status : {}", response.getStatusLine().getStatusCode() );
Response.Status status = Response.Status.fromStatusCode( response.getStatusLine().getStatusCode() );
if ( status == Response.Status.OK )
{
szResponse = IOUtils.toString( response.getEntity().getContent() );
LOG.debug( szResponse );
}
else if ( status == Response.Status.FORBIDDEN )
{
LOG.debug( "handleHttpMethod Authorization failure" );
}
else if ( status == Response.Status.UNAUTHORIZED )
{
LOG.debug( "handleHttpMethod Authentication failure" );
}
else
{
LOG.debug( "handleHttpMethod Unknown error" );
}
}
catch ( IOException ioe )
{
String error = "handleHttpMethod caught IOException=" + ioe;
LOG.error( error );
throw new RestException( GlobalErrIds.REST_IO_ERR, error, ioe );
}
finally
{
// Release current connection to the connection pool.
httpGetRequest.releaseConnection();
}
return szResponse;
}
/**
* @param inProps
* @return Properties
*/
public static Properties getProperties( Props inProps )
{
Properties properties = null;
List<Props.Entry> props = inProps.getEntry();
if ( props.size() > 0 )
{
properties = new Properties();
//int size = props.size();
for ( Props.Entry entry : props )
{
String key = entry.getKey();
String val = entry.getValue();
properties.setProperty( key, val );
}
}
return properties;
}
/**
*
* @param properties
* @return Prop contains name value pairs.
*/
public static Props getProps( Properties properties )
{
Props props = null;
if ( properties != null )
{
props = new ObjectFactory().createProps();
for ( Enumeration<?> e = properties.propertyNames(); e.hasMoreElements(); )
{
String key = ( String ) e.nextElement();
String val = properties.getProperty( key );
Props.Entry entry = new Props.Entry();
entry.setKey( key );
entry.setValue( val );
props.getEntry().add( entry );
}
}
return props;
}
}