forked from google/gdata-java-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathService.java
More file actions
2194 lines (1964 loc) · 81.1 KB
/
Copy pathService.java
File metadata and controls
2194 lines (1964 loc) · 81.1 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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* 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.client;
import com.google.gdata.util.common.base.Preconditions;
import com.google.gdata.util.common.net.UriParameterMap;
import com.google.gdata.client.AuthTokenFactory.AuthToken;
import com.google.gdata.client.batch.BatchInterruptedException;
import com.google.gdata.client.http.HttpGDataRequest;
import com.google.gdata.data.AbstractExtension;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.ExtensionProfile;
import com.google.gdata.data.IAtom;
import com.google.gdata.data.IEntry;
import com.google.gdata.data.IFeed;
import com.google.gdata.data.ILink;
import com.google.gdata.data.ParseSource;
import com.google.gdata.data.introspection.IServiceDocument;
import com.google.gdata.model.Element;
import com.google.gdata.model.ElementKey;
import com.google.gdata.model.ElementMetadata;
import com.google.gdata.model.MetadataContext;
import com.google.gdata.model.MetadataRegistry;
import com.google.gdata.model.Schema;
import com.google.gdata.model.atom.Feed;
import com.google.gdata.model.batch.BatchUtils;
import com.google.gdata.model.transforms.atom.AtomVersionTransforms;
import com.google.gdata.model.transforms.atompub.AtompubVersionTransforms;
import com.google.gdata.util.ContentType;
import com.google.gdata.util.NotModifiedException;
import com.google.gdata.util.ParseException;
import com.google.gdata.util.PreconditionFailedException;
import com.google.gdata.util.ResourceNotFoundException;
import com.google.gdata.util.ServiceException;
import com.google.gdata.util.Version;
import com.google.gdata.util.VersionRegistry;
import com.google.gdata.wireformats.AltFormat;
import com.google.gdata.wireformats.AltRegistry;
import com.google.gdata.wireformats.StreamProperties;
import com.google.gdata.wireformats.input.AtomDualParser;
import com.google.gdata.wireformats.input.AtomServiceDualParser;
import com.google.gdata.wireformats.input.InputParser;
import com.google.gdata.wireformats.input.InputProperties;
import com.google.gdata.wireformats.output.AtomDualGenerator;
import com.google.gdata.wireformats.output.AtomServiceDualGenerator;
import com.google.gdata.wireformats.output.OutputGenerator;
import com.google.gdata.wireformats.output.OutputProperties;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.util.Collection;
import java.util.Map;
/**
* The Service class represents a client connection to a GData service. It
* encapsulates all protocol-level interactions with the GData server and acts
* as a helper class for higher level entities (feeds, entries, etc) that invoke
* operations on the server and process their results.
* <p>
* This class provides the base level common functionality required to access
* any GData service. It is also designed to act as a base class that can be
* customized for specific types of GData services. Examples of supported
* customizations include:
* <ul>
* <li><b>Authentication</b> - implementing a custom authentication
* mechanism for services that require authentication and use something other
* than HTTP basic or digest authentication.
* <li><b>Extensions</b> - define expected extensions for feed, entry, and
* other types associated with a the service.
* <li><b>Formats</b> - define additional custom resource representations that
* might be consumed or produced by the service and client side parsers and
* generators to handle them.
* </ul>
*
*
*/
public class Service {
private static final String SERVICE_VERSION =
"GData-Java/" + Service.class.getPackage().getImplementationVersion()
+ "(gzip)"; // Necessary to get GZIP encoded responses
/**
* The Versions class defines {@link Version} constants representing the set
* of active versions of the GData core protocol and common data model
* classes.
*/
public static class Versions {
/**
* Version 1. GData core protocol released in May 2006 and is still in use
* by version 1 of some GData services.
*/
public static final Version V1 = new Version(Service.class, 1, 0);
/**
* Version 2. GData core protocol release that brings full alignment with
* the now standard Atom Publishing Protocol specification and migrates to
* OpenSearch 1.1.
*/
public static final Version V2 = new Version(Service.class, 2, 0);
/**
* Version {@code 2.1}. Support new gd:kind attribute on feeds and
* entries.
*/
public static final Version V2_1 = new Version(Service.class, 2, 1);
/**
* Version {@code 2.2}. Unreleased next minor version of the GData
* protocol.
*/
public static final Version V2_2 = new Version(Service.class, 2, 2);
/**
* Version 3. Unreleased next major version of the GData protocol that will
* default to structured error messages.
*/
public static final Version V3 = new Version(Service.class, 3, 0);
private Versions() {}
}
/**
* Initializes the default client version for the GData core protocol.
*/
@SuppressWarnings("unused")
private static final Version CORE_VERSION =
initServiceVersion(Service.class, Versions.V1);
/**
* The GDataRequest interface represents a streaming connection to a GData
* service that can be used either to send request data to the service using
* an OutputStream (or XmlWriter for XML content) or to receive response data
* from the service as an InputStream (or ParseSource for XML data). The
* calling client then has full control of the request data generation and
* response data parsing. This can be used to integrate GData services with an
* external Atom or RSS parsing library, such as Rome.
* <p>
* A GDataRequest instance will be returned by the streaming client APIs of
* the Service class. The basic usage pattern is:
* <p>
*
* <pre>
* GDataRequest request = ... // createXXXRequest API call
* try {
* OutputStream requestStream = request.getRequestStream();
* // stream request data, if any
* request.execute() // execute the request
* InputStream responseStream = request.getResponseStream();
* // process the response data, if any
* }
* catch (IOException ioe) {
* // handle errors writing to / reading from server
* } catch (ServiceException se) {
* // handle service invocation errors
* } finally {
* request.end();
* }
* </pre>
*
* @see Service#createEntryRequest(URL)
* @see Service#createFeedRequest(URL)
* @see Service#createInsertRequest(URL)
* @see Service#createUpdateRequest(URL)
* @see Service#createDeleteRequest(URL)
*/
public interface GDataRequest {
/**
* The RequestType enumeration defines the set of expected GData request
* types. These correspond to the four operations of the GData protocol:
* <ul>
* <li><b>QUERY</b> - query a feed, entry, or description document.</li>
* <li><b>INSERT</b> - insert a new entry into a feed.</li>
* <li><b>UPDATE</b> - update an existing entry within a feed.</li>
* <li><b>PATCH</b> - patch an existing entry within a feed.</li>
* <li><b>DELETE</b> - delete an existing entry within a feed.</li>
* <li><b>BATCH</b> - execute several insert/update/delete operations</li>
* </ul>
*/
public enum RequestType {
QUERY, INSERT, UPDATE, PATCH, DELETE, BATCH
}
/**
* Sets the number of milliseconds to wait for a connection to the remote
* GData service before timing out.
*
* @param timeout the read timeout. A value of zero indicates an infinite
* timeout.
* @throws IllegalArgumentException if the timeout value is negative.
*
* @see java.net.URLConnection#setConnectTimeout(int)
*/
public void setConnectTimeout(int timeout);
/**
* Sets the number of milliseconds to wait for a response from the remote
* GData service before timing out.
*
* @param timeout the read timeout. A value of zero indicates an infinite
* timeout.
* @throws IllegalArgumentException if the timeout value is negative.
*
* @see java.net.URLConnection#setReadTimeout(int)
*/
public void setReadTimeout(int timeout);
/**
* Sets the entity tag value that will be used to conditionalize the request
* if not {@code null}. For a query requests, the tag will cause the target
* resource to be returned if the resource entity tag <b>does not match</b>
* the specified value (i.e. if the resource has not changed). For update or
* delete request types, the entity tag value is used to indicate that the
* requested operation should occur only if the specified etag value <b>does
* match</b> the specified value (i.e. if the resource has changed). A
* request entity tag value may not be associated with other request types.
*
* @param etag
*/
public void setEtag(String etag);
/**
* Sets the If-Modified-Since date precondition to be applied to the
* request. If this precondition is set, then the request will be performed
* only if the target resource has been modified since the specified date;
* otherwise, a {@code NotModifiedException} will be thrown. The default
* value is {@code null}, indicating no precondition.
*
* @param conditionDate the date that should be used to limit the operation
* on the target resource. The operation will only be performed if
* the resource has been modified later than the specified date.
*/
public void setIfModifiedSince(DateTime conditionDate);
/**
* Sets a request header (and logs it, if logging is enabled)
*
* @param name the header name
* @param value the header value
*/
public void setHeader(String name, String value);
/**
* Sets request header (and log just the name but not the value, if logging
* is enabled)
*
* @param name the header name
* @param value the header value
*/
public void setPrivateHeader(String name, String value);
/**
* Returns the {@link URL} that is the target of the GData request
*/
public URL getRequestUrl();
/**
* Returns a stream that can be used to write request data to the GData
* service.
*
* @return OutputStream that can be used to write GData request data.
* @throws IOException error obtaining the request output stream.
*/
public OutputStream getRequestStream() throws IOException;
/**
* Returns the {@link ContentType} of the data that will be written to the
* service by this request or {@code null} if no data is written to the
* server by the request.
*/
public ContentType getRequestContentType();
/**
* Executes the GData service request.
*
* @throws IOException error writing to or reading from GData service.
* @throws com.google.gdata.util.ResourceNotFoundException invalid request
* target resource.
* @throws ServiceException system error executing request.
*/
public void execute() throws IOException, ServiceException;
/**
* Returns the content type of the GData response.
*
* @return ContentType the GData response content type or {@code null} if no
* response content.
* @throws IllegalStateException attempt to read content type without first
* calling {@link #execute()}.
* @throws IOException error obtaining the response content type.
* @throws ServiceException error obtaining the response content type.
*/
public ContentType getResponseContentType() throws IOException,
ServiceException;
/**
* Returns an input stream that can be used to read response data from the
* GData service. Returns null if response data cannot be read as an input
* stream. Use {@link #getParseSource()} instead.
* <p>
* <b>The caller is responsible for ensuring that the input stream is
* properly closed after the response has been read.</b>
*
* @return InputStream providing access to GData response input stream.
* @throws IllegalStateException attempt to read response without first
* calling {@link #execute()}.
* @throws IOException error obtaining the response input stream.
*/
public InputStream getResponseStream() throws IOException;
/**
* Returns the value of the specified response header name or {@code null}
* if no response header of this type exists.
*
* @param headerName name of header
* @return header value.
*/
public String getResponseHeader(String headerName);
/**
* Returns the value of a header containing a header or {@code null} if no
* response header of this type exists or it could not be parsed as a valid
* date.
*
* @param headerName name of header
* @return header value.
*/
public DateTime getResponseDateHeader(String headerName);
/**
* Returns a parse source that can be used to read response data from the
* GData service. Parse source is an abstraction over input streams,
* readers, and other forms of input.
* <p>
* <b>The caller is responsible for ensuring that input streams and readers
* contained in the parse source are properly closed after the response has
* been read.</b>
*
* @return ParseSource providing access to GData response data.
* @throws IllegalStateException attempt to read response without first
* calling {@link #execute()}.
* @throws IOException error obtaining the response data.
* @throws ServiceException error obtaining the response data.
*/
public ParseSource getParseSource() throws IOException, ServiceException;
/**
* Ends all processing associated with this request and releases any
* transient resources (such as open data streams) required for execution.
*/
public void end();
}
/**
* The GDataRequestFactory interface defines a basic factory interface for
* constructing a new GDataRequest interface.
*/
public interface GDataRequestFactory {
/**
* Set a header that will be included in all requests. If header of the same
* name was previously set, then replace the previous header value.
*
* @param header the name of the header
* @param value the value of the header, if null, then unset that header.
*/
public void setHeader(String header, String value);
/**
* Set a header that will be included in all requests and do not log the
* value. Useful for values that are sensitive or related to security. If
* header of the same name was previously set, then replace the previous
* header value.
*
* @param header the name of the header
* @param value the value of the header. If null, then unset that header.
*/
public void setPrivateHeader(String header, String value);
/**
* Set authentication token to be used on subsequent requests created via
* {@link #getRequest(
* com.google.gdata.client.Service.GDataRequest.RequestType, URL,
* ContentType)}.
*
* An {@link IllegalArgumentException} is thrown if an auth token of the
* wrong type is passed, or if authentication is not supported.
*
* @param authToken Authentication token.
*/
public void setAuthToken(AuthToken authToken);
/**
* Creates a new GDataRequest instance of the specified RequestType.
* <p>
* Clients should be sure to call {@link GDataRequest#end()} on the returned
* request once they have finished using it.
*
* @param type the request type
* @param requestUrl the target URL for the request
* @param contentType the contentType of the data being provided in the
* request body. May be {@code null} if no data is provided.
*/
public GDataRequest getRequest(GDataRequest.RequestType type,
URL requestUrl, ContentType contentType) throws IOException,
ServiceException;
/**
* Creates a new GDataRequest instance for querying a service. This method
* pushes the query parameters down to the factory method instead of
* serializing them as a URL. Some factory implementations prefer to get
* access to query parameters in their original form, not as a URL.
* <p>
* Clients should be sure to call {@link GDataRequest#end()} on the returned
* request once they have finished using it.
*
* @param query the query associated with the request
* @param contentType this parameter is unused but remains for backwards
* compatibility.
*/
public GDataRequest getRequest(Query query, ContentType contentType)
throws IOException, ServiceException;
}
/**
* Initializes the version information for a specific service type. Subclasses
* of {@link Service} will generally call this method from within their static
* initializers to bind version information for the associated service.
*
* @param serviceClass the service type being initialized.
* @param defaultVersion the service version expected by this client library.
*/
protected static Version initServiceVersion(
Class<? extends Service> serviceClass, Version defaultVersion) {
VersionRegistry versionRegistry = VersionRegistry.ensureRegistry();
Version v = null;
try {
// Check to see if default has already been defined
v = versionRegistry.getVersion(serviceClass);
} catch (IllegalStateException ise) {
// If not, use system property override or provided default version
try {
v = VersionRegistry.getVersionFromProperty(serviceClass);
} catch (SecurityException e) {
// Ignore exception, and just take default.
}
if (v == null) {
v = defaultVersion;
}
// Do not include any implied versions, which are defaulted separately
// by their own service static initialization.
versionRegistry.addDefaultVersion(v, false);
}
return v;
}
/**
* Returns the current {@link Version} of the GData core protocol.
*
* @return protocol version.
*/
public static Version getVersion() {
return VersionRegistry.get().getVersion(Service.class);
}
@SuppressWarnings("unchecked")
private static Version initProtocolVersion(
Class<? extends Service> serviceClass) {
// Find the service type with a declared default version that is
// closest to the requested service type. Walking up the class hierarchy
// allows for the possibility of subclassing without defining a different
// protocol type
Class<? extends Service> checkClass = serviceClass;
VersionRegistry registry = VersionRegistry.get();
while (checkClass != Service.class) {
try {
return registry.getVersion(checkClass);
} catch (IllegalStateException ise) {
checkClass = (Class<? extends Service>) checkClass.getSuperclass();
}
}
// If no matching default, just return the core protocol version
try {
return Service.getVersion();
} catch (IllegalStateException ise) {
return CORE_VERSION;
}
}
/**
* Constructs a new Service instance that is configured to accept arbitrary
* extension data within feed or entry elements.
*/
public Service() {
// Set the default User-Agent value for requests
requestFactory.setHeader("User-Agent", getServiceVersion());
// Initialize the protocol version for this Service instance
protocolVersion = initProtocolVersion(getClass());
// The default extension profile is configured to accept arbitrary XML
// at the feed or entry level. A client never wants to lose any
// foreign markup, so capture everything even if not explicitly
// understood.
new com.google.gdata.data.Feed().declareExtensions(extProfile);
// The default metadata registry contains the basic feed plus the
// version transforms for atom and atompub.
this.metadataRegistry = new MetadataRegistry();
Feed.registerMetadata(metadataRegistry);
AtomVersionTransforms.addTransforms(metadataRegistry);
AtompubVersionTransforms.addTransforms(metadataRegistry);
}
/**
* Returns an {@link AltRegistry} instance that is configured with the
* default parser/generator configuration for a media service.
*/
public static AltRegistry getDefaultAltRegistry() {
return BASE_REGISTRY;
}
/**
* The DEFAULT_REGISTRY contains the default set of representations and
* associated parser/generator configurations for all services. It will be
* used as the default configuration for all Service instances unless
* {@link #setAltRegistry(AltRegistry)} is called.
*/
private static final AltRegistry BASE_REGISTRY = new AltRegistry();
static {
BASE_REGISTRY.register(AltFormat.ATOM,
new AtomDualParser(),
new AtomDualGenerator());
BASE_REGISTRY.register(AltFormat.ATOM_SERVICE,
new AtomServiceDualParser(),
new AtomServiceDualGenerator());
BASE_REGISTRY.register(AltFormat.APPLICATION_XML,
null,
new AtomDualGenerator(AltFormat.APPLICATION_XML));
// protect against subsequent changes
BASE_REGISTRY.lock();
}
/**
* The version of the service protocol to use for this service instance. It
* will be initialized to the service default version but can be set
* explicitly by calling {@link #setProtocolVersion(Version)}.
*/
private Version protocolVersion;
/**
* Returns the service protocol version that will be used for requests
* generated by this service.
*
* @return service protocol version
*/
public Version getProtocolVersion() {
return protocolVersion;
}
/**
* Sets the service protocol version that will be used for requests associated
* with this service.
*
* @param v new service protocol version.
*/
public void setProtocolVersion(Version v) {
// Ensure that any set version is appropriate for this service type, based
// upon the default type that was computed at construction time.
if (!protocolVersion.getServiceClass().equals(v.getServiceClass())) {
throw new IllegalArgumentException("Invalid service class, " +
"was: " + v.getServiceClass() +
", expected: " + protocolVersion.getServiceClass());
}
protocolVersion = v;
}
protected void startVersionScope() {
VersionRegistry.get().setThreadVersion(protocolVersion);
}
protected void endVersionScope() {
VersionRegistry.get().resetThreadVersion();
}
/**
* Returns information about the service version.
*/
public String getServiceVersion() {
return SERVICE_VERSION;
}
protected ExtensionProfile extProfile = new ExtensionProfile();
/**
* Returns the {@link ExtensionProfile} that defines any expected extensions
* to the base RSS/Atom content model.
*/
public ExtensionProfile getExtensionProfile() {
return extProfile;
}
/**
* Sets the {@link ExtensionProfile} that defines any expected extensions to
* the base RSS/Atom content model.
*/
public void setExtensionProfile(ExtensionProfile v) {
this.extProfile = v;
}
protected final MetadataRegistry metadataRegistry;
/**
* Returns the {@link MetadataRegistry} that defines the expected metadata.
*/
public MetadataRegistry getMetadataRegistry() {
return metadataRegistry;
}
/**
* Returns the {@link Schema} that contains the metadata about
* element types parsed or generated by this service.
*/
public Schema getSchema() {
return metadataRegistry.createSchema();
}
/**
* The GDataRequestFactory associated with this service. The default is the
* base HttpGDataRequest Factory class.
*/
protected GDataRequestFactory requestFactory = new HttpGDataRequest.Factory();
/**
* Returns the GDataRequestFactory currently associated with the service.
*/
public GDataRequestFactory getRequestFactory() {
return requestFactory;
}
/**
* Sets the GDataRequestFactory currently associated with the service.
*/
public void setRequestFactory(GDataRequestFactory requestFactory) {
this.requestFactory = requestFactory;
}
/**
* Set a header that will be included in all requests. If header of the same
* name was previously set, then replace the previous header value.
*
* @param header the name of the header
* @param value the value of the header, if null, then unset that header.
*/
public void setHeader(String header, String value) {
getRequestFactory().setHeader(header, value);
}
/**
* Set a header that will be included in all requests and do not log the
* value. Useful for values that are sensitive or related to security. If
* header of the same name was previously set, then replace the previous
* header value.
*
* @param header the name of the header
* @param value the value of the header. If null, then unset that header.
*/
public void setPrivateHeader(String header, String value) {
getRequestFactory().setPrivateHeader(header, value);
}
/**
* Adds OAuth Proxy-related headers to the request. The OAuth Proxy
* simplifies the OAuth dance on when running in App Engine.
* @see <a href="http://sites.google.com/site/oauthgoog/Home/gaeoauthproxy">
* http://sites.google.com/site/oauthgoog/Home/gaeoauthproxy</a>
*/
public void setOAuthProxyHeaders(Map<String, String> headers) {
for (String key : headers.keySet()) {
setHeader(key, headers.get(key));
}
}
/**
* Sets the HttpGDataRequest.Factory associate with the service
* to use secure connections.
*/
public void useSsl() {
if (!(this.requestFactory instanceof HttpGDataRequest.Factory)) {
throw new UnsupportedOperationException("Not a http transport");
}
((HttpGDataRequest.Factory) this.requestFactory).useSsl();
}
/**
* Defines the languages accepted by the application.
*
* This parameters defines the human language the service should use for
* generated strings. Different services support different languages, please
* check the service documentation.
*
* If no language on this list is accepted by the service, and if the list
* does not contain {@code *} to accept all languages, the exception
* in the exception {@link com.google.gdata.util.NotAcceptableException}.
*
* The service will choose the best available language on this list. Check the
* attribute {@code xml:lang} on the relevant tags, such as atom:content,
* atom:title and atom:category.
*
* @param acceptedLanguages list of accepted languages, as defined
* in section 14.4 of RFC 2616
*/
public void setAcceptLanguage(String acceptedLanguages) {
this.requestFactory.setHeader(
GDataProtocol.Header.ACCEPT_LANGUAGE, acceptedLanguages);
}
/**
* Creates a new GDataRequest for use by the service.
* <p>
* Clients should be sure to call {@link GDataRequest#end()} on the
* returned request once they have finished using it.
*/
public GDataRequest createRequest(GDataRequest.RequestType type,
URL requestUrl, ContentType inputType) throws IOException,
ServiceException {
GDataRequest request =
requestFactory.getRequest(type, requestUrl, inputType);
setTimeouts(request);
return request;
}
/**
* Creates a new GDataRequest for querying the service.
* <p>
* Clients should be sure to call {@link GDataRequest#end()} on the
* returned request once they have finished using it.
*/
protected GDataRequest createRequest(Query query, ContentType inputType)
throws IOException, ServiceException {
GDataRequest request = requestFactory.getRequest(query, inputType);
setTimeouts(request);
return request;
}
/**
* Sets timeout value for GDataRequest.
*/
public void setTimeouts(GDataRequest request) {
if (connectTimeout >= 0) {
request.setConnectTimeout(connectTimeout);
}
if (readTimeout >= 0) {
request.setReadTimeout(readTimeout);
}
}
/**
* Content type of data posted to the GData service. Defaults to Atom using
* UTF-8 character set.
*/
private ContentType contentType = ContentType.ATOM;
/**
* Returns the default ContentType for data associated with this GData
* service.
*/
public ContentType getContentType() {
return contentType;
}
/**
* Sets the default ContentType for writing data to the GData service.
*/
public void setContentType(ContentType contentType) {
this.contentType = contentType;
}
/**
* Client-configured connection timeout value. A value of -1 indicates the
* client has not set any timeout.
*/
protected int connectTimeout = -1;
/**
* Sets the default wait timeout (in milliseconds) for a connection to the
* remote GData service.
*
* @param timeout the read timeout. A value of zero indicates an infinite
* timeout.
* @throws IllegalArgumentException if the timeout value is negative.
*
* @see java.net.URLConnection#setConnectTimeout(int)
*/
public void setConnectTimeout(int timeout) {
if (timeout < 0) {
throw new IllegalArgumentException("Timeout value cannot be negative");
}
connectTimeout = timeout;
}
/**
* Client configured read timeout value. A value of -1 indicates the client
* has not set any timeout.
*/
int readTimeout = -1;
/**
* Sets the default wait timeout (in milliseconds) for a response from the
* remote GData service.
*
* @param timeout the read timeout. A value of zero indicates an infinite
* timeout.
* @throws IllegalArgumentException if the timeout value is negative.
*
* @see java.net.URLConnection#setReadTimeout(int)
*/
public void setReadTimeout(int timeout) {
if (timeout < 0) {
throw new IllegalArgumentException("Timeout value cannot be negative");
}
readTimeout = timeout;
}
/**
* The alternate representation registry that describes formats supported by
* the remote GData service.
*/
private AltRegistry altRegistry = BASE_REGISTRY;
/**
* Returns the alternate registration registry that describes representations
* that may be parsed from or generated to the remote GData service.
*/
public AltRegistry getAltRegistry() {
return altRegistry;
}
public void setAltRegistry(AltRegistry altRegistry) {
this.altRegistry = altRegistry;
}
private boolean strictValidation = true;
/**
* Returns {@code true} if strict validation is enabled for
* this service.
*/
public boolean getStrictValidation() {
return strictValidation;
}
/**
* Enables or disables strict validation. It is enabled by
* default. When this flag is enabled, the client library rejects
* unknown attributes and validates both input and output data.
*/
public void setStrictValidation(boolean strictValidation) {
this.strictValidation = strictValidation;
}
// Helper method that narrows the scope of unchecked (but safe) class casting.
@SuppressWarnings("unchecked")
protected <T> Class<T> classOf(T object) {
return (Class<T>) object.getClass();
}
/**
* Returns the Atom introspection Service Document associated with a
* particular feed URL. This document provides service metadata about the set
* of Atom services associated with the target feed URL.
*
* @param feedUrl the URL associated with a feed. This URL can not include any
* query parameters.
* @param serviceClass the class used to represent a service document,
* not {@code null}.
* @return ServiceDocument resource referenced by the input URL.
* @throws IOException error sending request or reading the feed.
* @throws com.google.gdata.util.ParseException error parsing the returned
* service data.
* @throws com.google.gdata.util.ResourceNotFoundException invalid feed URL.
* @throws ServiceException system error retrieving service document.
*/
public <S extends IServiceDocument> S introspect(URL feedUrl,
Class<S> serviceClass) throws IOException, ServiceException {
String feedQuery = feedUrl.getQuery();
String altParam =
GDataProtocol.Parameter.ALT + "=" + AltFormat.ATOM_SERVICE.getName();
if (feedQuery == null || feedQuery.indexOf(altParam) == -1) {
char appendChar = (feedQuery == null) ? '?' : '&';
feedUrl = new URL(feedUrl.toString() + appendChar + altParam);
}
GDataRequest request = createFeedRequest(feedUrl);
try {
startVersionScope();
request.execute();
return parseResponseData(request, serviceClass);
} finally {
endVersionScope();
request.end();
}
}
/**
* Returns the Feed associated with a particular feed URL, if it's been
* modified since the specified date.
*
* @param feedUrl the URL associated with a feed. This URL can include GData
* query parameters.
* @param feedClass the class used to represent a service Feed.
* @param ifModifiedSince used to set a precondition date that indicates the
* feed should be returned only if it has been modified after the
* specified date. A value of {@code null} indicates no precondition.
* @return Feed resource referenced by the input URL.
* @throws IOException error sending request or reading the feed.
* @throws com.google.gdata.util.NotModifiedException if the feed resource has
* not been modified since the specified precondition date.
* @throws com.google.gdata.util.ParseException error parsing the returned
* feed data.
* @throws com.google.gdata.util.ResourceNotFoundException invalid feed URL.
* @throws ServiceException system error retrieving feed.
*/
@SuppressWarnings("unchecked")
public <F extends IFeed> F getFeed(URL feedUrl, Class<F> feedClass,
DateTime ifModifiedSince) throws IOException, ServiceException {
GDataRequest request = createFeedRequest(feedUrl);
return getFeed(request, feedClass, ifModifiedSince);
}
/**
* Returns the Feed associated with a particular feed URL if the entity tag
* associated with it has changed.
*
* @param feedUrl the URL associated with a feed. This URL can include GData
* query parameters.
* @param feedClass the class used to represent a service Feed.
* @param etag used to provide an entity tag that indicates the feed should be
* returned only if the entity tag of the current representation is
* different from the provided value. A value of {@code null} indicates
* unconditional return.
* @throws IOException error sending request or reading the feed.
* @throws NotModifiedException if the feed resource entity tag matches the
* provided value.
* @throws com.google.gdata.util.ParseException error parsing the returned
* feed data.
* @throws com.google.gdata.util.ResourceNotFoundException invalid feed URL.
* @throws ServiceException system error retrieving feed.
*/
@SuppressWarnings("unchecked")
public <F extends IFeed> F getFeed(URL feedUrl, Class<F> feedClass,
String etag) throws IOException, ServiceException {
GDataRequest request = createFeedRequest(feedUrl);
return getFeed(request, feedClass, etag);
}