forked from google/gdata-java-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServiceException.java
More file actions
608 lines (533 loc) · 17.6 KB
/
Copy pathServiceException.java
File metadata and controls
608 lines (533 loc) · 17.6 KB
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
/* Copyright (c) 2008 Google Inc.
*
* Licensed 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 com.google.gdata.util;
import com.google.gdata.util.common.base.CharEscapers;
import com.google.gdata.client.authn.oauthproxy.OAuthProxyProtocol;
import com.google.gdata.client.authn.oauthproxy.OAuthProxyResponse;
import com.google.gdata.util.ErrorContent.LocationType;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The ServiceException class is the base exception class used to
* indicate an error while processing a GDataRequest.
*
*
*
*
*/
public class ServiceException extends Exception {
// The instance variables of this class are package-private.
// This is done so that the class ServiceExceptionInitializer
// (which is in essence an extension of the HttpURLConnection
// constructor) can set them without violating the taboo about
// calling instance methods such as setters on a partially
// constructed object.
// Instance variables for HTTP
/** HTTP error code. */
int httpErrorCodeOverride = -1;
/**
* Optional HTTP headers to be output when HTTP response is generated.
* It is a mapping from header name to list of header values.
*/
Map<String, List<String>> httpHeaders;
/**
* Optional HTTP content type for a response.
*/
ContentType responseContentType;
/**
* Retrieve HTTP response body or error message.
* The content type must be set correctly.
*/
String responseBody;
// Structured error element.
ErrorElement errorElement = new ErrorElement();
/**
* Set to the exception we are filling during parsing.
*/
List<ServiceException> siblings =
new ArrayList<ServiceException>(1);
{
siblings.add(this);
}
// Server-side constructors for reporting exceptions to client
public ServiceException(String message) {
super(nullsafe(message));
httpHeaders = new HashMap<String, List<String>>();
}
public ServiceException(String message, Throwable cause) {
this(message);
initCause(cause);
}
public ServiceException(Throwable cause) {
this(cause.getMessage());
initCause(cause);
}
/**
* Initializes the ServiceException using the error response data from an
* HTTP connection. This constructor is used in the client library
* to approximately reconstitute the constructor as it appeared
* in the server.
* <p>This constructor uses a ServiceExceptionInitializer to do
* the work of parsing the connection and calling our setters to
* initialize our fields. The initializer object may also create
* sibling ServiceExceptions.
* @param httpConn is the http connection from which the error message
* (structured or simple) is read
* @throws IOException if network error receiving the error response
*/
public ServiceException(HttpURLConnection httpConn) throws IOException {
super(nullsafe(httpConn.getResponseMessage()));
ServiceExceptionInitializer initializer =
new ServiceExceptionInitializer(this);
try {
initializer.parse(httpConn);
} catch (ParseException pe) {
// Clean up after failed parse
errorElement = new ErrorElement();
siblings.clear();
siblings.add(this);
responseContentType = ContentType.TEXT_PLAIN;
}
}
/**
* Initializes the ServiceException using an {@link ErrorContent} object that
* encapsulates most of the information about the error. Most ErrorContent
* instances are declared in a subclass of {@link ErrorDomain} containing all
* the errors for a GData domain (service or portion of service).
*/
public ServiceException(ErrorContent errorCode) {
this(errorCode.getInternalReason());
this.errorElement = new ErrorElement(errorCode);
}
/**
* Initializes the ServiceException using an {@link ErrorContent} object that
* encapsulates most of the information about the error, and an embedded
* exception. Most ErrorContent instances are declared in a subclass of
* {@link ErrorDomain} containing all the errors for this GData domain
* (service or portion of service).
*/
public ServiceException(ErrorContent errorCode, Throwable cause) {
this(errorCode);
initCause(cause);
}
/**
* {@inheritDoc}
*
* <p>If {@code cause} is a {@link ServiceException}, it is added to
* the list of siblings so that the original exception appears when
* using XML error output.
*/
@Override
public Throwable initCause(Throwable cause) {
super.initCause(cause);
if (cause instanceof ServiceException) {
addSibling((ServiceException) cause);
}
return this;
}
// Private method used in constructors
private static String nullsafe(String src) {
return (src != null) ? src : "Exception message unavailable";
}
// Getters and setters
public int getHttpErrorCodeOverride() { return httpErrorCodeOverride; }
public void setHttpErrorCodeOverride(int v) { httpErrorCodeOverride = v; }
public ContentType getResponseContentType() {
return responseContentType;
}
public void setResponseContentType(ContentType v) {
if (v == null) {
throw new NullPointerException("Null content type");
}
responseContentType = v;
}
public String getResponseBody() {
return responseBody;
}
public void setResponseBody(String body) {
if (body == null) {
throw new NullPointerException("Null response body");
}
responseBody = body;
// Create and invoke a ServiceExceptionInitializer to
// do the dirty work of reading the stream, possibly
// parsing the result if it is a GData structured error,
// and set the instance variables accordingly.
// In C++ terms, SEI is a friend class.
ServiceExceptionInitializer initializer =
new ServiceExceptionInitializer(this);
try {
initializer.parse(responseContentType, responseBody);
} catch (ParseException pe) {
throw new RuntimeException(pe.getMessage(), pe);
}
}
/**
* Set HTTP response type and body simultaneously.
* They are inherently coupled together: a body without a content type
* is meaningless; a content type without a body is useless.
*/
public void setResponse(ContentType contentType, String body) {
if (contentType == null) {
throw new NullPointerException("Null content type");
}
if (body == null) {
throw new NullPointerException("Null response body");
}
responseContentType = contentType;
setResponseBody(body);
}
/** Generate error message in XML format. */
/**
* Converts the exception into a well-formated XML error
* message suitable for external uses.
*/
public String toXmlErrorMessage() {
return toXmlErrorMessage(false);
}
/**
* Converts the exception into a well-formated XML error
* message suitable for external uses.
*
* @param includeDebugInfo if {@code true}, include debug information.
* Such error message should only be returned to internal clients.
*/
public String toXmlErrorMessage(boolean includeDebugInfo) {
StringBuilder sb = new StringBuilder();
sb.append("<errors xmlns='http://schemas.google.com/g/2005'>\n");
for (ServiceException sibling : siblings) {
addXmlError(sibling, sb, includeDebugInfo);
}
sb.append("</errors>\n");
return sb.toString();
}
private String escape(String src) {
return CharEscapers.xmlEscaper().escape(src);
}
private void addXmlError(ServiceException se, StringBuilder sb,
boolean includeDebugInfo) {
// Simplistic StringBuffer implementation because the XML is trivial.
sb.append("<error>\n");
String domainName = se.getDomainName();
sb.append("<domain>");
sb.append(escape(domainName));
sb.append("</domain>\n");
String codeName = se.getCodeName();
sb.append("<code>");
sb.append(escape(codeName));
sb.append("</code>\n");
String location = se.getLocation();
LocationType locationType = se.getLocationTypeWithDefault();
if (location != null) {
sb.append("<location type='");
sb.append(escape(locationType.toString()));
sb.append("'>");
sb.append(escape(location));
sb.append("</location>\n");
}
String internalReason = se.getInternalReason();
if (internalReason != null) {
sb.append("<internalReason>");
sb.append(escape(internalReason));
sb.append("</internalReason>\n");
}
String extendedHelp = se.getExtendedHelp();
if (extendedHelp != null) {
sb.append("<extendedHelp>");
sb.append(escape(extendedHelp));
sb.append("</extendedHelp>\n");
}
String sendReport = se.getSendReport();
if (sendReport != null) {
sb.append("<sendReport>");
sb.append(escape(sendReport));
sb.append("</sendReport>\n");
}
if (includeDebugInfo) {
String debugInfo = se.getDebugInfo();
if (debugInfo != null) {
sb.append("<debugInfo>");
sb.append(escape(debugInfo));
sb.append("</debugInfo>\n");
}
}
sb.append("</error>\n");
}
/**
* Return the internal HTTP headers in modifiable form.
*/
public Map<String, List<String>> getHttpHeaders() { return httpHeaders; }
/**
* Return the value for requested internal HTTP header or {@code null} if
* the header is not present.
*
* @param header requested header name
* @return list of string values for the specified header or {@code null} if
* requested header is not found.
*/
public List<String> getHttpHeader(String header) {
if (header == null) {
return httpHeaders.get(header);
}
for (String key : httpHeaders.keySet()) {
if (key != null && key.toLowerCase().equals(header.toLowerCase())) {
return httpHeaders.get(key);
}
}
return null;
}
// Override the default Throwable toString() implementation to add
// the response body (either an explicitly set one or the default XML
// error message) to the resulting output. This is useful because the
// Throwable toString() output is included in exception stack traces,
// so this means the full response will be visible in traces.
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
if (responseBody != null) {
sb.append('\n');
sb.append(responseBody);
}
// purposes, but don't do this until all GData services are converted.
return sb.toString();
}
// Error model getters and setters
/**
* Return error domain.
*
* <p>Defaults to "GData", indicating an error that has
* not yet been upgraded to the new architecture.
*/
public String getDomainName() {
String domainName = errorElement.getDomainName();
return (domainName != null) ? domainName : "GData";
}
/**
* Set error domain.
*
* @throws NullPointerException if {@code domain} is {@code null}.
*/
public void setDomain(String domain) {
errorElement.setDomain(domain);
}
/**
* Return error code.
*
* <p>Defaults to the class name of {@code this}.
*/
public String getCodeName() {
String codeName = errorElement.getCodeName();
return (codeName != null) ? codeName : getClass().getSimpleName();
}
/**
* Set error code.
*
* @throws NullPointerException if {@code code} is {@code null}.
*/
public void setCode(String code) {
errorElement.setCode(code);
}
/**
* Return error location.
*/
public String getLocation() {
return errorElement.getLocation();
}
/**
* Return error location type.
*/
public LocationType getLocationType() {
return errorElement.getLocationType();
}
/**
* Returns error location type, defaulting to {@link LocationType#OTHER}.
*/
private LocationType getLocationTypeWithDefault() {
LocationType type = getLocationType();
return type != null ? type : LocationType.OTHER;
}
/**
* Set XPath-based error location.
* This must be a valid XPath expression sibling to the atom:entry
* element (or the atom:feed element if we are not in an entry).
*
* @throws NullPointerException if {@code location} is {@code null}.
*/
public void setXpathLocation(String location) {
errorElement.setXpathLocation(location);
}
/**
* Set header name for an error in a header.
*
* @throws NullPointerException if {@code location} is {@code null}.
*/
public void setHeaderLocation(String location) {
errorElement.setHeaderLocation(location);
}
/**
* Set generic error location.
*
* @throws NullPointerException if {@code location} is {@code null}.
*/
public void setLocation(String location) {
errorElement.setLocation(location);
}
/**
* Return error internal reason.
*
* <p>Defaults to the message set at construction time.
*/
public String getInternalReason() {
String internalReason = errorElement.getInternalReason();
return (internalReason != null) ? internalReason : super.getMessage();
}
/**
* Return message: same as getInternalReason.
*/
@Override
public String getMessage() {
return getInternalReason();
}
/**
* Sets the internal reason of the error.
*
* @throws NullPointerException if {@code internalReason} is {@code null}.
*/
public void setInternalReason(String internalReason) {
errorElement.setInternalReason(internalReason);
}
/**
* Return URI for extended help
*/
public String getExtendedHelp() {
return errorElement.getExtendedHelp();
}
/**
* Set URI for extended help.
*
* @throws NullPointerException if {@code extendedHelp} is {@code null}.
*/
public void setExtendedHelp(String extendedHelp) {
errorElement.setExtendedHelp(extendedHelp);
}
/**
* Return URI to send report to.
*/
public String getSendReport() {
return errorElement.getSendReport();
}
/**
* Set URI to send report to.
*
* @throws NullPointerException if {@code sendReport} is {@code null}.
*/
public void setSendReport(String sendReport) {
errorElement.setSendReport(sendReport);
}
/**
* Return debugging information.
* Defaults to the stack trace.
*/
public String getDebugInfo() {
return errorElement.getDebugInfo();
}
/**
* Set debugging information.
*
* @throws NullPointerException if {@code debugInfo} is {@code null}.
*/
public void setDebugInfo(String debugInfo) {
errorElement.setDebugInfo(debugInfo);
}
// Logic for handling sibling exceptions.
// All the siblings, including this one. We keep ourselves
// in the sibling list so that all siblings can share a common
// list. There is no hierarchy among siblings, so throwing any
// of them will produce the same result.
/**
* Return an unmodifiable copy of the sibling list.
*/
public List<ServiceException> getSiblings() {
return Collections.unmodifiableList(
new ArrayList<ServiceException>(siblings));
}
/**
* Make {@tt this} and {@tt newbie} siblings, returning {@tt this}.
* All sibling exceptions are jointly converted to an
* error message when any of them are thrown.
*/
public ServiceException addSibling(ServiceException newbie) {
if (newbie == null) {
throw new NullPointerException("Null exception being added");
}
for (ServiceException newbieSibling : newbie.siblings) {
if (!siblings.contains(newbieSibling)) {
siblings.add(newbieSibling);
}
newbieSibling.siblings = siblings;
}
return this;
}
/**
* Return true if this ServiceException matches the specified
* {@link ErrorContent} in domain name and code name. Sibling exceptions are
* not checked.
*/
public boolean matches(ErrorContent code) {
return getDomainName().equals(code.getDomainName())
&& getCodeName().equals(code.getCodeName());
}
/**
* Return true if this ServiceException or any of its sibling exceptions
* matches the specified {@link ErrorContent} in domain name and code name.
* If you want to know <i>which</i> particular ServiceException matched, call
* {@link #getSiblings} and examine the individual ServiceExceptions with
* {@link #matches}.
*/
public boolean matchesAny(ErrorContent errorCode) {
for (ServiceException se : siblings) {
if (se.matches(errorCode)) {
return true;
}
}
return false;
}
/**
* Returns whether or not the request has OAuth Proxy-related headers.
*/
public boolean hasOAuthProxyResponse() {
return httpHeaders.containsKey(
OAuthProxyProtocol.Header.X_OAUTH_APPROVAL_URL)
|| httpHeaders.containsKey(OAuthProxyProtocol.Header.X_OAUTH_STATE)
|| httpHeaders.containsKey(OAuthProxyProtocol.Header.X_OAUTH_ERROR)
|| httpHeaders.containsKey(OAuthProxyProtocol.Header.X_OAUTH_ERROR);
}
/**
* Returns the headers related to the OAuth Proxy. If there are no OAuth
* Proxy related headers on the request, this method will return an
* {@link OAuthProxyResponse} object with null values for the headers. Use
* {@link #hasOAuthProxyResponse()} to determine whether the request has
* OAuth Proxy information.
*/
public OAuthProxyResponse getOAuthProxyResponse() {
return new OAuthProxyResponse(httpHeaders);
}
}