summaryrefslogtreecommitdiff
path: root/chromium/third_party/cacheinvalidation/src/java
diff options
context:
space:
mode:
authorAndras Becsi <andras.becsi@digia.com>2013-12-11 21:33:03 +0100
committerAndras Becsi <andras.becsi@digia.com>2013-12-13 12:34:07 +0100
commitf2a33ff9cbc6d19943f1c7fbddd1f23d23975577 (patch)
tree0586a32aa390ade8557dfd6b4897f43a07449578 /chromium/third_party/cacheinvalidation/src/java
parent5362912cdb5eea702b68ebe23702468d17c3017a (diff)
downloadqtwebengine-chromium-f2a33ff9cbc6d19943f1c7fbddd1f23d23975577.tar.gz
Update Chromium to branch 1650 (31.0.1650.63)
Change-Id: I57d8c832eaec1eb2364e0a8e7352a6dd354db99f Reviewed-by: Jocelyn Turcotte <jocelyn.turcotte@digia.com>
Diffstat (limited to 'chromium/third_party/cacheinvalidation/src/java')
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/COPYING202
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/common/base/Receiver.java38
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/BuildConstants.java37
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/ClientProtocolAccessor.java1796
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/CommonInvalidationConstants2.java82
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/CommonProtoStrings2.java650
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/CommonProtos2.java436
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/DigestFunction.java36
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/ObjectIdDigestUtils.java103
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/ProtoValidator.java296
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/TiclMessageValidator2.java480
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/TrickleState.java39
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/examples/android2/ExampleListener.java308
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/examples/android2/MainActivity.java132
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationClient.java108
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationClientConfig.java43
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationClientFactory.java49
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationClientTestHelper.java47
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationListener.java177
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/SystemResources.java211
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/SystemResourcesBuilder.java174
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/AndroidClientFactory.java147
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/AndroidInvalidationClient.java44
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/AndroidInvalidationClientImpl.java341
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/AndroidInvalidationListener.java220
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/AndroidClientException.java40
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/AndroidLogger.java230
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/Event.java218
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/InvalidationBinder.java58
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/InvalidationService.aidl62
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ListenerBinder.java41
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ListenerService.aidl59
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/Message.java185
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ParcelableErrorInfo.java92
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ParcelableInvalidation.java110
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ParcelableObjectId.java88
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/Request.java184
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/Response.java130
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ServiceBinder.java280
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android2/AndroidClientFactory.java53
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android2/AndroidManifest.xml58
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListener.java598
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerIntents.java220
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerManifest.xml12
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerProtos.java137
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerState.java300
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/MultiplexingGcmListener.java362
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/AckHandle.java68
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/ApplicationClientId.java77
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/BytesFormatter.java101
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/Callback.java33
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/ErrorContext.java38
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/ErrorInfo.java93
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/Invalidation.java136
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/ObjectId.java85
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/SimplePair.java115
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/Status.java122
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/testing/android/InvalidationTest.aidl54
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/testing/android/InvalidationTestListener.java192
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/testing/android/InvalidationTestService.java414
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/BasicSystemResources.java125
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/CheckingInvalidationListener.java178
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/DigestStore.java81
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/InvalidationClientCore.java1563
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/InvalidationClientImpl.java163
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/MemoryStorageImpl.java146
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/PersistenceUtils.java78
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/ProtoConverter.java116
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/ProtoWrapper.java94
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/ProtocolHandler.java712
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/RecurringTask.java250
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/RegistrationManager.java303
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/RunState.java95
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/SafeStorage.java111
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/SimpleRegistrationStore.java132
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/Statistics.java353
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/TestableInvalidationClient.java141
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/TestableNetworkChannel.java33
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/TiclExponentialBackoffDelayGenerator.java60
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AbstractInvalidationService.java185
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidC2DMConstants.java48
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidChannel.java462
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidChannelBase.java138
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidClientManager.java242
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidClientProxy.java387
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidHttpConstants.java48
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidInvalidationService.java597
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidResourcesFactory.java116
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidStorage.java331
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/BaseC2DMReceiver.java125
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMBroadcastReceiver.java40
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMManager.java653
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMObserver.java207
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMSettings.java254
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMTestUtil.java45
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMessaging.java164
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/WakeLockManager.java218
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidClock.java37
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidIntentProtocolValidator.java306
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInternalScheduler.java199
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInvalidationClientImpl.java260
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInvalidationClientStub.java116
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInvalidationListenerIntentMapper.java160
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInvalidationListenerStub.java83
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidManifest.xml15
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidServiceAccessor.java1217
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidStorage.java164
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidStrings.java390
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidTiclManifest.java108
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/ProtocolIntents.java288
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/ResourcesFactory.java138
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/TiclService.java371
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/TiclStateManager.java264
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidChannelConstants.java134
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidChannelPreferences.java111
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidMessageReceiverService.java135
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidMessageSenderService.java374
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidNetworkChannel.java62
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/BaseLogger.java63
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Box.java70
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Bytes.java332
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/ExponentialBackoffDelayGenerator.java109
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Formatter.java72
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/InternalBase.java97
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/LazyString.java50
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Marshallable.java27
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/NamedRunnable.java45
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Smearer.java64
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/TextBuilder.java160
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/TypedUtil.java74
-rw-r--r--chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/UtilFormatter.java37
131 files changed, 0 insertions, 26367 deletions
diff --git a/chromium/third_party/cacheinvalidation/src/java/COPYING b/chromium/third_party/cacheinvalidation/src/java/COPYING
deleted file mode 100644
index d6456956733..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/COPYING
+++ /dev/null
@@ -1,202 +0,0 @@
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- 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.
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/common/base/Receiver.java b/chromium/third_party/cacheinvalidation/src/java/com/google/common/base/Receiver.java
deleted file mode 100644
index 536e8c75b05..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/common/base/Receiver.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2008 The Guava Authors
- *
- * 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.common.base;
-
-/**
- * General purpose receiver of objects of a single type.
- *
- * <p>This interface is complementary to the {@code Supplier} interface.
- * Semantically, it can be used as an Output Stream, Sink, Closure or something
- * else entirely. No guarantees are implied by this interface.
- *
- * @param <T> type of received object
- *
- * @author micapolos@google.com (Michal Pociecha-Los)
- */
-public interface Receiver<T> {
-
- /**
- * Accepts received object.
- *
- * @param object received object
- */
- void accept(T object);
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/BuildConstants.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/BuildConstants.java
deleted file mode 100644
index c206a510471..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/BuildConstants.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright 2011 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.
- */
-/*
- * Copyright 2013 Google Inc. All Rights Reserved.
- *
- * 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.ipc.invalidation.common;
-
-/** Build constant definitions. */
-class BuildConstants {
- static final int BUILD_DATESTAMP = 20130604;
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/ClientProtocolAccessor.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/ClientProtocolAccessor.java
deleted file mode 100644
index 976e22736eb..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/ClientProtocolAccessor.java
+++ /dev/null
@@ -1,1796 +0,0 @@
-/*
- * Copyright 2011 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.
- */
-// GENERATED CODE. DO NOT EDIT. (But isn't it pretty?)
-package com.google.ipc.invalidation.common;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.common.ProtoValidator.Accessor;
-
-import com.google.ipc.invalidation.common.ProtoValidator.Descriptor;
-
-import com.google.protobuf.MessageLite;
-
-import com.google.protos.ipc.invalidation.ClientProtocol.ApplicationClientIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientConfigP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientHeader;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientToServerMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientVersion;
-import com.google.protos.ipc.invalidation.ClientProtocol.ConfigChangeMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.ErrorMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InfoMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InfoRequestMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InitializeMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InvalidationMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InvalidationP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ObjectIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.PropertyRecord;
-import com.google.protos.ipc.invalidation.ClientProtocol.ProtocolHandlerConfigP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ProtocolVersion;
-import com.google.protos.ipc.invalidation.ClientProtocol.RateLimitP;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationP;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationStatus;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationStatusMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSubtree;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSummary;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSyncMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSyncRequestMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.ServerHeader;
-import com.google.protos.ipc.invalidation.ClientProtocol.ServerToClientMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.StatusP;
-import com.google.protos.ipc.invalidation.ClientProtocol.TokenControlMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.Version;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Set;
-
-/** Class providing access to fields of protocol buffers in a generic way without using Java reflection. */
-public class ClientProtocolAccessor {
- /** Class to access fields in {@link ApplicationClientIdP} protos. */
- public static class ApplicationClientIdPAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "client_type",
- "client_name"
- ));
-
- public static final Descriptor CLIENT_TYPE = new Descriptor("client_type");
- public static final Descriptor CLIENT_NAME = new Descriptor("client_name");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ApplicationClientIdP message = (ApplicationClientIdP) rawMessage;
- if (field == CLIENT_TYPE) {
- return message.hasClientType();
- }
- if (field == CLIENT_NAME) {
- return message.hasClientName();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ApplicationClientIdP message = (ApplicationClientIdP) rawMessage;
- if (field == CLIENT_TYPE) {
- return message.getClientType();
- }
- if (field == CLIENT_NAME) {
- return message.getClientName();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ApplicationClientIdPAccessor APPLICATION_CLIENT_ID_P_ACCESSOR = new ApplicationClientIdPAccessor();
-
- /** Class to access fields in {@link ClientConfigP} protos. */
- public static class ClientConfigPAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "version",
- "network_timeout_delay_ms",
- "write_retry_delay_ms",
- "heartbeat_interval_ms",
- "perf_counter_delay_ms",
- "max_exponential_backoff_factor",
- "smear_percent",
- "is_transient",
- "initial_persistent_heartbeat_delay_ms",
- "protocol_handler_config",
- "channel_supports_offline_delivery",
- "offline_heartbeat_threshold_ms",
- "allow_suppression"
- ));
-
- public static final Descriptor VERSION = new Descriptor("version");
- public static final Descriptor NETWORK_TIMEOUT_DELAY_MS = new Descriptor("network_timeout_delay_ms");
- public static final Descriptor WRITE_RETRY_DELAY_MS = new Descriptor("write_retry_delay_ms");
- public static final Descriptor HEARTBEAT_INTERVAL_MS = new Descriptor("heartbeat_interval_ms");
- public static final Descriptor PERF_COUNTER_DELAY_MS = new Descriptor("perf_counter_delay_ms");
- public static final Descriptor MAX_EXPONENTIAL_BACKOFF_FACTOR = new Descriptor("max_exponential_backoff_factor");
- public static final Descriptor SMEAR_PERCENT = new Descriptor("smear_percent");
- public static final Descriptor IS_TRANSIENT = new Descriptor("is_transient");
- public static final Descriptor INITIAL_PERSISTENT_HEARTBEAT_DELAY_MS = new Descriptor("initial_persistent_heartbeat_delay_ms");
- public static final Descriptor PROTOCOL_HANDLER_CONFIG = new Descriptor("protocol_handler_config");
- public static final Descriptor CHANNEL_SUPPORTS_OFFLINE_DELIVERY = new Descriptor("channel_supports_offline_delivery");
- public static final Descriptor OFFLINE_HEARTBEAT_THRESHOLD_MS = new Descriptor("offline_heartbeat_threshold_ms");
- public static final Descriptor ALLOW_SUPPRESSION = new Descriptor("allow_suppression");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ClientConfigP message = (ClientConfigP) rawMessage;
- if (field == VERSION) {
- return message.hasVersion();
- }
- if (field == NETWORK_TIMEOUT_DELAY_MS) {
- return message.hasNetworkTimeoutDelayMs();
- }
- if (field == WRITE_RETRY_DELAY_MS) {
- return message.hasWriteRetryDelayMs();
- }
- if (field == HEARTBEAT_INTERVAL_MS) {
- return message.hasHeartbeatIntervalMs();
- }
- if (field == PERF_COUNTER_DELAY_MS) {
- return message.hasPerfCounterDelayMs();
- }
- if (field == MAX_EXPONENTIAL_BACKOFF_FACTOR) {
- return message.hasMaxExponentialBackoffFactor();
- }
- if (field == SMEAR_PERCENT) {
- return message.hasSmearPercent();
- }
- if (field == IS_TRANSIENT) {
- return message.hasIsTransient();
- }
- if (field == INITIAL_PERSISTENT_HEARTBEAT_DELAY_MS) {
- return message.hasInitialPersistentHeartbeatDelayMs();
- }
- if (field == PROTOCOL_HANDLER_CONFIG) {
- return message.hasProtocolHandlerConfig();
- }
- if (field == CHANNEL_SUPPORTS_OFFLINE_DELIVERY) {
- return message.hasChannelSupportsOfflineDelivery();
- }
- if (field == OFFLINE_HEARTBEAT_THRESHOLD_MS) {
- return message.hasOfflineHeartbeatThresholdMs();
- }
- if (field == ALLOW_SUPPRESSION) {
- return message.hasAllowSuppression();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ClientConfigP message = (ClientConfigP) rawMessage;
- if (field == VERSION) {
- return message.getVersion();
- }
- if (field == NETWORK_TIMEOUT_DELAY_MS) {
- return message.getNetworkTimeoutDelayMs();
- }
- if (field == WRITE_RETRY_DELAY_MS) {
- return message.getWriteRetryDelayMs();
- }
- if (field == HEARTBEAT_INTERVAL_MS) {
- return message.getHeartbeatIntervalMs();
- }
- if (field == PERF_COUNTER_DELAY_MS) {
- return message.getPerfCounterDelayMs();
- }
- if (field == MAX_EXPONENTIAL_BACKOFF_FACTOR) {
- return message.getMaxExponentialBackoffFactor();
- }
- if (field == SMEAR_PERCENT) {
- return message.getSmearPercent();
- }
- if (field == IS_TRANSIENT) {
- return message.getIsTransient();
- }
- if (field == INITIAL_PERSISTENT_HEARTBEAT_DELAY_MS) {
- return message.getInitialPersistentHeartbeatDelayMs();
- }
- if (field == PROTOCOL_HANDLER_CONFIG) {
- return message.getProtocolHandlerConfig();
- }
- if (field == CHANNEL_SUPPORTS_OFFLINE_DELIVERY) {
- return message.getChannelSupportsOfflineDelivery();
- }
- if (field == OFFLINE_HEARTBEAT_THRESHOLD_MS) {
- return message.getOfflineHeartbeatThresholdMs();
- }
- if (field == ALLOW_SUPPRESSION) {
- return message.getAllowSuppression();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ClientConfigPAccessor CLIENT_CONFIG_P_ACCESSOR = new ClientConfigPAccessor();
-
- /** Class to access fields in {@link ClientHeader} protos. */
- public static class ClientHeaderAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "protocol_version",
- "client_token",
- "registration_summary",
- "client_time_ms",
- "max_known_server_time_ms",
- "message_id",
- "client_type"
- ));
-
- public static final Descriptor PROTOCOL_VERSION = new Descriptor("protocol_version");
- public static final Descriptor CLIENT_TOKEN = new Descriptor("client_token");
- public static final Descriptor REGISTRATION_SUMMARY = new Descriptor("registration_summary");
- public static final Descriptor CLIENT_TIME_MS = new Descriptor("client_time_ms");
- public static final Descriptor MAX_KNOWN_SERVER_TIME_MS = new Descriptor("max_known_server_time_ms");
- public static final Descriptor MESSAGE_ID = new Descriptor("message_id");
- public static final Descriptor CLIENT_TYPE = new Descriptor("client_type");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ClientHeader message = (ClientHeader) rawMessage;
- if (field == PROTOCOL_VERSION) {
- return message.hasProtocolVersion();
- }
- if (field == CLIENT_TOKEN) {
- return message.hasClientToken();
- }
- if (field == REGISTRATION_SUMMARY) {
- return message.hasRegistrationSummary();
- }
- if (field == CLIENT_TIME_MS) {
- return message.hasClientTimeMs();
- }
- if (field == MAX_KNOWN_SERVER_TIME_MS) {
- return message.hasMaxKnownServerTimeMs();
- }
- if (field == MESSAGE_ID) {
- return message.hasMessageId();
- }
- if (field == CLIENT_TYPE) {
- return message.hasClientType();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ClientHeader message = (ClientHeader) rawMessage;
- if (field == PROTOCOL_VERSION) {
- return message.getProtocolVersion();
- }
- if (field == CLIENT_TOKEN) {
- return message.getClientToken();
- }
- if (field == REGISTRATION_SUMMARY) {
- return message.getRegistrationSummary();
- }
- if (field == CLIENT_TIME_MS) {
- return message.getClientTimeMs();
- }
- if (field == MAX_KNOWN_SERVER_TIME_MS) {
- return message.getMaxKnownServerTimeMs();
- }
- if (field == MESSAGE_ID) {
- return message.getMessageId();
- }
- if (field == CLIENT_TYPE) {
- return message.getClientType();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ClientHeaderAccessor CLIENT_HEADER_ACCESSOR = new ClientHeaderAccessor();
-
- /** Class to access fields in {@link ClientToServerMessage} protos. */
- public static class ClientToServerMessageAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "header",
- "initialize_message",
- "registration_message",
- "registration_sync_message",
- "invalidation_ack_message",
- "info_message"
- ));
-
- public static final Descriptor HEADER = new Descriptor("header");
- public static final Descriptor INITIALIZE_MESSAGE = new Descriptor("initialize_message");
- public static final Descriptor REGISTRATION_MESSAGE = new Descriptor("registration_message");
- public static final Descriptor REGISTRATION_SYNC_MESSAGE = new Descriptor("registration_sync_message");
- public static final Descriptor INVALIDATION_ACK_MESSAGE = new Descriptor("invalidation_ack_message");
- public static final Descriptor INFO_MESSAGE = new Descriptor("info_message");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ClientToServerMessage message = (ClientToServerMessage) rawMessage;
- if (field == HEADER) {
- return message.hasHeader();
- }
- if (field == INITIALIZE_MESSAGE) {
- return message.hasInitializeMessage();
- }
- if (field == REGISTRATION_MESSAGE) {
- return message.hasRegistrationMessage();
- }
- if (field == REGISTRATION_SYNC_MESSAGE) {
- return message.hasRegistrationSyncMessage();
- }
- if (field == INVALIDATION_ACK_MESSAGE) {
- return message.hasInvalidationAckMessage();
- }
- if (field == INFO_MESSAGE) {
- return message.hasInfoMessage();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ClientToServerMessage message = (ClientToServerMessage) rawMessage;
- if (field == HEADER) {
- return message.getHeader();
- }
- if (field == INITIALIZE_MESSAGE) {
- return message.getInitializeMessage();
- }
- if (field == REGISTRATION_MESSAGE) {
- return message.getRegistrationMessage();
- }
- if (field == REGISTRATION_SYNC_MESSAGE) {
- return message.getRegistrationSyncMessage();
- }
- if (field == INVALIDATION_ACK_MESSAGE) {
- return message.getInvalidationAckMessage();
- }
- if (field == INFO_MESSAGE) {
- return message.getInfoMessage();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ClientToServerMessageAccessor CLIENT_TO_SERVER_MESSAGE_ACCESSOR = new ClientToServerMessageAccessor();
-
- /** Class to access fields in {@link ClientVersion} protos. */
- public static class ClientVersionAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "version",
- "platform",
- "language",
- "application_info"
- ));
-
- public static final Descriptor VERSION = new Descriptor("version");
- public static final Descriptor PLATFORM = new Descriptor("platform");
- public static final Descriptor LANGUAGE = new Descriptor("language");
- public static final Descriptor APPLICATION_INFO = new Descriptor("application_info");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ClientVersion message = (ClientVersion) rawMessage;
- if (field == VERSION) {
- return message.hasVersion();
- }
- if (field == PLATFORM) {
- return message.hasPlatform();
- }
- if (field == LANGUAGE) {
- return message.hasLanguage();
- }
- if (field == APPLICATION_INFO) {
- return message.hasApplicationInfo();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ClientVersion message = (ClientVersion) rawMessage;
- if (field == VERSION) {
- return message.getVersion();
- }
- if (field == PLATFORM) {
- return message.getPlatform();
- }
- if (field == LANGUAGE) {
- return message.getLanguage();
- }
- if (field == APPLICATION_INFO) {
- return message.getApplicationInfo();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ClientVersionAccessor CLIENT_VERSION_ACCESSOR = new ClientVersionAccessor();
-
- /** Class to access fields in {@link ConfigChangeMessage} protos. */
- public static class ConfigChangeMessageAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "next_message_delay_ms"
- ));
-
- public static final Descriptor NEXT_MESSAGE_DELAY_MS = new Descriptor("next_message_delay_ms");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ConfigChangeMessage message = (ConfigChangeMessage) rawMessage;
- if (field == NEXT_MESSAGE_DELAY_MS) {
- return message.hasNextMessageDelayMs();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ConfigChangeMessage message = (ConfigChangeMessage) rawMessage;
- if (field == NEXT_MESSAGE_DELAY_MS) {
- return message.getNextMessageDelayMs();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ConfigChangeMessageAccessor CONFIG_CHANGE_MESSAGE_ACCESSOR = new ConfigChangeMessageAccessor();
-
- /** Class to access fields in {@link ErrorMessage} protos. */
- public static class ErrorMessageAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "code",
- "description"
- ));
-
- public static final Descriptor CODE = new Descriptor("code");
- public static final Descriptor DESCRIPTION = new Descriptor("description");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ErrorMessage message = (ErrorMessage) rawMessage;
- if (field == CODE) {
- return message.hasCode();
- }
- if (field == DESCRIPTION) {
- return message.hasDescription();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ErrorMessage message = (ErrorMessage) rawMessage;
- if (field == CODE) {
- return message.getCode();
- }
- if (field == DESCRIPTION) {
- return message.getDescription();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ErrorMessageAccessor ERROR_MESSAGE_ACCESSOR = new ErrorMessageAccessor();
-
- /** Class to access fields in {@link InfoMessage} protos. */
- public static class InfoMessageAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "client_version",
- "config_parameter",
- "performance_counter",
- "server_registration_summary_requested",
- "client_config"
- ));
-
- public static final Descriptor CLIENT_VERSION = new Descriptor("client_version");
- public static final Descriptor CONFIG_PARAMETER = new Descriptor("config_parameter");
- public static final Descriptor PERFORMANCE_COUNTER = new Descriptor("performance_counter");
- public static final Descriptor SERVER_REGISTRATION_SUMMARY_REQUESTED = new Descriptor("server_registration_summary_requested");
- public static final Descriptor CLIENT_CONFIG = new Descriptor("client_config");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- InfoMessage message = (InfoMessage) rawMessage;
- if (field == CLIENT_VERSION) {
- return message.hasClientVersion();
- }
- if (field == CONFIG_PARAMETER) {
- return message.getConfigParameterCount() > 0;
- }
- if (field == PERFORMANCE_COUNTER) {
- return message.getPerformanceCounterCount() > 0;
- }
- if (field == SERVER_REGISTRATION_SUMMARY_REQUESTED) {
- return message.hasServerRegistrationSummaryRequested();
- }
- if (field == CLIENT_CONFIG) {
- return message.hasClientConfig();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- InfoMessage message = (InfoMessage) rawMessage;
- if (field == CLIENT_VERSION) {
- return message.getClientVersion();
- }
- if (field == CONFIG_PARAMETER) {
- return message.getConfigParameterList();
- }
- if (field == PERFORMANCE_COUNTER) {
- return message.getPerformanceCounterList();
- }
- if (field == SERVER_REGISTRATION_SUMMARY_REQUESTED) {
- return message.getServerRegistrationSummaryRequested();
- }
- if (field == CLIENT_CONFIG) {
- return message.getClientConfig();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final InfoMessageAccessor INFO_MESSAGE_ACCESSOR = new InfoMessageAccessor();
-
- /** Class to access fields in {@link InfoRequestMessage} protos. */
- public static class InfoRequestMessageAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "info_type"
- ));
-
- public static final Descriptor INFO_TYPE = new Descriptor("info_type");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- InfoRequestMessage message = (InfoRequestMessage) rawMessage;
- if (field == INFO_TYPE) {
- return message.getInfoTypeCount() > 0;
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- InfoRequestMessage message = (InfoRequestMessage) rawMessage;
- if (field == INFO_TYPE) {
- return message.getInfoTypeList();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final InfoRequestMessageAccessor INFO_REQUEST_MESSAGE_ACCESSOR = new InfoRequestMessageAccessor();
-
- /** Class to access fields in {@link InitializeMessage} protos. */
- public static class InitializeMessageAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "client_type",
- "nonce",
- "application_client_id",
- "digest_serialization_type"
- ));
-
- public static final Descriptor CLIENT_TYPE = new Descriptor("client_type");
- public static final Descriptor NONCE = new Descriptor("nonce");
- public static final Descriptor APPLICATION_CLIENT_ID = new Descriptor("application_client_id");
- public static final Descriptor DIGEST_SERIALIZATION_TYPE = new Descriptor("digest_serialization_type");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- InitializeMessage message = (InitializeMessage) rawMessage;
- if (field == CLIENT_TYPE) {
- return message.hasClientType();
- }
- if (field == NONCE) {
- return message.hasNonce();
- }
- if (field == APPLICATION_CLIENT_ID) {
- return message.hasApplicationClientId();
- }
- if (field == DIGEST_SERIALIZATION_TYPE) {
- return message.hasDigestSerializationType();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- InitializeMessage message = (InitializeMessage) rawMessage;
- if (field == CLIENT_TYPE) {
- return message.getClientType();
- }
- if (field == NONCE) {
- return message.getNonce();
- }
- if (field == APPLICATION_CLIENT_ID) {
- return message.getApplicationClientId();
- }
- if (field == DIGEST_SERIALIZATION_TYPE) {
- return message.getDigestSerializationType();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final InitializeMessageAccessor INITIALIZE_MESSAGE_ACCESSOR = new InitializeMessageAccessor();
-
- /** Class to access fields in {@link InvalidationMessage} protos. */
- public static class InvalidationMessageAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "invalidation"
- ));
-
- public static final Descriptor INVALIDATION = new Descriptor("invalidation");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- InvalidationMessage message = (InvalidationMessage) rawMessage;
- if (field == INVALIDATION) {
- return message.getInvalidationCount() > 0;
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- InvalidationMessage message = (InvalidationMessage) rawMessage;
- if (field == INVALIDATION) {
- return message.getInvalidationList();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final InvalidationMessageAccessor INVALIDATION_MESSAGE_ACCESSOR = new InvalidationMessageAccessor();
-
- /** Class to access fields in {@link InvalidationP} protos. */
- public static class InvalidationPAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "object_id",
- "is_known_version",
- "version",
- "is_trickle_restart",
- "payload",
- "bridge_arrival_time_ms_deprecated"
- ));
-
- public static final Descriptor OBJECT_ID = new Descriptor("object_id");
- public static final Descriptor IS_KNOWN_VERSION = new Descriptor("is_known_version");
- public static final Descriptor VERSION = new Descriptor("version");
- public static final Descriptor IS_TRICKLE_RESTART = new Descriptor("is_trickle_restart");
- public static final Descriptor PAYLOAD = new Descriptor("payload");
- public static final Descriptor BRIDGE_ARRIVAL_TIME_MS_DEPRECATED = new Descriptor("bridge_arrival_time_ms_deprecated");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings({ "deprecation", "unchecked" })
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- InvalidationP message = (InvalidationP) rawMessage;
- if (field == OBJECT_ID) {
- return message.hasObjectId();
- }
- if (field == IS_KNOWN_VERSION) {
- return message.hasIsKnownVersion();
- }
- if (field == VERSION) {
- return message.hasVersion();
- }
- if (field == IS_TRICKLE_RESTART) {
- return message.hasIsTrickleRestart();
- }
- if (field == PAYLOAD) {
- return message.hasPayload();
- }
- if (field == BRIDGE_ARRIVAL_TIME_MS_DEPRECATED) {
- return message.hasBridgeArrivalTimeMsDeprecated();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings({ "deprecation", "unchecked" })
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- InvalidationP message = (InvalidationP) rawMessage;
- if (field == OBJECT_ID) {
- return message.getObjectId();
- }
- if (field == IS_KNOWN_VERSION) {
- return message.getIsKnownVersion();
- }
- if (field == VERSION) {
- return message.getVersion();
- }
- if (field == IS_TRICKLE_RESTART) {
- return message.getIsTrickleRestart();
- }
- if (field == PAYLOAD) {
- return message.getPayload();
- }
- if (field == BRIDGE_ARRIVAL_TIME_MS_DEPRECATED) {
- return message.getBridgeArrivalTimeMsDeprecated();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final InvalidationPAccessor INVALIDATION_P_ACCESSOR = new InvalidationPAccessor();
-
- /** Class to access fields in {@link ObjectIdP} protos. */
- public static class ObjectIdPAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "source",
- "name"
- ));
-
- public static final Descriptor SOURCE = new Descriptor("source");
- public static final Descriptor NAME = new Descriptor("name");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ObjectIdP message = (ObjectIdP) rawMessage;
- if (field == SOURCE) {
- return message.hasSource();
- }
- if (field == NAME) {
- return message.hasName();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ObjectIdP message = (ObjectIdP) rawMessage;
- if (field == SOURCE) {
- return message.getSource();
- }
- if (field == NAME) {
- return message.getName();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ObjectIdPAccessor OBJECT_ID_P_ACCESSOR = new ObjectIdPAccessor();
-
- /** Class to access fields in {@link PropertyRecord} protos. */
- public static class PropertyRecordAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "name",
- "value"
- ));
-
- public static final Descriptor NAME = new Descriptor("name");
- public static final Descriptor VALUE = new Descriptor("value");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- PropertyRecord message = (PropertyRecord) rawMessage;
- if (field == NAME) {
- return message.hasName();
- }
- if (field == VALUE) {
- return message.hasValue();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- PropertyRecord message = (PropertyRecord) rawMessage;
- if (field == NAME) {
- return message.getName();
- }
- if (field == VALUE) {
- return message.getValue();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final PropertyRecordAccessor PROPERTY_RECORD_ACCESSOR = new PropertyRecordAccessor();
-
- /** Class to access fields in {@link ProtocolHandlerConfigP} protos. */
- public static class ProtocolHandlerConfigPAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "batching_delay_ms",
- "rate_limit"
- ));
-
- public static final Descriptor BATCHING_DELAY_MS = new Descriptor("batching_delay_ms");
- public static final Descriptor RATE_LIMIT = new Descriptor("rate_limit");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ProtocolHandlerConfigP message = (ProtocolHandlerConfigP) rawMessage;
- if (field == BATCHING_DELAY_MS) {
- return message.hasBatchingDelayMs();
- }
- if (field == RATE_LIMIT) {
- return message.getRateLimitCount() > 0;
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ProtocolHandlerConfigP message = (ProtocolHandlerConfigP) rawMessage;
- if (field == BATCHING_DELAY_MS) {
- return message.getBatchingDelayMs();
- }
- if (field == RATE_LIMIT) {
- return message.getRateLimitList();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ProtocolHandlerConfigPAccessor PROTOCOL_HANDLER_CONFIG_P_ACCESSOR = new ProtocolHandlerConfigPAccessor();
-
- /** Class to access fields in {@link ProtocolVersion} protos. */
- public static class ProtocolVersionAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "version"
- ));
-
- public static final Descriptor VERSION = new Descriptor("version");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ProtocolVersion message = (ProtocolVersion) rawMessage;
- if (field == VERSION) {
- return message.hasVersion();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ProtocolVersion message = (ProtocolVersion) rawMessage;
- if (field == VERSION) {
- return message.getVersion();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ProtocolVersionAccessor PROTOCOL_VERSION_ACCESSOR = new ProtocolVersionAccessor();
-
- /** Class to access fields in {@link RateLimitP} protos. */
- public static class RateLimitPAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "window_ms",
- "count"
- ));
-
- public static final Descriptor WINDOW_MS = new Descriptor("window_ms");
- public static final Descriptor COUNT = new Descriptor("count");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RateLimitP message = (RateLimitP) rawMessage;
- if (field == WINDOW_MS) {
- return message.hasWindowMs();
- }
- if (field == COUNT) {
- return message.hasCount();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RateLimitP message = (RateLimitP) rawMessage;
- if (field == WINDOW_MS) {
- return message.getWindowMs();
- }
- if (field == COUNT) {
- return message.getCount();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final RateLimitPAccessor RATE_LIMIT_P_ACCESSOR = new RateLimitPAccessor();
-
- /** Class to access fields in {@link RegistrationMessage} protos. */
- public static class RegistrationMessageAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "registration"
- ));
-
- public static final Descriptor REGISTRATION = new Descriptor("registration");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationMessage message = (RegistrationMessage) rawMessage;
- if (field == REGISTRATION) {
- return message.getRegistrationCount() > 0;
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationMessage message = (RegistrationMessage) rawMessage;
- if (field == REGISTRATION) {
- return message.getRegistrationList();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final RegistrationMessageAccessor REGISTRATION_MESSAGE_ACCESSOR = new RegistrationMessageAccessor();
-
- /** Class to access fields in {@link RegistrationP} protos. */
- public static class RegistrationPAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "object_id",
- "op_type"
- ));
-
- public static final Descriptor OBJECT_ID = new Descriptor("object_id");
- public static final Descriptor OP_TYPE = new Descriptor("op_type");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationP message = (RegistrationP) rawMessage;
- if (field == OBJECT_ID) {
- return message.hasObjectId();
- }
- if (field == OP_TYPE) {
- return message.hasOpType();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationP message = (RegistrationP) rawMessage;
- if (field == OBJECT_ID) {
- return message.getObjectId();
- }
- if (field == OP_TYPE) {
- return message.getOpType();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final RegistrationPAccessor REGISTRATION_P_ACCESSOR = new RegistrationPAccessor();
-
- /** Class to access fields in {@link RegistrationStatus} protos. */
- public static class RegistrationStatusAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "registration",
- "status"
- ));
-
- public static final Descriptor REGISTRATION = new Descriptor("registration");
- public static final Descriptor STATUS = new Descriptor("status");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationStatus message = (RegistrationStatus) rawMessage;
- if (field == REGISTRATION) {
- return message.hasRegistration();
- }
- if (field == STATUS) {
- return message.hasStatus();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationStatus message = (RegistrationStatus) rawMessage;
- if (field == REGISTRATION) {
- return message.getRegistration();
- }
- if (field == STATUS) {
- return message.getStatus();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final RegistrationStatusAccessor REGISTRATION_STATUS_ACCESSOR = new RegistrationStatusAccessor();
-
- /** Class to access fields in {@link RegistrationStatusMessage} protos. */
- public static class RegistrationStatusMessageAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "registration_status"
- ));
-
- public static final Descriptor REGISTRATION_STATUS = new Descriptor("registration_status");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationStatusMessage message = (RegistrationStatusMessage) rawMessage;
- if (field == REGISTRATION_STATUS) {
- return message.getRegistrationStatusCount() > 0;
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationStatusMessage message = (RegistrationStatusMessage) rawMessage;
- if (field == REGISTRATION_STATUS) {
- return message.getRegistrationStatusList();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final RegistrationStatusMessageAccessor REGISTRATION_STATUS_MESSAGE_ACCESSOR = new RegistrationStatusMessageAccessor();
-
- /** Class to access fields in {@link RegistrationSubtree} protos. */
- public static class RegistrationSubtreeAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "registered_object"
- ));
-
- public static final Descriptor REGISTERED_OBJECT = new Descriptor("registered_object");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationSubtree message = (RegistrationSubtree) rawMessage;
- if (field == REGISTERED_OBJECT) {
- return message.getRegisteredObjectCount() > 0;
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationSubtree message = (RegistrationSubtree) rawMessage;
- if (field == REGISTERED_OBJECT) {
- return message.getRegisteredObjectList();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final RegistrationSubtreeAccessor REGISTRATION_SUBTREE_ACCESSOR = new RegistrationSubtreeAccessor();
-
- /** Class to access fields in {@link RegistrationSummary} protos. */
- public static class RegistrationSummaryAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "num_registrations",
- "registration_digest"
- ));
-
- public static final Descriptor NUM_REGISTRATIONS = new Descriptor("num_registrations");
- public static final Descriptor REGISTRATION_DIGEST = new Descriptor("registration_digest");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationSummary message = (RegistrationSummary) rawMessage;
- if (field == NUM_REGISTRATIONS) {
- return message.hasNumRegistrations();
- }
- if (field == REGISTRATION_DIGEST) {
- return message.hasRegistrationDigest();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationSummary message = (RegistrationSummary) rawMessage;
- if (field == NUM_REGISTRATIONS) {
- return message.getNumRegistrations();
- }
- if (field == REGISTRATION_DIGEST) {
- return message.getRegistrationDigest();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final RegistrationSummaryAccessor REGISTRATION_SUMMARY_ACCESSOR = new RegistrationSummaryAccessor();
-
- /** Class to access fields in {@link RegistrationSyncMessage} protos. */
- public static class RegistrationSyncMessageAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "subtree"
- ));
-
- public static final Descriptor SUBTREE = new Descriptor("subtree");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationSyncMessage message = (RegistrationSyncMessage) rawMessage;
- if (field == SUBTREE) {
- return message.getSubtreeCount() > 0;
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationSyncMessage message = (RegistrationSyncMessage) rawMessage;
- if (field == SUBTREE) {
- return message.getSubtreeList();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final RegistrationSyncMessageAccessor REGISTRATION_SYNC_MESSAGE_ACCESSOR = new RegistrationSyncMessageAccessor();
-
- /** Class to access fields in {@link RegistrationSyncRequestMessage} protos. */
- public static class RegistrationSyncRequestMessageAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- ));
-
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationSyncRequestMessage message = (RegistrationSyncRequestMessage) rawMessage;
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationSyncRequestMessage message = (RegistrationSyncRequestMessage) rawMessage;
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final RegistrationSyncRequestMessageAccessor REGISTRATION_SYNC_REQUEST_MESSAGE_ACCESSOR = new RegistrationSyncRequestMessageAccessor();
-
- /** Class to access fields in {@link ServerHeader} protos. */
- public static class ServerHeaderAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "protocol_version",
- "client_token",
- "registration_summary",
- "server_time_ms",
- "message_id"
- ));
-
- public static final Descriptor PROTOCOL_VERSION = new Descriptor("protocol_version");
- public static final Descriptor CLIENT_TOKEN = new Descriptor("client_token");
- public static final Descriptor REGISTRATION_SUMMARY = new Descriptor("registration_summary");
- public static final Descriptor SERVER_TIME_MS = new Descriptor("server_time_ms");
- public static final Descriptor MESSAGE_ID = new Descriptor("message_id");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ServerHeader message = (ServerHeader) rawMessage;
- if (field == PROTOCOL_VERSION) {
- return message.hasProtocolVersion();
- }
- if (field == CLIENT_TOKEN) {
- return message.hasClientToken();
- }
- if (field == REGISTRATION_SUMMARY) {
- return message.hasRegistrationSummary();
- }
- if (field == SERVER_TIME_MS) {
- return message.hasServerTimeMs();
- }
- if (field == MESSAGE_ID) {
- return message.hasMessageId();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ServerHeader message = (ServerHeader) rawMessage;
- if (field == PROTOCOL_VERSION) {
- return message.getProtocolVersion();
- }
- if (field == CLIENT_TOKEN) {
- return message.getClientToken();
- }
- if (field == REGISTRATION_SUMMARY) {
- return message.getRegistrationSummary();
- }
- if (field == SERVER_TIME_MS) {
- return message.getServerTimeMs();
- }
- if (field == MESSAGE_ID) {
- return message.getMessageId();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ServerHeaderAccessor SERVER_HEADER_ACCESSOR = new ServerHeaderAccessor();
-
- /** Class to access fields in {@link ServerToClientMessage} protos. */
- public static class ServerToClientMessageAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "header",
- "token_control_message",
- "invalidation_message",
- "registration_status_message",
- "registration_sync_request_message",
- "config_change_message",
- "info_request_message",
- "error_message"
- ));
-
- public static final Descriptor HEADER = new Descriptor("header");
- public static final Descriptor TOKEN_CONTROL_MESSAGE = new Descriptor("token_control_message");
- public static final Descriptor INVALIDATION_MESSAGE = new Descriptor("invalidation_message");
- public static final Descriptor REGISTRATION_STATUS_MESSAGE = new Descriptor("registration_status_message");
- public static final Descriptor REGISTRATION_SYNC_REQUEST_MESSAGE = new Descriptor("registration_sync_request_message");
- public static final Descriptor CONFIG_CHANGE_MESSAGE = new Descriptor("config_change_message");
- public static final Descriptor INFO_REQUEST_MESSAGE = new Descriptor("info_request_message");
- public static final Descriptor ERROR_MESSAGE = new Descriptor("error_message");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ServerToClientMessage message = (ServerToClientMessage) rawMessage;
- if (field == HEADER) {
- return message.hasHeader();
- }
- if (field == TOKEN_CONTROL_MESSAGE) {
- return message.hasTokenControlMessage();
- }
- if (field == INVALIDATION_MESSAGE) {
- return message.hasInvalidationMessage();
- }
- if (field == REGISTRATION_STATUS_MESSAGE) {
- return message.hasRegistrationStatusMessage();
- }
- if (field == REGISTRATION_SYNC_REQUEST_MESSAGE) {
- return message.hasRegistrationSyncRequestMessage();
- }
- if (field == CONFIG_CHANGE_MESSAGE) {
- return message.hasConfigChangeMessage();
- }
- if (field == INFO_REQUEST_MESSAGE) {
- return message.hasInfoRequestMessage();
- }
- if (field == ERROR_MESSAGE) {
- return message.hasErrorMessage();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ServerToClientMessage message = (ServerToClientMessage) rawMessage;
- if (field == HEADER) {
- return message.getHeader();
- }
- if (field == TOKEN_CONTROL_MESSAGE) {
- return message.getTokenControlMessage();
- }
- if (field == INVALIDATION_MESSAGE) {
- return message.getInvalidationMessage();
- }
- if (field == REGISTRATION_STATUS_MESSAGE) {
- return message.getRegistrationStatusMessage();
- }
- if (field == REGISTRATION_SYNC_REQUEST_MESSAGE) {
- return message.getRegistrationSyncRequestMessage();
- }
- if (field == CONFIG_CHANGE_MESSAGE) {
- return message.getConfigChangeMessage();
- }
- if (field == INFO_REQUEST_MESSAGE) {
- return message.getInfoRequestMessage();
- }
- if (field == ERROR_MESSAGE) {
- return message.getErrorMessage();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ServerToClientMessageAccessor SERVER_TO_CLIENT_MESSAGE_ACCESSOR = new ServerToClientMessageAccessor();
-
- /** Class to access fields in {@link StatusP} protos. */
- public static class StatusPAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "code",
- "description"
- ));
-
- public static final Descriptor CODE = new Descriptor("code");
- public static final Descriptor DESCRIPTION = new Descriptor("description");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- StatusP message = (StatusP) rawMessage;
- if (field == CODE) {
- return message.hasCode();
- }
- if (field == DESCRIPTION) {
- return message.hasDescription();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- StatusP message = (StatusP) rawMessage;
- if (field == CODE) {
- return message.getCode();
- }
- if (field == DESCRIPTION) {
- return message.getDescription();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final StatusPAccessor STATUS_P_ACCESSOR = new StatusPAccessor();
-
- /** Class to access fields in {@link TokenControlMessage} protos. */
- public static class TokenControlMessageAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "new_token"
- ));
-
- public static final Descriptor NEW_TOKEN = new Descriptor("new_token");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- TokenControlMessage message = (TokenControlMessage) rawMessage;
- if (field == NEW_TOKEN) {
- return message.hasNewToken();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- TokenControlMessage message = (TokenControlMessage) rawMessage;
- if (field == NEW_TOKEN) {
- return message.getNewToken();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final TokenControlMessageAccessor TOKEN_CONTROL_MESSAGE_ACCESSOR = new TokenControlMessageAccessor();
-
- /** Class to access fields in {@link Version} protos. */
- public static class VersionAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "major_version",
- "minor_version"
- ));
-
- public static final Descriptor MAJOR_VERSION = new Descriptor("major_version");
- public static final Descriptor MINOR_VERSION = new Descriptor("minor_version");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- Version message = (Version) rawMessage;
- if (field == MAJOR_VERSION) {
- return message.hasMajorVersion();
- }
- if (field == MINOR_VERSION) {
- return message.hasMinorVersion();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- Version message = (Version) rawMessage;
- if (field == MAJOR_VERSION) {
- return message.getMajorVersion();
- }
- if (field == MINOR_VERSION) {
- return message.getMinorVersion();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final VersionAccessor VERSION_ACCESSOR = new VersionAccessor();
-
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/CommonInvalidationConstants2.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/CommonInvalidationConstants2.java
deleted file mode 100644
index 4cca6eca81a..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/CommonInvalidationConstants2.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.common;
-
-import com.google.protobuf.ByteString;
-import com.google.protos.ipc.invalidation.ClientProtocol.ObjectIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ProtocolVersion;
-import com.google.protos.ipc.invalidation.ClientProtocol.Version;
-import com.google.protos.ipc.invalidation.Types.ClientType;
-import com.google.protos.ipc.invalidation.Types.ObjectSource;
-
-/**
- * Various constants common to clients and servers used in version 2 of the Ticl.
- *
- */
-public class CommonInvalidationConstants2 {
-
- /** Major version of the client library. */
- public static final int CLIENT_MAJOR_VERSION = 3;
-
- /**
- * Minor version of the client library, defined to be equal to the datestamp of the build
- * (e.g. 20130401).
- */
- public static final int CLIENT_MINOR_VERSION = BuildConstants.BUILD_DATESTAMP;
-
- /** Major version of the protocol between the client and the server. */
- public static final int PROTOCOL_MAJOR_VERSION = 3;
-
- /** Minor version of the protocol between the client and the server. */
- public static final int PROTOCOL_MINOR_VERSION = 2;
-
- /** Major version of the client config. */
- public static final int CONFIG_MAJOR_VERSION = 3;
-
- /** Minor version of the client config. */
- public static final int CONFIG_MINOR_VERSION = 2;
-
- /** Version of the protocol currently being used by the client/server for v2 clients. */
- public static final ProtocolVersion PROTOCOL_VERSION = ProtocolVersion.newBuilder()
- .setVersion(CommonProtos2.newVersion(PROTOCOL_MAJOR_VERSION, PROTOCOL_MINOR_VERSION)).build();
-
- /** Version of the protocol currently being used by the client/server for v1 clients. */
- public static final ProtocolVersion PROTOCOL_VERSION_V1 = ProtocolVersion.newBuilder()
- .setVersion(CommonProtos2.newVersion(2, 0)).build();
-
- /** Version of the client currently being used by the client. */
- public static final Version CLIENT_VERSION_VALUE =
- CommonProtos2.newVersion(CLIENT_MAJOR_VERSION, CLIENT_MINOR_VERSION);
-
- /** The value of ObjectSource.Type from types.proto. Must be kept in sync with that file. */
- public static final int INTERNAL_OBJECT_SOURCE_TYPE = ObjectSource.Type.INTERNAL.getNumber();
-
- /** The value of ObjectSource.Type from types.proto. Must be kept in sync with that file. */
- public static final int TEST_OBJECT_SOURCE_TYPE = ObjectSource.Type.TEST.getNumber();
-
- /** The value of ClientType.Type from types.proto. Must be kept in sync with that file. */
- public static final int INTERNAL_CLIENT_TYPE = ClientType.Type.INTERNAL.getNumber();
-
- /** The value of ClientType.Type from types.proto. Must be kept in sync with that file. */
- public static final int TEST_CLIENT_TYPE = ClientType.Type.TEST.getNumber();
-
- /** Object id used to trigger a refresh of all cached objects ("invalidate-all"). */
- public static final ObjectIdP ALL_OBJECT_ID = ObjectIdP.newBuilder()
- .setName(ByteString.EMPTY)
- .setSource(INTERNAL_OBJECT_SOURCE_TYPE)
- .build();
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/CommonProtoStrings2.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/CommonProtoStrings2.java
deleted file mode 100644
index fc7ebf7834a..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/CommonProtoStrings2.java
+++ /dev/null
@@ -1,650 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.common;
-
-import com.google.common.base.Receiver;
-import com.google.ipc.invalidation.util.Bytes;
-import com.google.ipc.invalidation.util.LazyString;
-import com.google.ipc.invalidation.util.TextBuilder;
-import com.google.protobuf.ByteString;
-import com.google.protos.ipc.invalidation.ClientProtocol.ApplicationClientIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientHeader;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientToServerMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.ConfigChangeMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.ErrorMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InfoMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InfoRequestMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InitializeMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InvalidationMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InvalidationP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ObjectIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.PropertyRecord;
-import com.google.protos.ipc.invalidation.ClientProtocol.ProtocolVersion;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationP;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationStatus;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationStatusMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSubtree;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSummary;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSyncMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSyncRequestMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.ServerHeader;
-import com.google.protos.ipc.invalidation.ClientProtocol.ServerToClientMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.StatusP;
-import com.google.protos.ipc.invalidation.ClientProtocol.TokenControlMessage;
-
-import java.util.Collection;
-
-
-/**
- * Utilities to make it easier/cleaner/shorter for printing and converting protobufs to strings in
- * . This class exposes methods to return objects such that their toString method returns a
- * compact representation of the proto. These methods can be used in the Ticl
- *
- */
-public class CommonProtoStrings2 {
-
- //
- // Implementation notes: The following methods return the object as mentioned above for different
- // protos. Each method (except for a couple of them) essentially calls a private static method
- // that uses a TextBuilder to construct the final string. Each method has the following spec:
- // Returns a compact string representation for {@code <parameter-name>} for logging
- //
-
- /** See spec in implementation notes. */
- public static Object toLazyCompactString(final ByteString byteString) {
- if (byteString == null) {
- return null;
- }
- return new Object() {
- @Override
- public String toString() {
- return Bytes.toString(byteString.toByteArray());
- }
- };
- }
-
- /** See spec in implementation notes. */
- public static Object toLazyCompactString(final byte[] bytes) {
- if (bytes == null) {
- return null;
- }
- return new Object() {
- @Override
- public String toString() {
- return Bytes.toString(bytes);
- }
- };
- }
-
- /** See spec in implementation notes. */
- public static Object toLazyCompactString(final ObjectIdP objectId) {
- return LazyString.toLazyCompactString(objectId, new Receiver<TextBuilder>() {
- @Override
- public void accept(TextBuilder builder) {
- toCompactString(builder, objectId);
- }
- });
- }
-
- /** See spec in implementation notes. */
- public static Object toLazyCompactString(final InvalidationP invalidation) {
- return LazyString.toLazyCompactString(invalidation, new Receiver<TextBuilder>() {
- @Override
- public void accept(TextBuilder builder) {
- toCompactString(builder, invalidation);
- }
- });
- }
-
- /** See spec in implementation notes. */
- public static Object toLazyCompactString(final RegistrationP registration) {
- return LazyString.toLazyCompactString(registration, new Receiver<TextBuilder>() {
- @Override
- public void accept(TextBuilder builder) {
- toCompactString(builder, registration);
- }
- });
- }
-
- /** See spec in implementation notes. */
- public static Object toLazyCompactString(final ApplicationClientIdP applicationId) {
- return LazyString.toLazyCompactString(applicationId, new Receiver<TextBuilder>() {
- @Override
- public void accept(TextBuilder builder) {
- toCompactString(builder, applicationId);
- }
- });
- }
-
- /** See spec in implementation notes. */
- public static Object toLazyCompactString(final RegistrationSummary regSummary) {
- return LazyString.toLazyCompactString(regSummary, new Receiver<TextBuilder>() {
- @Override
- public void accept(TextBuilder builder) {
- toCompactString(builder, regSummary);
- }
- });
- }
-
- /** See spec in implementation notes. */
- public static Object toLazyCompactString(final InfoMessage infoMessage) {
- return LazyString.toLazyCompactString(infoMessage, new Receiver<TextBuilder>() {
- @Override
- public void accept(TextBuilder builder) {
- toCompactString(builder, infoMessage);
- }
- });
- }
-
- /** See spec in implementation notes. */
- public static Object toLazyCompactString(final RegistrationSyncMessage syncMessage) {
- return LazyString.toLazyCompactString(syncMessage, new Receiver<TextBuilder>() {
- @Override
- public void accept(TextBuilder builder) {
- toCompactString(builder, syncMessage);
- }
- });
- }
-
- /** See spec in implementation notes and toCompactString for ClientToServerMessage. */
- public static Object toLazyCompactString(final ClientToServerMessage message,
- final boolean printHighFrequencyMessages) {
- return LazyString.toLazyCompactString(message, new Receiver<TextBuilder>() {
- @Override
- public void accept(TextBuilder builder) {
- toCompactString(builder, message, printHighFrequencyMessages);
- }
- });
- }
-
- /** See spec in implementation notes and toCompactString for ServerToClientMessage. */
- public static Object toLazyCompactString(final ServerToClientMessage message,
- final boolean printHighFrequencyMessages) {
- return LazyString.toLazyCompactString(message, new Receiver<TextBuilder>() {
- @Override
- public void accept(TextBuilder builder) {
- toCompactString(builder, message, printHighFrequencyMessages);
- }
- });
- }
-
-
- /** See spec in implementation notes. */
- public static Object toLazyCompactStringForObjectIds(
- final Collection<ObjectIdP> objectIds) {
- return LazyString.toLazyCompactString(objectIds, new Receiver<TextBuilder>() {
- @Override
- public void accept(TextBuilder builder) {
- toCompactStringForObjectIds(builder, objectIds);
- }
- });
- }
-
- /** See spec in implementation notes. */
- public static Object toLazyCompactStringForInvalidations(
- final Collection<InvalidationP> invalidations) {
- return LazyString.toLazyCompactString(invalidations, new Receiver<TextBuilder>() {
- @Override
- public void accept(TextBuilder builder) {
- toCompactStringForInvalidations(builder, invalidations);
- }
- });
- }
-
- /** See spec in implementation notes. */
- public static Object toLazyCompactStringForRegistrations(
- final Collection<RegistrationP> registrations) {
- return LazyString.toLazyCompactString(registrations, new Receiver<TextBuilder>() {
- @Override
- public void accept(TextBuilder builder) {
- toCompactStringForRegistrations(builder, registrations);
- }
- });
- }
-
- //
- // Implementation notes: The following helper methods do the actual conversion of the proto into
- // the compact representation in the given builder. Each method has the following spec:
- // Adds a compact representation for {@code <parameter-name>} to {@code builder} and
- // returns {@code builder}.
- // TODO: Look into building indirection tables for the collections to avoid
- // code duplication.
- //
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder, ByteString byteString) {
- if (byteString == null) {
- return builder;
- }
- return Bytes.toCompactString(builder, byteString.toByteArray());
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder, ObjectIdP objectId) {
- if (objectId == null) {
- return builder;
- }
- builder.appendFormat("(Obj: %s, ", objectId.getSource());
- toCompactString(builder, objectId.getName());
- builder.append(')');
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder,
- InvalidationP invalidation) {
- if (invalidation == null) {
- return builder;
- }
- builder.append("(Inv: ");
- toCompactString(builder, invalidation.getObjectId());
- builder.append(", ");
- if (invalidation.getIsTrickleRestart()) {
- builder.append("<");
- }
- builder.append(invalidation.getVersion());
- if (invalidation.hasPayload()) {
- builder.append(", P:");
- toCompactString(builder, invalidation.getPayload());
- }
- builder.append(')');
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactStringForInvalidations(TextBuilder builder,
- final Collection<InvalidationP> invalidations) {
- if (invalidations == null) {
- return builder;
- }
- boolean first = true;
- for (InvalidationP invalidation : invalidations) {
- if (!first) {
- builder.append(", ");
- }
- toCompactString(builder, invalidation);
- first = false;
- }
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder, StatusP status) {
- if (status == null) {
- return builder;
- }
- builder.appendFormat("Status: %s", status.getCode());
- if (status.hasDescription()) {
- builder.appendFormat(", Desc: %s", status.getDescription());
- }
- return builder;
- }
-
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder, RegistrationP regOp) {
- if (regOp == null) {
- return builder;
- }
- builder.appendFormat("RegOp: %s, ",
- regOp.getOpType() == RegistrationP.OpType.REGISTER ? "R" : "U");
- toCompactString(builder, regOp.getObjectId());
- return builder;
- }
-
- public static TextBuilder toCompactString(TextBuilder builder,
- RegistrationStatus regStatus) {
- if (regStatus == null) {
- return builder;
- }
- builder.append('<');
- toCompactString(builder, regStatus.getRegistration());
- builder.append(", ");
- toCompactString(builder, regStatus.getStatus());
- builder.append('>');
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactStringForRegistrations(TextBuilder builder,
- Collection<RegistrationP> registrations) {
- if (registrations == null) {
- return builder;
- }
-
- boolean first = true;
- builder.append("RegOps: ");
- for (RegistrationP registration : registrations) {
- if (!first) {
- builder.append(", ");
- }
- toCompactString(builder, registration);
- first = false;
- }
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactStringForRegistrationStatuses(TextBuilder builder,
- Collection<RegistrationStatus> registrationStatuses) {
- if (registrationStatuses == null) {
- return builder;
- }
-
- boolean first = true;
- builder.append("RegOps: ");
- for (RegistrationStatus registrationStatus : registrationStatuses) {
- if (!first) {
- builder.append(", ");
- }
- toCompactString(builder, registrationStatus);
- first = false;
- }
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactStringForObjectIds(TextBuilder builder,
- Collection<ObjectIdP> objectIds) {
- if (objectIds == null) {
- return builder;
- }
- boolean first = true;
- builder.append("ObjectIds: ");
- for (ObjectIdP objectId : objectIds) {
- if (!first) {
- builder.append(", ");
- }
- toCompactString(builder, objectId);
- first = false;
- }
- return builder;
- }
-
- /** See spec in implementation notes. */
- private static TextBuilder toCompactString(TextBuilder builder,
- ApplicationClientIdP applicationClientId) {
- if (applicationClientId == null) {
- return builder;
- }
- builder.appendFormat("(Ceid: ");
- toCompactString(builder, applicationClientId.getClientName());
- builder.append(')');
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder,
- RegistrationSummary regSummary) {
- if (regSummary == null) {
- return builder;
- }
-
- builder.appendFormat("<RegSummary: Num = %d, Hash = ", regSummary.getNumRegistrations());
- CommonProtoStrings2.toCompactString(builder, regSummary.getRegistrationDigest());
- builder.append('>');
- return builder;
- }
-
- public static TextBuilder toCompactString(TextBuilder builder,
- ProtocolVersion protocolVersion) {
- if (protocolVersion == null) {
- return builder;
- }
- builder.appendFormat("%d.%d", protocolVersion.getVersion().getMajorVersion(),
- protocolVersion.getVersion().getMinorVersion());
- return builder;
- }
-
- // Print methods for every client-to-server message type.
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder, ClientHeader header) {
- if (header == null) {
- return builder;
- }
- builder.append("C2S: ");
- toCompactString(builder, header.getProtocolVersion());
- builder.appendFormat(", MsgId: %s, Num regs = %s, Token = ", header.getMessageId(),
- header.getRegistrationSummary().getNumRegistrations());
- toCompactString(builder, header.getClientToken());
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder,
- InitializeMessage initializeMessage) {
- if (initializeMessage == null) {
- return builder;
- }
- builder.appendFormat("InitMsg: Client Type: %d, ", initializeMessage.getClientType());
- toCompactString(builder, initializeMessage.getApplicationClientId());
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder,
- RegistrationMessage registrationMessage) {
- if (registrationMessage == null) {
- return builder;
- }
- builder.appendFormat("RegMsg: ");
- toCompactStringForRegistrations(builder, registrationMessage.getRegistrationList());
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder,
- RegistrationSyncMessage syncMessage) {
- if (syncMessage == null) {
- return builder;
- }
- RegistrationSubtree subtree = syncMessage.getSubtree(0);
- builder.appendFormat("RegSyncMsg: Num regs: %d, Regs: ", subtree.getRegisteredObjectCount());
- toCompactStringForObjectIds(builder, subtree.getRegisteredObjectList());
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder,
- InfoMessage infoMessage) {
- if (infoMessage == null) {
- return builder;
- }
- builder.appendFormat("InfoMsg: Platform = %s, Is_summary_requested = %s, Perf counters: ",
- infoMessage.getClientVersion().getPlatform(),
- infoMessage.getServerRegistrationSummaryRequested());
- boolean first = true;
- for (PropertyRecord record : infoMessage.getPerformanceCounterList()) {
- if (!first) {
- builder.append(", ");
- }
- builder.appendFormat("%s = %d", record.getName(), record.getValue());
- first = false;
- }
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder,
- InvalidationMessage invMessage) {
- if (invMessage == null) {
- return builder;
- }
- builder.appendFormat("InvMsg: ");
- toCompactStringForInvalidations(builder, invMessage.getInvalidationList());
- return builder;
- }
-
- // Print methods for every server-to-client message type.
-
- public static TextBuilder toCompactString(TextBuilder builder, ServerHeader header) {
- if (header == null) {
- return builder;
- }
- builder.append("S2C: ");
- toCompactString(builder, header.getProtocolVersion());
- builder.appendFormat(", MsgId: %s, Num regs = %s, Token = ", header.getMessageId(),
- header.getRegistrationSummary().getNumRegistrations());
- toCompactString(builder, header.getClientToken());
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder,
- TokenControlMessage tokenControlMessage) {
- if (tokenControlMessage == null) {
- return builder;
- }
- builder.append("TokenMsg: ");
- toCompactString(builder, tokenControlMessage.getNewToken());
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder,
- RegistrationStatusMessage regStatusMessage) {
- if (regStatusMessage == null) {
- return builder;
- }
- builder.append("RegStatusMsg: ");
- toCompactStringForRegistrationStatuses(builder, regStatusMessage.getRegistrationStatusList());
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder,
- RegistrationSyncRequestMessage regSyncRequestMessage) {
- if (regSyncRequestMessage == null) {
- return builder;
- }
- builder.append("RegSyncRequestMsg: ");
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder,
- InfoRequestMessage infoRequestMessage) {
- if (infoRequestMessage == null) {
- return builder;
- }
- builder.append("InfoRequestMsg:");
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder,
- ConfigChangeMessage configChangeMessage) {
- if (configChangeMessage == null) {
- return builder;
- }
- builder.appendFormat("ConfigChangeMsg: %d", configChangeMessage.getNextMessageDelayMs());
- return builder;
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder,
- ErrorMessage errorMessage) {
- if (errorMessage == null) {
- return builder;
- }
- builder.appendFormat("ErrorMsg: %s, %s", errorMessage.getCode(), errorMessage.getDescription());
- return builder;
- }
-
- /**
- * If {@code printHighFrequencyMessages} is true, logs sub-messages that are exchanged at a high
- * frequency between the client and the registrar, e.g., invalidation ack message, heartbeat
- * message.
- */
- public static TextBuilder toCompactString(TextBuilder builder,
- ClientToServerMessage msg, boolean printHighFrequencyMessages) {
- // Print the header and any sub-messages in the message.
-
- toCompactString(builder, msg.getHeader());
- builder.append(',');
-
- if (msg.hasInitializeMessage()) {
- toCompactString(builder, msg.getInitializeMessage());
- builder.append(',');
- }
- if (msg.hasRegistrationMessage()) {
- toCompactString(builder, msg.getRegistrationMessage());
- builder.append(',');
- }
- if (msg.hasRegistrationSyncMessage()) {
- toCompactString(builder, msg.getRegistrationSyncMessage());
- builder.append(',');
- }
- if (printHighFrequencyMessages && msg.hasInvalidationAckMessage()) {
- toCompactString(builder, msg.getInvalidationAckMessage());
- builder.append(',');
- }
- if (printHighFrequencyMessages && msg.hasInfoMessage()) {
- toCompactString(builder, msg.getInfoMessage());
- builder.append(',');
- }
- return builder;
- }
-
- /**
- * If {@code printHighFrequencyMessages} is true, logs sub-messages that are exchanged at a high
- * frequency between the client and the registrar (if they are the only messages present),
- * e.g., invalidation message.
- */
- public static TextBuilder toCompactString(TextBuilder builder,
- ServerToClientMessage msg, boolean printHighFrequencyMessages) {
- // Print the header and any sub-messages in the message.
-
- toCompactString(builder, msg.getHeader());
- builder.append(',');
-
- if (msg.hasTokenControlMessage()) {
- toCompactString(builder, msg.getTokenControlMessage());
- builder.append(',');
- }
- if (printHighFrequencyMessages && msg.hasInvalidationMessage()) {
- toCompactString(builder, msg.getInvalidationMessage());
- builder.append(',');
- }
- if (msg.hasErrorMessage()) {
- toCompactString(builder, msg.getErrorMessage());
- builder.append(',');
- }
- if (msg.hasRegistrationSyncRequestMessage()) {
- toCompactString(builder, msg.getRegistrationSyncRequestMessage());
- builder.append(',');
- }
- if (msg.hasRegistrationStatusMessage()) {
- toCompactString(builder, msg.getRegistrationStatusMessage());
- builder.append(',');
- }
- if (msg.hasInfoRequestMessage()) {
- toCompactString(builder, msg.getInfoRequestMessage());
- builder.append(',');
- }
- if (msg.hasConfigChangeMessage()) {
- toCompactString(builder, msg.getConfigChangeMessage());
- builder.append(',');
- }
- return builder;
- }
-
- private CommonProtoStrings2() { // To prevent instantiation
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/CommonProtos2.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/CommonProtos2.java
deleted file mode 100644
index 8968088f724..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/CommonProtos2.java
+++ /dev/null
@@ -1,436 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.common;
-
-import com.google.common.base.Preconditions;
-import com.google.protobuf.ByteString;
-import com.google.protos.ipc.invalidation.AndroidChannel;
-import com.google.protos.ipc.invalidation.Channel.NetworkEndpointId;
-import com.google.protos.ipc.invalidation.Channel.NetworkEndpointId.NetworkAddress;
-import com.google.protos.ipc.invalidation.Client.AckHandleP;
-import com.google.protos.ipc.invalidation.Client.PersistentStateBlob;
-import com.google.protos.ipc.invalidation.Client.PersistentTiclState;
-import com.google.protos.ipc.invalidation.ClientProtocol.ApplicationClientIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientVersion;
-import com.google.protos.ipc.invalidation.ClientProtocol.ConfigChangeMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.ErrorMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InfoRequestMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InitializeMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InitializeMessage.DigestSerializationType;
-import com.google.protos.ipc.invalidation.ClientProtocol.InvalidationMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InvalidationP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ObjectIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.PropertyRecord;
-import com.google.protos.ipc.invalidation.ClientProtocol.RateLimitP;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationP;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationStatus;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationStatusMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSubtree;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSummary;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSyncMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSyncRequestMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.ServerHeader;
-import com.google.protos.ipc.invalidation.ClientProtocol.ServerToClientMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.StatusP;
-import com.google.protos.ipc.invalidation.ClientProtocol.TokenControlMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.Version;
-
-import java.util.Collection;
-import java.util.List;
-
-
-/**
- * Utilities for creating protocol buffers.
- *
- */
-public class CommonProtos2 {
-
-
- /** Returns true iff status corresponds to success. */
- public static boolean isSuccess(StatusP status) {
- return status.getCode() == StatusP.Code.SUCCESS;
- }
-
- /** Returns true iff status corresponds to transient failure. */
- public static boolean isTransientFailure(StatusP status) {
- return status.getCode() == StatusP.Code.TRANSIENT_FAILURE;
- }
-
- /** Returns true iff status corresponds to permanent failure. */
- public static boolean isPermanentFailure(StatusP status) {
- return status.getCode() == StatusP.Code.PERMANENT_FAILURE;
- }
-
- // The following methods help in creating a protobuf object given its components. A Nullable
- // parameter implies that the particular field will not be set for that proto.
- // For the specs, please see the corresponding Proto file (to avoid inconsistency due to
- // duplication).
-
- public static Version newVersion(int majorVersion, int minorVersion) {
- return Version.newBuilder().setMajorVersion(majorVersion).setMinorVersion(minorVersion).build();
- }
-
- public static ClientVersion newClientVersion(String platform, String language,
- String applicationInfo) {
- return ClientVersion.newBuilder()
- .setVersion(CommonInvalidationConstants2.CLIENT_VERSION_VALUE)
- .setPlatform(platform)
- .setLanguage(language)
- .setApplicationInfo(applicationInfo)
- .build();
- }
-
- public static ObjectIdP newObjectIdP(int source, ByteString name) {
- return ObjectIdP.newBuilder().setSource(source).setName(name).build();
- }
-
- public static ObjectIdP newObjectIdP(int source, byte[] name) {
- return newObjectIdP(source, ByteString.copyFrom(name));
- }
-
- public static boolean isAllObjectId(ObjectIdP objectId) {
- return (objectId != null) &&
- (CommonInvalidationConstants2.ALL_OBJECT_ID.getSource() == objectId.getSource()) &&
- (CommonInvalidationConstants2.ALL_OBJECT_ID.getName().equals(objectId.getName()));
-
- }
-
- public static RateLimitP newRateLimitP(int windowMs, int count) {
- return RateLimitP.newBuilder()
- .setWindowMs(windowMs)
- .setCount(count)
- .build();
- }
-
- public static ApplicationClientIdP newApplicationClientIdP(int clientType,
- ByteString clientName) {
- return ApplicationClientIdP.newBuilder()
- .setClientType(clientType)
- .setClientName(clientName)
- .build();
- }
-
- public static InvalidationP newInvalidationP(ObjectIdP oid, long version,
- TrickleState trickleState) {
- return newInvalidationP(oid, version, trickleState, null);
- }
-
- public static InvalidationP newInvalidationP(ObjectIdP oid, long version,
- TrickleState trickleState, ByteString payload) {
- InvalidationP.Builder builder = InvalidationP.newBuilder()
- .setObjectId(oid)
- .setIsKnownVersion(true)
- .setVersion(version)
- .setIsTrickleRestart(trickleState == TrickleState.RESTART);
- if (payload != null) {
- builder.setPayload(payload);
- }
- return builder.build();
- }
-
- public static InvalidationP newInvalidationPForUnknownVersion(ObjectIdP oid,
- long sequenceNumber) {
- return InvalidationP.newBuilder()
- .setObjectId(oid)
- .setIsKnownVersion(false)
- .setIsTrickleRestart(true)
- .setVersion(sequenceNumber)
- .build();
- }
-
- /**
- * Returns an invalidation that is identical to {@code invalidation} but with the
- * {@code is_trickle_restart} flag set to true. If the input {@invalidation} is already restarted,
- * it is returned directly. Otherwise, a new invalidation is created.
- */
- public static InvalidationP toRestartedInvalidation(InvalidationP invalidation) {
- if (invalidation.hasIsTrickleRestart() && invalidation.getIsTrickleRestart()) {
- return invalidation;
- }
- return invalidation.toBuilder().setIsTrickleRestart(true).build();
- }
-
- /**
- * Returns an invalidation that is identical to {@code invalidation} but with the
- * {@code is_trickle_restart} flag set to false. If the input {@invalidation} is already
- * a continuous invalidation, it is returned directly. Otherwise, a new invalidation is created.
- */
- public static InvalidationP toContinuousInvalidation(InvalidationP invalidation) {
- if (invalidation.hasIsTrickleRestart() && !invalidation.getIsTrickleRestart()) {
- return invalidation;
- }
- return invalidation.toBuilder().setIsTrickleRestart(false).build();
- }
-
- public static RegistrationP newRegistrationP(ObjectIdP oid, boolean isReg) {
- RegistrationP registration = RegistrationP.newBuilder()
- .setObjectId(oid)
- .setOpType(isReg ? RegistrationP.OpType.REGISTER : RegistrationP.OpType.UNREGISTER)
- .build();
- return registration;
- }
-
- public static RegistrationP newRegistrationPForRegistration(ObjectIdP oid) {
- return newRegistrationP(oid, true);
- }
-
- public static RegistrationP newRegistrationPForUnregistration(ObjectIdP oid) {
- return newRegistrationP(oid, false);
- }
-
- public static StatusP newSuccessStatus() {
- return StatusP.newBuilder().setCode(StatusP.Code.SUCCESS).build();
- }
-
- public static StatusP newFailureStatus(boolean isTransient, String description) {
- return StatusP.newBuilder()
- .setCode(isTransient ? StatusP.Code.TRANSIENT_FAILURE : StatusP.Code.PERMANENT_FAILURE)
- .setDescription(description)
- .build();
- }
-
- public static RegistrationSummary newRegistrationSummary(int numRegistrations, byte[] regDigest) {
- RegistrationSummary regSummary = RegistrationSummary.newBuilder()
- .setNumRegistrations(numRegistrations)
- .setRegistrationDigest(ByteString.copyFrom(regDigest))
- .build();
- return regSummary;
- }
-
- public static RegistrationStatus newRegistrationStatus(RegistrationP registration,
- StatusP status) {
- return RegistrationStatus.newBuilder()
- .setRegistration(registration)
- .setStatus(status)
- .build();
- }
-
- public static RegistrationStatus newSuccessRegistrationStatus(RegistrationP registration) {
- return RegistrationStatus.newBuilder()
- .setRegistration(registration)
- .setStatus(newSuccessStatus())
- .build();
- }
-
- public static RegistrationStatus newTransientFailureRegistrationStatus(
- RegistrationP registration, String description) {
- return RegistrationStatus.newBuilder()
- .setRegistration(registration)
- .setStatus(newFailureStatus(true, description))
- .build();
- }
-
- public static PersistentTiclState newPersistentTiclState(ByteString clientToken,
- long lastMessageSendTimeMs) {
- return PersistentTiclState.newBuilder()
- .setClientToken(clientToken)
- .setLastMessageSendTimeMs(lastMessageSendTimeMs)
- .build();
- }
-
- public static AckHandleP newAckHandleP(InvalidationP invalidation) {
- return AckHandleP.newBuilder().setInvalidation(invalidation).build();
- }
-
- public static PersistentStateBlob newPersistentStateBlob(PersistentTiclState state,
- ByteString mac) {
- return PersistentStateBlob.newBuilder()
- .setTiclState(state)
- .setAuthenticationCode(mac)
- .build();
- }
-
- // Methods to create ClientToServerMessages.
-
- public static InitializeMessage newInitializeMessage(int clientType,
- ApplicationClientIdP applicationClientId, ByteString nonce,
- DigestSerializationType digestSerializationType) {
- return InitializeMessage.newBuilder()
- .setClientType(clientType)
- .setApplicationClientId(applicationClientId)
- .setDigestSerializationType(digestSerializationType)
- .setNonce(nonce)
- .build();
- }
-
- public static PropertyRecord newPropertyRecord(String name, int value) {
- return PropertyRecord.newBuilder().setName(name).setValue(value).build();
- }
-
- // Methods to create ServerToClientMessages.
-
- public static ServerHeader newServerHeader(ByteString clientToken, long currentTimeMs,
- RegistrationSummary registrationSummary, String messageId) {
- ServerHeader.Builder builder = ServerHeader.newBuilder()
- .setProtocolVersion(CommonInvalidationConstants2.PROTOCOL_VERSION)
- .setClientToken(clientToken)
- .setServerTimeMs(currentTimeMs);
- if (registrationSummary != null) {
- builder.setRegistrationSummary(registrationSummary);
- }
- if (messageId != null) {
- builder.setMessageId(messageId);
- }
- return builder.build();
- }
-
- public static ErrorMessage newErrorMessage(ErrorMessage.Code code, String description) {
- return ErrorMessage.newBuilder()
- .setCode(code)
- .setDescription(description)
- .build();
- }
-
- public static InvalidationMessage newInvalidationMessage(Iterable<InvalidationP> invalidations) {
- return InvalidationMessage.newBuilder().addAllInvalidation(invalidations).build();
- }
-
- public static RegistrationSyncRequestMessage newRegistrationSyncRequestMessage() {
- return RegistrationSyncRequestMessage.getDefaultInstance();
- }
-
- public static RegistrationSyncMessage newRegistrationSyncMessage(
- List<RegistrationSubtree> subtrees) {
- return RegistrationSyncMessage.newBuilder().addAllSubtree(subtrees).build();
- }
-
- public static RegistrationSubtree newRegistrationSubtree(List<ObjectIdP> registeredOids) {
- return RegistrationSubtree.newBuilder().addAllRegisteredObject(registeredOids).build();
- }
-
- public static InfoRequestMessage newPerformanceCounterRequestMessage() {
- return InfoRequestMessage.newBuilder()
- .addInfoType(InfoRequestMessage.InfoType.GET_PERFORMANCE_COUNTERS)
- .build();
- }
-
- public static ConfigChangeMessage newConfigChangeMessage(long nextMessageDelayMs) {
- return ConfigChangeMessage.newBuilder().setNextMessageDelayMs(nextMessageDelayMs).build();
- }
-
- public static ServerToClientMessage newServerToClientMessage(ServerHeader scHeader) {
- return ServerToClientMessage.newBuilder()
- .setHeader(scHeader)
- .build();
- }
-
- public static ServerToClientMessage.Builder newServerToClientMessage(ServerHeader scHeader,
- TokenControlMessage tokenControlMessage) {
- return ServerToClientMessage.newBuilder()
- .setHeader(scHeader)
- .setTokenControlMessage(tokenControlMessage);
- }
-
- public static ServerToClientMessage newServerToClientMessage(ServerHeader scHeader,
- RegistrationSyncRequestMessage syncRequestionMessage) {
- return ServerToClientMessage.newBuilder()
- .setHeader(scHeader)
- .setRegistrationSyncRequestMessage(syncRequestionMessage)
- .build();
- }
-
- public static ServerToClientMessage newServerToClientMessage(ServerHeader scHeader,
- InvalidationMessage invalidationMessage) {
- return ServerToClientMessage.newBuilder()
- .setHeader(scHeader)
- .setInvalidationMessage(invalidationMessage)
- .build();
- }
-
- public static ServerToClientMessage newServerToClientMessage(ServerHeader scHeader,
- RegistrationStatusMessage registrationStatusMessage) {
- return ServerToClientMessage.newBuilder()
- .setHeader(scHeader)
- .setRegistrationStatusMessage(registrationStatusMessage)
- .build();
- }
-
- public static ServerToClientMessage newServerToClientMessage(ServerHeader scHeader,
- InfoRequestMessage infoRequestMessage) {
- return ServerToClientMessage.newBuilder()
- .setHeader(scHeader)
- .setInfoRequestMessage(infoRequestMessage)
- .build();
- }
-
- public static ServerToClientMessage newServerToClientMessage(ServerHeader scHeader,
- ConfigChangeMessage configChangeMessage) {
- return ServerToClientMessage.newBuilder()
- .setHeader(scHeader)
- .setConfigChangeMessage(configChangeMessage)
- .build();
- }
-
- public static ServerToClientMessage newServerToClientMessage(ServerHeader scHeader,
- ErrorMessage errorMessage) {
- return ServerToClientMessage.newBuilder()
- .setHeader(scHeader)
- .setErrorMessage(errorMessage)
- .build();
- }
-
- /**
- * Constructs a network endpoint id for an Android client with the given {@code registrationId},
- * {@code clientKey}, and {@code packageName}.
- */
- public static NetworkEndpointId newAndroidEndpointId(String registrationId, String clientKey,
- String packageName, Version channelVersion) {
- Preconditions.checkNotNull(registrationId, "Null registration id");
- Preconditions.checkNotNull(clientKey, "Null client key");
- Preconditions.checkNotNull(packageName, "Null package name");
- Preconditions.checkNotNull(channelVersion, "Null channel version");
-
- AndroidChannel.EndpointId.Builder endpointBuilder = AndroidChannel.EndpointId.newBuilder()
- .setC2DmRegistrationId(registrationId)
- .setClientKey(clientKey)
- .setPackageName(packageName)
- .setChannelVersion(channelVersion);
- return newNetworkEndpointId(NetworkAddress.ANDROID, endpointBuilder.build().toByteString());
- }
-
- public static NetworkEndpointId newNetworkEndpointId(NetworkAddress networkAddr,
- ByteString clientAddr) {
- return NetworkEndpointId.newBuilder()
- .setNetworkAddress(networkAddr)
- .setClientAddress(clientAddr)
- .build();
- }
-
- public static TokenControlMessage newTokenControlMessage(ByteString newToken) {
- TokenControlMessage.Builder builder = TokenControlMessage.newBuilder();
- if (newToken != null) {
- builder.setNewToken(newToken);
- }
- return builder.build();
- }
-
- public static RegistrationStatusMessage newRegistrationStatusMessage(
- Collection<RegistrationStatus> statuses) {
- Preconditions.checkArgument(!statuses.isEmpty(), "Empty statuses");
- return RegistrationStatusMessage.newBuilder().addAllRegistrationStatus(statuses).build();
- }
-
- public static RegistrationMessage newRegistrationMessage(
- Collection<RegistrationP> registrations) {
- Preconditions.checkArgument(!registrations.isEmpty(), "Empty registrations");
- return RegistrationMessage.newBuilder().addAllRegistration(registrations).build();
- }
-
- private CommonProtos2() { // To prevent instantiation
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/DigestFunction.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/DigestFunction.java
deleted file mode 100644
index a61b92d0193..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/DigestFunction.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.common;
-
-
-/**
- * Interface specifying a function to compute digests.
- *
- */
-
-public interface DigestFunction {
- /** Clears the digest state. */
- void reset();
-
- /** Adds {@code data} to the digest being computed. */
- void update(byte[] data);
-
- /**
- * Returns the digest of the data added by {@link #update}. After this call has been made,
- * reset must be called before {@link #update} and {@link #getDigest} can be called.
- */
- byte[] getDigest();
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/ObjectIdDigestUtils.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/ObjectIdDigestUtils.java
deleted file mode 100644
index 710b05a4fa6..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/ObjectIdDigestUtils.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.common;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.util.Bytes;
-import com.google.protos.ipc.invalidation.ClientProtocol.ObjectIdP;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-
-/**
- * Digest-related utilities for object ids.
- *
- */
-
-public class ObjectIdDigestUtils {
- /**
- * Implementation of {@link DigestFunction} using SHA-1.
- */
-
- public static class Sha1DigestFunction implements DigestFunction {
- /** Digest implementation. */
- private MessageDigest sha1;
-
- /**
- * Whether the {@link #reset()} method needs to be called. This is set to true
- * when {@link #getDigest()} is called and aims to prevent subtle bugs caused by
- * failing to reset the object before computing a new digest.
- */
- private boolean resetNeeded = false;
-
- public Sha1DigestFunction() {
- try {
- this.sha1 = MessageDigest.getInstance("SHA-1");
- } catch (NoSuchAlgorithmException exception) {
- throw new RuntimeException(exception);
- }
- }
-
- @Override
- public void reset() {
- resetNeeded = false;
- sha1.reset();
- }
-
- @Override
- public void update(byte[] data) {
- Preconditions.checkState(!resetNeeded);
- sha1.update(data);
- }
-
- @Override
- public byte[] getDigest() {
- Preconditions.checkState(!resetNeeded);
- resetNeeded = true;
- return sha1.digest();
- }
- }
-
- /**
- * Returns the digest of {@code objectIdDigests} using {@code digestFn}.
- * <p>
- * REQUIRES: {@code objectIdDigests} iterate in sorted order.
- */
-
- public static Bytes getDigest(Iterable<Bytes> objectIdDigests, DigestFunction digestFn) {
- digestFn.reset();
- for (Bytes objectIdDigest : objectIdDigests) {
- digestFn.update(objectIdDigest.getByteArray());
- }
- return new Bytes(digestFn.getDigest());
- }
-
- /** Returns the digest of {@code objectId} using {@code digestFn}. */
-
- public static Bytes getDigest(ObjectIdP objectId, DigestFunction digestFn) {
- digestFn.reset();
- ByteBuffer buffer = ByteBuffer.allocate(Integer.SIZE / 8).order(ByteOrder.LITTLE_ENDIAN);
- buffer.putInt(objectId.getSource());
-
- // Little endian number for type followed by bytes.
- digestFn.update(buffer.array());
- digestFn.update(objectId.getName().toByteArray());
- return new Bytes(digestFn.getDigest());
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/ProtoValidator.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/ProtoValidator.java
deleted file mode 100644
index c14d3a2683d..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/ProtoValidator.java
+++ /dev/null
@@ -1,296 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.common;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.common.ProtoValidator.FieldInfo.Presence;
-import com.google.ipc.invalidation.util.BaseLogger;
-import com.google.ipc.invalidation.util.TypedUtil;
-import com.google.protobuf.MessageLite;
-
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.NoSuchElementException;
-import java.util.Set;
-
-
-/**
- * Base class for writing protocol buffer validators. This is used in conjunction with
- * {@code ProtoAccessorGenerator}.
- *
- */
-public abstract class ProtoValidator {
- /** Class providing access to protocol buffer fields in a generic way. */
- public interface Accessor {
- public boolean hasField(MessageLite message, Descriptor field);
- public Object getField(MessageLite message, Descriptor field);
- public Collection<String> getAllFieldNames();
- }
-
- /** Class naming a protocol buffer field in a generic way. */
- public static class Descriptor {
- private final String name;
-
- public Descriptor(String name) {
- this.name = name;
- }
- /** Returns the name of the described field. */
- public String getName() {
- return name;
- }
- @Override
- public String toString() {
- return "Descriptor for field " + name;
- }
- }
-
- /** Describes how to validate a message. */
- public static class MessageInfo {
- /** Protocol buffer descriptor for the message. */
- private final Accessor messageAccessor;
-
- /** Information about required and optional fields in this message. */
- private final Set<FieldInfo> fieldInfo = new HashSet<FieldInfo>();
-
- private int numRequiredFields;
-
- /**
- * Constructs a message info.
- *
- * @param messageAccessor descriptor for the protocol buffer
- * @param fields information about the fields
- */
- public MessageInfo(Accessor messageAccessor, FieldInfo... fields) {
- // Track which fields in the message descriptor have not yet been covered by a FieldInfo.
- // We'll use this to verify that we get a FieldInfo for every field.
- Set<String> unusedDescriptors = new HashSet<String>();
- unusedDescriptors.addAll(messageAccessor.getAllFieldNames());
-
- this.messageAccessor = messageAccessor;
- for (FieldInfo info : fields) {
- // Lookup the field given the name in the FieldInfo.
- boolean removed = TypedUtil.remove(unusedDescriptors, info.getFieldDescriptor().getName());
- Preconditions.checkState(removed, "Bad field: %s", info.getFieldDescriptor().getName());
-
- // Add the field info to the number -> info map.
- fieldInfo.add(info);
-
- if (info.getPresence() == Presence.REQUIRED) {
- ++numRequiredFields;
- }
- }
- Preconditions.checkState(unusedDescriptors.isEmpty(), "Not all fields specified in %s: %s",
- messageAccessor, unusedDescriptors);
- }
-
- /** Returns the stored field information. */
- protected Collection<FieldInfo> getAllFields() {
- return fieldInfo;
- }
-
- /**
- * Function called after the presence/absence of all fields in this message and its child
- * messages have been verified. Should be overridden to enforce additional semantic constraints
- * beyond field presence/absence if needed.
- */
- protected boolean postValidate(MessageLite message) {
- return true;
- }
-
- /** Returns the number of required fields for messages of this type. */
- public int getNumRequiredFields() {
- return numRequiredFields;
- }
- }
-
- /** Describes a field in a message. */
- protected static class FieldInfo {
- /**
- * Whether the field is required or optional. A repeated field where at least one value
- * must be set should use {@code REQUIRED}.
- */
- enum Presence {
- REQUIRED,
- OPTIONAL
- }
-
- /** Name of the field in the containing message. */
- private final Descriptor fieldDescriptor;
-
- /** Whether the field is required or optional. */
- private final Presence presence;
-
- /** If not {@code null}, message info describing how to validate the field. */
- private final MessageInfo messageInfo;
-
- /**
- * Constructs an instance.
- *
- * @param fieldDescriptor identifier for the field
- * @param presence required/optional
- * @param messageInfo if not {@code null}, describes how to validate the field
- */
- FieldInfo(Descriptor fieldDescriptor, Presence presence,
- MessageInfo messageInfo) {
- this.fieldDescriptor = fieldDescriptor;
- this.presence = presence;
- this.messageInfo = messageInfo;
- }
-
- /** Returns the name of the field. */
- public Descriptor getFieldDescriptor() {
- return fieldDescriptor;
- }
-
- /** Returns the presence information for the field. */
- Presence getPresence() {
- return presence;
- }
-
- /** Returns the validation information for the field. */
- MessageInfo getMessageInfo() {
- return messageInfo;
- }
-
- /** Returns whether the field needs additional validation. */
- boolean requiresAdditionalValidation() {
- return messageInfo != null;
- }
-
- /**
- * Returns a new instance describing a required field with name {@code fieldName} and validation
- * specified by {@code messageInfo}.
- */
- public static FieldInfo newRequired(Descriptor fieldDescriptor, MessageInfo messageInfo) {
- return new FieldInfo(fieldDescriptor, Presence.REQUIRED,
- Preconditions.checkNotNull(messageInfo, "messageInfo cannot be null"));
- }
-
- /**
- * Returns a new instance describing a required field with name {@code fieldName} and no
- * additional validation.
- */
- public static FieldInfo newRequired(Descriptor fieldDescriptor) {
- return new FieldInfo(fieldDescriptor, Presence.REQUIRED, null);
- }
-
- /**
- * Returns a new instance describing an optional field with name {@code fieldName} and
- * validation specified by {@code messageInfo}.
- */
- public static FieldInfo newOptional(Descriptor fieldDescriptor, MessageInfo messageInfo) {
- return new FieldInfo(fieldDescriptor, Presence.OPTIONAL,
- Preconditions.checkNotNull(messageInfo));
- }
-
- /**
- * Returns a new instance describing an optional field with name {@code fieldName} and no
- * additional validation.
- */
- public static FieldInfo newOptional(Descriptor fieldDescriptor) {
- return new FieldInfo(fieldDescriptor, Presence.OPTIONAL, null);
- }
- }
-
- /** Logger for errors */
- protected final BaseLogger logger;
-
- protected ProtoValidator(BaseLogger logger) {
- this.logger = logger;
- }
-
- /**
- * Returns an {@link Iterable} over the instance(s) of {@code field} in {@code message}. This
- * provides a uniform way to handle both singleton and repeated fields in protocol buffers, which
- * are accessed using different calls in the protocol buffer API.
- */
- @SuppressWarnings("unchecked")
-
- protected static <FieldType> Iterable<FieldType> getFieldIterable(final MessageLite message,
- final Accessor messageAccessor, final Descriptor fieldDescriptor) {
- final Object obj = messageAccessor.getField(message, fieldDescriptor);
- if (obj instanceof List) {
- return (List<FieldType>) obj;
- } else {
- // Otherwise, just use a singleton iterator.
- return new Iterable<FieldType>() {
- @Override
- public Iterator<FieldType> iterator() {
- return new Iterator<FieldType>() {
- boolean done;
- @Override
- public boolean hasNext() {
- return !done;
- }
-
- @Override
- public FieldType next() {
- if (done) {
- throw new NoSuchElementException();
- }
- done = true;
- return (FieldType) obj;
- }
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException("Not allowed");
- }
- };
- }
- };
- }
- }
-
- /**
- * Returns whether {@code message} is valid.
- * @param messageInfo specification of validity for {@code message}
- */
-
- protected boolean checkMessage(MessageLite message, MessageInfo messageInfo) {
- for (FieldInfo fieldInfo : messageInfo.getAllFields()) {
- Descriptor fieldDescriptor = fieldInfo.getFieldDescriptor();
- boolean isFieldPresent =
- messageInfo.messageAccessor.hasField(message, fieldDescriptor);
-
- // If the field must be present but isn't, fail.
- if ((fieldInfo.getPresence() == FieldInfo.Presence.REQUIRED) && !(isFieldPresent)) {
- logger.warning("Required field not set: %s", fieldInfo.getFieldDescriptor().getName());
- return false;
- }
-
- // If the field is present and requires its own validation, validate it.
- if (isFieldPresent && fieldInfo.requiresAdditionalValidation()) {
- for (MessageLite subMessage : TiclMessageValidator2.<MessageLite>getFieldIterable(
- message, messageInfo.messageAccessor, fieldDescriptor)) {
- if (!checkMessage(subMessage, fieldInfo.getMessageInfo())) {
- return false;
- }
- }
- }
- }
-
- // Once we've validated all fields, post-validate this message.
- if (!messageInfo.postValidate(message)) {
- logger.info("Failed post-validation of message (%s): %s",
- message.getClass().getSimpleName(), message);
- return false;
- }
- return true;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/TiclMessageValidator2.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/TiclMessageValidator2.java
deleted file mode 100644
index bcd932dbbe7..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/TiclMessageValidator2.java
+++ /dev/null
@@ -1,480 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.common;
-
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.ApplicationClientIdPAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.ClientConfigPAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.ClientHeaderAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.ClientToServerMessageAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.ClientVersionAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.ConfigChangeMessageAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.ErrorMessageAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.InfoMessageAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.InfoRequestMessageAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.InitializeMessageAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.InvalidationMessageAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.InvalidationPAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.ObjectIdPAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.ProtocolHandlerConfigPAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.RateLimitPAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.RegistrationMessageAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.RegistrationPAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.RegistrationStatusAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.RegistrationStatusMessageAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.RegistrationSubtreeAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.RegistrationSummaryAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.RegistrationSyncMessageAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.ServerHeaderAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.ServerToClientMessageAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.StatusPAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.TokenControlMessageAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.VersionAccessor;
-import com.google.ipc.invalidation.util.BaseLogger;
-import com.google.protobuf.MessageLite;
-import com.google.protos.ipc.invalidation.ClientProtocol.ApplicationClientIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientHeader;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientToServerMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.ConfigChangeMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InitializeMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InvalidationP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ObjectIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.RateLimitP;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSummary;
-import com.google.protos.ipc.invalidation.ClientProtocol.ServerHeader;
-import com.google.protos.ipc.invalidation.ClientProtocol.ServerToClientMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.Version;
-
-/**
- * Validator for v2 protocol messages.
- * <p>
- * The basic idea is to declare information about each field in each message, i.e., whether it is
- * optional or it is required. {@code FieldInfo} is a class that keeps track of information
- * about each field and {@code MessageInfo} is a class that keeps track of information about each
- * message. Given a message, we recursively descend a MessageInfo and determine if the fields
- * are as expected. Then once we are done with a message, we perform a post validation step
- * which checks constraints across fields.
- *
- */
-public class TiclMessageValidator2 extends ProtoValidator {
- public TiclMessageValidator2(BaseLogger logger) {
- super(logger);
- }
-
- /** Describes how to validate common messages. */
-
- public class CommonMsgInfos {
-
- /** Validation for composite (major/minor) versions. */
- final MessageInfo VERSION = new MessageInfo(ClientProtocolAccessor.VERSION_ACCESSOR,
- FieldInfo.newRequired(VersionAccessor.MAJOR_VERSION),
- FieldInfo.newRequired(VersionAccessor.MINOR_VERSION)) {
- @Override
- public boolean postValidate(MessageLite message) {
- // Versions must be non-negative.
- Version version = (Version) message;
- if ((version.getMajorVersion() < 0) || (version.getMinorVersion() < 0)) {
- logger.info("Invalid versions: %s", version);
- return false;
- }
- return true;
- }
- };
-
- /** Validation for the protocol version. */
- final MessageInfo PROTOCOL_VERSION = new MessageInfo(
- ClientProtocolAccessor.PROTOCOL_VERSION_ACCESSOR,
- FieldInfo.newRequired(ClientProtocolAccessor.ProtocolVersionAccessor.VERSION, VERSION));
-
- /** Validation for object ids. */
- final MessageInfo OID = new MessageInfo(ClientProtocolAccessor.OBJECT_ID_P_ACCESSOR,
- FieldInfo.newRequired(ObjectIdPAccessor.NAME),
- FieldInfo.newRequired(ObjectIdPAccessor.SOURCE)) {
- @Override
- public boolean postValidate(MessageLite message) {
- // Must have non-negative source code.
- ObjectIdP oid = (ObjectIdP) message;
- if (oid.getSource() < 0) {
- logger.info("Source was negative: %s", oid);
- return false;
- }
- return true;
- }
- };
-
- /** Validation for invalidations. */
- final MessageInfo INVALIDATION = new MessageInfo(
- ClientProtocolAccessor.INVALIDATION_P_ACCESSOR,
- FieldInfo.newRequired(InvalidationPAccessor.OBJECT_ID, OID),
- FieldInfo.newRequired(InvalidationPAccessor.IS_KNOWN_VERSION),
- FieldInfo.newRequired(InvalidationPAccessor.VERSION),
- FieldInfo.newOptional(InvalidationPAccessor.PAYLOAD),
- FieldInfo.newOptional(InvalidationPAccessor.IS_TRICKLE_RESTART),
- FieldInfo.newOptional(InvalidationPAccessor.BRIDGE_ARRIVAL_TIME_MS_DEPRECATED)) {
- @Override
- public boolean postValidate(MessageLite message) {
- // Must have non-negative version.
- InvalidationP invalidation = (InvalidationP) message;
- if (invalidation.getVersion() < 0) {
- logger.info("Version was negative: %s", invalidation);
- return false;
- }
- boolean isUnknownVersion = !invalidation.getIsKnownVersion();
- // Note that a missing value for is_trickle_restart is treated like a true value,
- // becomes it comes from a downlevel client that uses invalidation semantics.
- boolean isTrickleRestart = !invalidation.hasIsTrickleRestart() ||
- invalidation.getIsTrickleRestart();
- if (isUnknownVersion && !isTrickleRestart) {
- logger.info(
- "if is_known_version is false, is_trickle_restart must be true or missing: %s",
- invalidation);
- return false;
- }
- return true;
- }
- };
-
- /** Validation for a message containing many invalidations. */
- final MessageInfo INVALIDATION_MSG;
-
- /** Validation for a single registration description. */
- final MessageInfo REGISTRATIONP = new MessageInfo(
- ClientProtocolAccessor.REGISTRATION_P_ACCESSOR,
- FieldInfo.newRequired(RegistrationPAccessor.OBJECT_ID, OID),
- FieldInfo.newRequired(RegistrationPAccessor.OP_TYPE));
-
- /** Validation for a summary of registration state. */
- final MessageInfo REGISTRATION_SUMMARY = new MessageInfo(
- ClientProtocolAccessor.REGISTRATION_SUMMARY_ACCESSOR,
- FieldInfo.newRequired(RegistrationSummaryAccessor.NUM_REGISTRATIONS),
- FieldInfo.newRequired(RegistrationSummaryAccessor.REGISTRATION_DIGEST)) {
- @Override
- public boolean postValidate(MessageLite message) {
- RegistrationSummary summary = (RegistrationSummary) message;
- return (summary.getNumRegistrations() >= 0)
- && (!summary.getRegistrationDigest().isEmpty());
- }
- };
-
- final MessageInfo RATE_LIMIT = new MessageInfo(
- ClientProtocolAccessor.RATE_LIMIT_P_ACCESSOR,
- FieldInfo.newRequired(RateLimitPAccessor.WINDOW_MS),
- FieldInfo.newRequired(RateLimitPAccessor.COUNT)) {
- @Override
- public boolean postValidate(MessageLite message) {
- RateLimitP rateLimit = (RateLimitP) message;
- return (rateLimit.getWindowMs() >= 1000) &&
- (rateLimit.getWindowMs() > rateLimit.getCount());
- }
- };
-
- final MessageInfo PROTOCOL_HANDLER_CONFIG = new MessageInfo(
- ClientProtocolAccessor.PROTOCOL_HANDLER_CONFIG_P_ACCESSOR,
- FieldInfo.newOptional(ProtocolHandlerConfigPAccessor.BATCHING_DELAY_MS),
- FieldInfo.newOptional(ProtocolHandlerConfigPAccessor.RATE_LIMIT, RATE_LIMIT)
- );
-
- // Validation for Client Config. */
- final MessageInfo CLIENT_CONFIG = new MessageInfo(
- ClientProtocolAccessor.CLIENT_CONFIG_P_ACCESSOR,
- FieldInfo.newRequired(ClientConfigPAccessor.VERSION, VERSION),
- FieldInfo.newOptional(ClientConfigPAccessor.NETWORK_TIMEOUT_DELAY_MS),
- FieldInfo.newOptional(ClientConfigPAccessor.WRITE_RETRY_DELAY_MS),
- FieldInfo.newOptional(ClientConfigPAccessor.HEARTBEAT_INTERVAL_MS),
- FieldInfo.newOptional(ClientConfigPAccessor.PERF_COUNTER_DELAY_MS),
- FieldInfo.newOptional(ClientConfigPAccessor.MAX_EXPONENTIAL_BACKOFF_FACTOR),
- FieldInfo.newOptional(ClientConfigPAccessor.SMEAR_PERCENT),
- FieldInfo.newOptional(ClientConfigPAccessor.IS_TRANSIENT),
- FieldInfo.newOptional(ClientConfigPAccessor.INITIAL_PERSISTENT_HEARTBEAT_DELAY_MS),
- FieldInfo.newOptional(ClientConfigPAccessor.CHANNEL_SUPPORTS_OFFLINE_DELIVERY),
- FieldInfo.newRequired(ClientConfigPAccessor.PROTOCOL_HANDLER_CONFIG,
- PROTOCOL_HANDLER_CONFIG),
- FieldInfo.newOptional(ClientConfigPAccessor.OFFLINE_HEARTBEAT_THRESHOLD_MS),
- FieldInfo.newOptional(ClientConfigPAccessor.ALLOW_SUPPRESSION)
- );
-
- private CommonMsgInfos() {
- // Initialize in constructor since other instance fields are referenced
- INVALIDATION_MSG = new MessageInfo(
- ClientProtocolAccessor.INVALIDATION_MESSAGE_ACCESSOR,
- FieldInfo.newRequired(InvalidationMessageAccessor.INVALIDATION,
- this.INVALIDATION));
- }
- }
-
- /** Describes how to validate client messages. */
- private class ClientMsgInfos {
- /** Validation for client headers. */
- final MessageInfo HEADER = new MessageInfo(
- ClientProtocolAccessor.CLIENT_HEADER_ACCESSOR,
- FieldInfo.newRequired(ClientHeaderAccessor.PROTOCOL_VERSION,
- commonMsgInfos.PROTOCOL_VERSION),
- FieldInfo.newOptional(ClientHeaderAccessor.CLIENT_TOKEN),
- FieldInfo.newOptional(ClientHeaderAccessor.REGISTRATION_SUMMARY,
- commonMsgInfos.REGISTRATION_SUMMARY),
- FieldInfo.newRequired(ClientHeaderAccessor.CLIENT_TIME_MS),
- FieldInfo.newRequired(ClientHeaderAccessor.MAX_KNOWN_SERVER_TIME_MS),
- FieldInfo.newOptional(ClientHeaderAccessor.MESSAGE_ID),
- FieldInfo.newOptional(ClientHeaderAccessor.CLIENT_TYPE)) {
- @Override
- public boolean postValidate(MessageLite message) {
- ClientHeader header = (ClientHeader) message;
-
- // If set, token must not be empty.
- if (header.hasClientToken() && header.getClientToken().isEmpty()) {
- logger.info("Client token was set but empty: %s", header);
- return false;
- }
-
- // If set, message id must not be empty.
- // Do not use String.isEmpty() here for Froyo (JDK5) compatibility.
- if (header.hasMessageId() && (header.getMessageId().length() == 0)) {
- logger.info("Message id was set but empty: %s", header);
- return false;
- }
-
- if (header.getClientTimeMs() < 0) {
- logger.info("Client time was negative: %s", header);
- return false;
- }
-
- if (header.getMaxKnownServerTimeMs() < 0) {
- logger.info("Max known server time was negative: %s", header);
- return false;
- }
- return true;
- }
- };
-
- /** Validation for application client ids. */
- final MessageInfo APPLICATION_CLIENT_ID = new MessageInfo(
- // Client type is optional here since the registrar needs to accept messages from
- // the ticls that do not set the client type.
- ClientProtocolAccessor.APPLICATION_CLIENT_ID_P_ACCESSOR,
- FieldInfo.newOptional(ApplicationClientIdPAccessor.CLIENT_TYPE),
- FieldInfo.newRequired(ApplicationClientIdPAccessor.CLIENT_NAME)) {
- @Override
- public boolean postValidate(MessageLite message) {
- ApplicationClientIdP applicationClientId = (ApplicationClientIdP) message;
- return !applicationClientId.getClientName().isEmpty();
- }
- };
-
- /** Validation for client initialization messages. */
- final MessageInfo INITIALIZE_MESSAGE = new MessageInfo(
- ClientProtocolAccessor.INITIALIZE_MESSAGE_ACCESSOR,
- FieldInfo.newRequired(InitializeMessageAccessor.CLIENT_TYPE),
- FieldInfo.newRequired(InitializeMessageAccessor.NONCE),
- FieldInfo.newRequired(InitializeMessageAccessor.DIGEST_SERIALIZATION_TYPE),
- FieldInfo.newRequired(InitializeMessageAccessor.APPLICATION_CLIENT_ID,
- APPLICATION_CLIENT_ID)) {
- @Override
- public boolean postValidate(MessageLite message) {
- return ((InitializeMessage) message).getClientType() >= 0;
- }
- };
-
- /** Validation for registration requests. */
- final MessageInfo REGISTRATION = new MessageInfo(
- ClientProtocolAccessor.REGISTRATION_MESSAGE_ACCESSOR,
- FieldInfo.newRequired(RegistrationMessageAccessor.REGISTRATION,
- commonMsgInfos.REGISTRATIONP));
-
- /** Validation for client versions. */
- final MessageInfo CLIENT_VERSION = new MessageInfo(
- ClientProtocolAccessor.CLIENT_VERSION_ACCESSOR,
- FieldInfo.newRequired(ClientVersionAccessor.VERSION, commonMsgInfos.VERSION),
- FieldInfo.newRequired(ClientVersionAccessor.PLATFORM),
- FieldInfo.newRequired(ClientVersionAccessor.LANGUAGE),
- FieldInfo.newRequired(ClientVersionAccessor.APPLICATION_INFO));
-
- /** Validation for client information messages. */
- final MessageInfo INFO = new MessageInfo(
- ClientProtocolAccessor.INFO_MESSAGE_ACCESSOR,
- FieldInfo.newRequired(InfoMessageAccessor.CLIENT_VERSION, CLIENT_VERSION),
- FieldInfo.newOptional(InfoMessageAccessor.CONFIG_PARAMETER),
- FieldInfo.newOptional(InfoMessageAccessor.PERFORMANCE_COUNTER),
- FieldInfo.newOptional(InfoMessageAccessor.CLIENT_CONFIG, commonMsgInfos.CLIENT_CONFIG),
- FieldInfo.newOptional(InfoMessageAccessor.SERVER_REGISTRATION_SUMMARY_REQUESTED));
-
- /** Validation for registration subtrees. */
- final MessageInfo SUBTREE = new MessageInfo(
- ClientProtocolAccessor.REGISTRATION_SUBTREE_ACCESSOR,
- FieldInfo.newOptional(RegistrationSubtreeAccessor.REGISTERED_OBJECT));
-
- /** Validation for registration sync messages. */
- final MessageInfo REGISTRATION_SYNC = new MessageInfo(
- ClientProtocolAccessor.REGISTRATION_SYNC_MESSAGE_ACCESSOR,
- FieldInfo.newRequired(RegistrationSyncMessageAccessor.SUBTREE, SUBTREE));
-
- /** Validation for a ClientToServerMessage. */
- final MessageInfo CLIENT_MSG = new MessageInfo(
- ClientProtocolAccessor.CLIENT_TO_SERVER_MESSAGE_ACCESSOR,
- FieldInfo.newRequired(ClientToServerMessageAccessor.HEADER, HEADER),
- FieldInfo.newOptional(ClientToServerMessageAccessor.INFO_MESSAGE, INFO),
- FieldInfo.newOptional(ClientToServerMessageAccessor.INITIALIZE_MESSAGE, INITIALIZE_MESSAGE),
- FieldInfo.newOptional(ClientToServerMessageAccessor.INVALIDATION_ACK_MESSAGE,
- commonMsgInfos.INVALIDATION_MSG),
- FieldInfo.newOptional(ClientToServerMessageAccessor.REGISTRATION_MESSAGE, REGISTRATION),
- FieldInfo.newOptional(ClientToServerMessageAccessor.REGISTRATION_SYNC_MESSAGE,
- REGISTRATION_SYNC)) {
- @Override
- public boolean postValidate(MessageLite message) {
- ClientToServerMessage parsedMessage = (ClientToServerMessage) message;
- // The message either has an initialize request from the client or it has the client token.
- return (parsedMessage.hasInitializeMessage() ^ parsedMessage.getHeader().hasClientToken());
- }
- };
- }
-
- /** Describes how to validate server messages. */
-
- class ServerMsgInfos {
- /** Validation for server headers. */
- final MessageInfo HEADER = new MessageInfo(
- ClientProtocolAccessor.SERVER_HEADER_ACCESSOR,
- FieldInfo.newRequired(ServerHeaderAccessor.PROTOCOL_VERSION,
- commonMsgInfos.PROTOCOL_VERSION),
- FieldInfo.newRequired(ServerHeaderAccessor.CLIENT_TOKEN),
- FieldInfo.newOptional(ServerHeaderAccessor.REGISTRATION_SUMMARY,
- commonMsgInfos.REGISTRATION_SUMMARY),
- FieldInfo.newRequired(ServerHeaderAccessor.SERVER_TIME_MS),
- FieldInfo.newOptional(ServerHeaderAccessor.MESSAGE_ID)) {
- @Override
- public boolean postValidate(MessageLite message) {
- ServerHeader header = (ServerHeader) message;
- if (header.getClientToken().isEmpty()) {
- logger.info("Client token was empty: %s", header);
- return false;
- }
- if (header.getServerTimeMs() < 0) {
- logger.info("Server time was negative: %s", header);
- return false;
- }
- // If set, message id must not be empty.
- // Do not use String.isEmpty() here for Froyo (JDK5) compatibility.
- if (header.hasMessageId() && (header.getMessageId().length() == 0)) {
- logger.info("Message id was set but empty: %s", header);
- return false;
- }
- return true;
- }
- };
-
- /** Validation for server response codes. */
- final MessageInfo STATUSP = new MessageInfo(
- ClientProtocolAccessor.STATUS_P_ACCESSOR,
- FieldInfo.newRequired(StatusPAccessor.CODE),
- FieldInfo.newOptional(StatusPAccessor.DESCRIPTION));
-
- /** Validation for token control messages. */
- final MessageInfo TOKEN_CONTROL = new MessageInfo(
- ClientProtocolAccessor.TOKEN_CONTROL_MESSAGE_ACCESSOR,
- FieldInfo.newOptional(TokenControlMessageAccessor.NEW_TOKEN));
-
- /** Validation for error messages. */
- final MessageInfo ERROR = new MessageInfo(
- ClientProtocolAccessor.ERROR_MESSAGE_ACCESSOR,
- FieldInfo.newRequired(ErrorMessageAccessor.CODE),
- FieldInfo.newRequired(ErrorMessageAccessor.DESCRIPTION));
-
- /** Validation for registration results. */
- final MessageInfo REGISTRATION_RESULT = new MessageInfo(
- ClientProtocolAccessor.REGISTRATION_STATUS_ACCESSOR,
- FieldInfo.newRequired(RegistrationStatusAccessor.REGISTRATION,
- commonMsgInfos.REGISTRATIONP),
- FieldInfo.newRequired(RegistrationStatusAccessor.STATUS, STATUSP));
-
- /** Validation for registration status messages. */
- final MessageInfo REGISTRATION_STATUS_MSG = new MessageInfo(
- ClientProtocolAccessor.REGISTRATION_STATUS_MESSAGE_ACCESSOR,
- FieldInfo.newRequired(RegistrationStatusMessageAccessor.REGISTRATION_STATUS,
- REGISTRATION_RESULT));
-
- /** Validation for registration sync requests. */
- final MessageInfo REGISTRATION_SYNC_REQUEST = new MessageInfo(
- ClientProtocolAccessor.REGISTRATION_SYNC_REQUEST_MESSAGE_ACCESSOR);
-
- /** Validation for info requests. */
- final MessageInfo INFO_REQUEST = new MessageInfo(
- ClientProtocolAccessor.INFO_REQUEST_MESSAGE_ACCESSOR,
- FieldInfo.newRequired(InfoRequestMessageAccessor.INFO_TYPE));
-
- /** Validation for config change message. */
- final MessageInfo CONFIG_CHANGE = new MessageInfo(
- ClientProtocolAccessor.CONFIG_CHANGE_MESSAGE_ACCESSOR,
- FieldInfo.newOptional(ConfigChangeMessageAccessor.NEXT_MESSAGE_DELAY_MS)) {
- @Override
- public boolean postValidate(MessageLite message) {
- ConfigChangeMessage parsedMessage = (ConfigChangeMessage) message;
- // If the message has a next_message_delay_ms value, it must be positive.
- return !parsedMessage.hasNextMessageDelayMs() ||
- (parsedMessage.getNextMessageDelayMs() > 0);
- }
- };
-
- /** Validation for the top-level server messages. */
- final MessageInfo SERVER_MSG = new MessageInfo(
- ClientProtocolAccessor.SERVER_TO_CLIENT_MESSAGE_ACCESSOR,
- FieldInfo.newRequired(ServerToClientMessageAccessor.HEADER, HEADER),
- FieldInfo.newOptional(ServerToClientMessageAccessor.TOKEN_CONTROL_MESSAGE, TOKEN_CONTROL),
- FieldInfo.newOptional(ServerToClientMessageAccessor.INVALIDATION_MESSAGE,
- commonMsgInfos.INVALIDATION_MSG),
- FieldInfo.newOptional(ServerToClientMessageAccessor.REGISTRATION_STATUS_MESSAGE,
- REGISTRATION_STATUS_MSG),
- FieldInfo.newOptional(ServerToClientMessageAccessor.REGISTRATION_SYNC_REQUEST_MESSAGE,
- REGISTRATION_SYNC_REQUEST),
- FieldInfo.newOptional(ServerToClientMessageAccessor.CONFIG_CHANGE_MESSAGE, CONFIG_CHANGE),
- FieldInfo.newOptional(ServerToClientMessageAccessor.INFO_REQUEST_MESSAGE, INFO_REQUEST),
- FieldInfo.newOptional(ServerToClientMessageAccessor.ERROR_MESSAGE, ERROR));
- }
-
- /** Common validation information */
-
- final CommonMsgInfos commonMsgInfos = new CommonMsgInfos();
-
- /** Client validation information */
- private final ClientMsgInfos clientMsgInfos = new ClientMsgInfos();
-
- /** Server validation information */
-
- final ServerMsgInfos serverMsgInfos = new ServerMsgInfos();
-
- /** Returns whether {@code clientMessage} is valid. */
- public boolean isValid(ClientToServerMessage clientMessage) {
- return checkMessage(clientMessage, clientMsgInfos.CLIENT_MSG);
- }
-
- /** Returns whether {@code serverMessage} is valid. */
- public boolean isValid(ServerToClientMessage serverMessage) {
- return checkMessage(serverMessage, serverMsgInfos.SERVER_MSG);
- }
-
- /** Returns whether {@code invalidation} is valid. */
- public boolean isValid(InvalidationP invalidation) {
- return checkMessage(invalidation, commonMsgInfos.INVALIDATION);
- }
-
- /** Returns whether {@code version} is valid. */
- public boolean isValid(Version version) {
- return checkMessage(version, commonMsgInfos.VERSION);
- }
-
- /** Returns the {@code MessageInfo} for a {@link ServerToClientMessage}. */
- public MessageInfo getServerToClientMessageInfo() {
- return serverMsgInfos.SERVER_MSG;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/TrickleState.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/TrickleState.java
deleted file mode 100644
index 97cb55f870e..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/common/TrickleState.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.common;
-
-import com.google.protos.ipc.invalidation.ClientProtocol.InvalidationP;
-
-/**
- * Enumeration describing whether an invalidation restarts its trickle.
- *
- */
-public enum TrickleState {
- /** The trickle is restarting; that is, past versions may have been dropped. */
- RESTART,
- /** The trickle is not restarting. */
- CONTINUE;
-
- /** Returns RESTART if {@code isTrickleRestart} is true, CONTINUE otherwise. */
- public static TrickleState fromBoolean(boolean isTrickleRestart) {
- return isTrickleRestart ? RESTART : CONTINUE;
- }
-
- /** Returns a TrickleState based on the value of {@code invalidation.is_trickle_restart}. */
- public static TrickleState fromInvalidation(InvalidationP invalidation) {
- return TrickleState.fromBoolean(invalidation.getIsTrickleRestart());
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/examples/android2/ExampleListener.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/examples/android2/ExampleListener.java
deleted file mode 100644
index 7cf74c4dc70..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/examples/android2/ExampleListener.java
+++ /dev/null
@@ -1,308 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.examples.android2;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.InvalidationListener.RegistrationState;
-import com.google.ipc.invalidation.external.client.contrib.AndroidListener;
-import com.google.ipc.invalidation.external.client.types.ErrorInfo;
-import com.google.ipc.invalidation.external.client.types.Invalidation;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-
-import android.accounts.Account;
-import android.accounts.AccountManager;
-import android.accounts.AccountManagerFuture;
-import android.accounts.AuthenticatorException;
-import android.accounts.OperationCanceledException;
-import android.app.PendingIntent;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.content.SharedPreferences.Editor;
-import android.os.Bundle;
-import android.util.Base64;
-import android.util.Log;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-
-/**
- * Implements the service that handles invalidation client events for this application. This
- * listener registers an interest in a small number of objects and calls {@link MainActivity} with
- * any relevant status changes.
- *
- */
-public final class ExampleListener extends AndroidListener {
-
- /** The account type value for Google accounts */
- private static final String GOOGLE_ACCOUNT_TYPE = "com.google";
-
- /**
- * This is the authentication token type that's used for invalidation client communication to the
- * server. For real applications, it would generally match the authorization type used by the
- * application.
- */
- private static final String AUTH_TYPE = "android";
-
- /** Name used for shared preferences. */
- private static final String PREFERENCES_NAME = "example_listener";
-
- /** Key used for listener state in shared preferences. */
- private static final String STATE_KEY = "example_listener_state";
-
- /** Object source for objects the client is tracking. */
- private static final int DEMO_SOURCE = 4;
-
- /** Prefix for object names. */
- private static final String OBJECT_ID_PREFIX = "Obj";
-
- /** The tag used for logging in the listener. */
- private static final String TAG = "TEA2:ExampleListener";
-
- /** Number of objects we're interested in tracking. */
-
- static final int NUM_INTERESTING_OBJECTS = 4;
-
- /** Ids for objects we want to track. */
- private final Set<ObjectId> interestingObjects;
-
- public ExampleListener() {
- super();
- // We're interested in objects with ids Obj1, Obj2, ...
- interestingObjects = new HashSet<ObjectId>();
- for (int i = 1; i <= NUM_INTERESTING_OBJECTS; i++) {
- interestingObjects.add(getObjectId(i));
- }
- }
-
- @Override
- public void informError(ErrorInfo errorInfo) {
- Log.e(TAG, "informError: " + errorInfo);
-
- /***********************************************************************************************
- * YOUR CODE HERE
- *
- * Handling of permanent failures is application-specific.
- **********************************************************************************************/
- }
-
- @Override
- public void ready(byte[] clientId) {
- Log.i(TAG, "ready()");
- }
-
- @Override
- public void reissueRegistrations(byte[] clientId) {
- Log.i(TAG, "reissueRegistrations()");
- register(clientId, interestingObjects);
- }
-
- @Override
- public void invalidate(Invalidation invalidation, byte[] ackHandle) {
- Log.i(TAG, "invalidate: " + invalidation);
-
- // Do real work here based upon the invalidation
- MainActivity.State.setVersion(
- invalidation.getObjectId(), "invalidate", invalidation.toString());
-
- acknowledge(ackHandle);
- }
-
- @Override
- public void invalidateUnknownVersion(ObjectId objectId, byte[] ackHandle) {
- Log.i(TAG, "invalidateUnknownVersion: " + objectId);
-
- // Do real work here based upon the invalidation.
- MainActivity.State.setVersion(
- objectId, "invalidateUnknownVersion", getBackendVersion(objectId));
-
- acknowledge(ackHandle);
- }
-
- @Override
- public void invalidateAll(byte[] ackHandle) {
- Log.i(TAG, "invalidateAll");
-
- // Do real work here based upon the invalidation.
- for (ObjectId objectId : interestingObjects) {
- MainActivity.State.setVersion(objectId, "invalidateAll", getBackendVersion(objectId));
- }
-
- acknowledge(ackHandle);
- }
-
-
- @Override
- public byte[] readState() {
- Log.i(TAG, "readState");
- SharedPreferences sharedPreferences = getSharedPreferences();
- String data = sharedPreferences.getString(STATE_KEY, null);
- return (data != null) ? Base64.decode(data, Base64.DEFAULT) : null;
- }
-
- @Override
- public void writeState(byte[] data) {
- Log.i(TAG, "writeState");
- Editor editor = getSharedPreferences().edit();
- editor.putString(STATE_KEY, Base64.encodeToString(data, Base64.DEFAULT));
- editor.commit();
- }
-
- @Override
- public void requestAuthToken(PendingIntent pendingIntent,
- String invalidAuthToken) {
- Log.i(TAG, "requestAuthToken");
-
- // In response to requestAuthToken, we need to get an auth token and inform the invalidation
- // client of the result through a call to setAuthToken. In this example, we block until a
- // result is available. It is also possible to invoke setAuthToken in a callback or when
- // handling an intent.
- AccountManager accountManager = AccountManager.get(getApplicationContext());
-
- // Invalidate the old token if necessary.
- if (invalidAuthToken != null) {
- accountManager.invalidateAuthToken(GOOGLE_ACCOUNT_TYPE, invalidAuthToken);
- }
-
- // Choose an (arbitrary in this example) account for which to retrieve an authentication token.
- Account account = getAccount(accountManager);
-
- try {
- // There are three possible outcomes of the call to getAuthToken:
- //
- // 1. Authentication failure (null result).
- // 2. The user needs to sign in or give permission for the account. In such cases, the result
- // includes an intent that can be started to retrieve credentials from the user.
- // 3. The response includes the auth token, in which case we can inform the invalidation
- // client.
- //
- // In the first case, we simply log and return. The response to such errors is application-
- // specific. For instance, the application may prompt the user to choose another account.
- //
- // In the second case, we start an intent to ask for user credentials so that they are
- // available to the application if there is a future request. An application should listen for
- // the LOGIN_ACCOUNTS_CHANGED_ACTION broadcast intent to trigger a response to the
- // invalidation client after the user has responded. Otherwise, it may take several minutes
- // for the invalidation client to start.
- //
- // In the third case, success!, we pass the authorization token and type to the invalidation
- // client using the setAuthToken method.
- AccountManagerFuture<Bundle> future = accountManager.getAuthToken(account, AUTH_TYPE,
- new Bundle(), false, null, null);
- Bundle result = future.getResult();
- if (result == null) {
- // If the result is null, it means that authentication was not possible.
- Log.w(TAG, "Auth token - getAuthToken returned null");
- return;
- }
- if (result.containsKey(AccountManager.KEY_INTENT)) {
- Log.i(TAG, "Starting intent to get auth credentials");
-
- // Need to start intent to get credentials.
- Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
- int flags = intent.getFlags();
- flags |= Intent.FLAG_ACTIVITY_NEW_TASK;
- intent.setFlags(flags);
- getApplicationContext().startActivity(intent);
- return;
- }
- String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
- setAuthToken(getApplicationContext(), pendingIntent, authToken, AUTH_TYPE);
- } catch (OperationCanceledException e) {
- Log.w(TAG, "Auth token - operation cancelled", e);
- } catch (AuthenticatorException e) {
- Log.w(TAG, "Auth token - authenticator exception", e);
- } catch (IOException e) {
- Log.w(TAG, "Auth token - IO exception", e);
- }
- }
-
- /** Returns any Google account enabled on the device. */
- private static Account getAccount(AccountManager accountManager) {
- Preconditions.checkNotNull(accountManager);
- for (Account acct : accountManager.getAccounts()) {
- if (GOOGLE_ACCOUNT_TYPE.equals(acct.type)) {
- return acct;
- }
- }
- throw new RuntimeException("No google account enabled.");
- }
-
- @Override
- public void informRegistrationFailure(byte[] clientId, ObjectId objectId, boolean isTransient,
- String errorMessage) {
- Log.e(TAG, "Registration failure!");
- if (isTransient) {
- // Retry immediately on transient failures. The base AndroidListener will handle exponential
- // backoff if there are repeated failures.
- List<ObjectId> objectIds = new ArrayList<ObjectId>();
- objectIds.add(objectId);
- if (interestingObjects.contains(objectId)) {
- Log.i(TAG, "Retrying registration of " + objectId);
- register(clientId, objectIds);
- } else {
- Log.i(TAG, "Retrying unregistration of " + objectId);
- unregister(clientId, objectIds);
- }
- }
- }
-
- @Override
- public void informRegistrationStatus(byte[] clientId, ObjectId objectId,
- RegistrationState regState) {
- Log.i(TAG, "informRegistrationStatus");
-
- List<ObjectId> objectIds = new ArrayList<ObjectId>();
- objectIds.add(objectId);
- if (regState == RegistrationState.REGISTERED) {
- if (!interestingObjects.contains(objectId)) {
- Log.i(TAG, "Unregistering for object we're no longer interested in");
- unregister(clientId, objectIds);
- }
- } else {
- if (interestingObjects.contains(objectId)) {
- Log.i(TAG, "Registering for an object");
- register(clientId, objectIds);
- }
- }
- }
-
- private SharedPreferences getSharedPreferences() {
- return getApplicationContext().getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE);
- }
-
- private String getBackendVersion(ObjectId objectId) {
- /***********************************************************************************************
- * YOUR CODE HERE
- *
- * Invalidation client has no information about the given object. Connect with the application
- * backend to determine its current state. The implementation should be non-blocking.
- **********************************************************************************************/
-
- // Normally, we would connect to a real application backend. For this example, we return a fixed
- // value.
-
- return "some value from custom app backend";
- }
-
- /** Gets object ID given index. */
- private static ObjectId getObjectId(int i) {
- return ObjectId.newInstance(DEMO_SOURCE, (OBJECT_ID_PREFIX + i).getBytes());
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/examples/android2/MainActivity.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/examples/android2/MainActivity.java
deleted file mode 100644
index fc49a832db6..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/examples/android2/MainActivity.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.examples.android2;
-
-import com.google.ipc.invalidation.external.client.contrib.AndroidListener;
-import com.google.ipc.invalidation.external.client.contrib.MultiplexingGcmListener;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-
-import android.app.Activity;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-import android.util.Log;
-import android.widget.TextView;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
-/**
- * A simple sample application that displays information about object registrations and
- * versions.
- *
- * <p>To submit invalidations, you can run the ExampleServlet:
- *
- * <p><code>
- * blaze run java/com/google/ipc/invalidation/examples:ExampleServlet -- \
- --publisherSpec="" \
- --port=8888 \
- --channelUri="talkgadget.google.com"
- * </code>
- *
- * <p>and open http://localhost:8888/publisher.
- *
- * <p>Just publish invalidations with ids similar to 'Obj1', 'Obj2', ... 'Obj3'
- *
- */
-public final class MainActivity extends Activity {
-
- /** Tag used in logging. */
- private static final String TAG = "TEA2:MainActivity";
-
- /** Ticl client configuration. */
- private static final int CLIENT_TYPE = 4; // Demo client ID.
- private static final byte[] CLIENT_NAME = "TEA2:eetrofoot".getBytes();
-
- /**
- * Keep track of current registration and object status. This should probably be implemented
- * using intents rather than static state but I don't want to distract from the invalidation
- * client essentials in this example.
- */
- public static final class State {
- private static final Map<ObjectId, String> lastInformedVersion =
- new HashMap<ObjectId, String>();
- private static volatile MainActivity currentActivity;
-
- public static void setVersion(ObjectId objectId, String origin, String description) {
- synchronized (lastInformedVersion) {
- Log.i(TAG, "[setVersion] oid=" + objectId +
- ", origin=" + origin + ", descript=" + description);
- lastInformedVersion.put(objectId, "From " + origin + "; des=" + description);
- }
- Log.i(TAG, "[setVersion] calling refreshData");
- refreshData();
- }
- }
-
- // Controls
- private TextView info;
-
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- Log.i(TAG, "[onCreate] Creating main activity");
- super.onCreate(savedInstanceState);
-
- MultiplexingGcmListener.initializeGcm(this);
-
- // Create and start a notification client. When the client is available, or if there is an
- // existing client, AndroidListener.reissueRegistrations() is called.
- Context context = getApplicationContext();
- Intent startIntent = AndroidListener.createStartIntent(context, CLIENT_TYPE, CLIENT_NAME);
- context.startService(startIntent);
-
- // Setup UI.
- info = new TextView(this);
- setContentView(info);
-
- // Remember the current activity since the TICL service in this example communicates via
- // static state.
- State.currentActivity = this;
- Log.i(TAG, "[onCreate] Calling refresh data from main activity");
- refreshData();
- }
-
- /** Updates UI with current registration status and object versions. */
- private static void refreshData() {
- final MainActivity activity = State.currentActivity;
- if (null != activity) {
- final StringBuilder builder = new StringBuilder();
- builder.append("\nLast informed versions status\n");
- builder.append("--begin-------------\n");
- synchronized (State.lastInformedVersion) {
- for (Entry<ObjectId, String> entry : State.lastInformedVersion.entrySet()) {
- builder.append(entry.getKey().toString()).append(" -> ").append(entry.getValue())
- .append("\n");
- }
- }
- builder.append("--end---------------\n");
- activity.info.post(new Runnable() {
- @Override
- public void run() {
- activity.info.setText(builder.toString());
- }
- });
- }
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationClient.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationClient.java
deleted file mode 100644
index 80103a63b9d..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationClient.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client;
-
-import com.google.ipc.invalidation.external.client.types.AckHandle;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-
-import java.util.Collection;
-
-/**
- * Interface for the invalidation client library (Ticl).
- *
- */
-public interface InvalidationClient {
-
- /**
- * Starts the client. This method MUST be called before any other method is invoked. The client is
- * considered to be started after {@link InvalidationListener#ready} has received by the
- * application.
- * <p>
- * REQUIRES: {@link #start} has not already been called.
- * Also, the resources given to the client must have been started by the caller.
- */
- void start();
-
- /**
- * Stops the client. After this method has been called, it is an error to call any other method.
- * Does not stop the resources bound to this client.
- * <p>
- * REQUIRES: {@link #start} has already been called.
- */
- void stop();
-
- /**
- * Registers to receive invalidations for the object with id {@code objectId}.
- * <p>
- * The library guarantees that the caller will be informed of the results of this call either via
- * {@link InvalidationListener#informRegistrationStatus} or
- * {@link InvalidationListener#informRegistrationFailure}.
- * <p>
- * The caller should consider the registration to have succeeded only if it gets a call
- * {@link InvalidationListener#informRegistrationStatus} for {@code objectId} with
- * {@code InvalidationListener.RegistrationState.REGISTERED}. Note that if the network is
- * disconnected, the listener events will probably show up after the network connection is
- * repaired.
- * <p>
- * REQUIRES: {@link #start} has been called and {@link InvalidationListener#ready} has been
- * received by the application's listener.
- */
- void register(ObjectId objectId);
-
- /**
- * Registers to receive invalidations for multiple objects. See the specs on
- * {@link #register(ObjectId)} for more details. If the caller needs to register for a number of
- * object ids, this method is more efficient than calling {@code register} in a loop.
- */
- void register(Collection<ObjectId> objectIds);
-
- /**
- * Unregisters for invalidations for the object with id {@code objectId}.
- * <p>
- * The library guarantees that the caller will be informed of the results of this call either via
- * {@link InvalidationListener#informRegistrationStatus} or
- * {@link InvalidationListener#informRegistrationFailure} unless the library informs the caller of
- * a connection failure via {@link InvalidationListener#informError}.
- * <p>
- * The caller should consider the unregistration to have succeeded only if it gets a call
- * {@link InvalidationListener#informRegistrationStatus} for {@code objectId} with
- * {@link InvalidationListener.RegistrationState#UNREGISTERED}.
- * Note that if the network is disconnected, the listener events will probably show up when the
- * network connection is repaired.
- * <p>
- * REQUIRES: {@link #start} has been called and and {@link InvalidationListener#ready} has been
- * receiveed by the application's listener.
- */
- void unregister(ObjectId objectId);
-
- /**
- * Unregisters for multiple objects. See the specs on {@link #unregister(ObjectId)} for more
- * details. If the caller needs to unregister for a number of object ids, this method is more
- * efficient than calling {@code unregister} in a loop.
- */
- void unregister(Collection<ObjectId> objectIds);
-
- /**
- * Acknowledges the {@link InvalidationListener} event that was delivered with the provided
- * acknowledgement handle. This indicates that the client has accepted responsibility for
- * processing the event and it does not need to be redelivered later.
- * <p>
- * REQUIRES: {@link #start} has been called and and {@link InvalidationListener#ready} has been
- * received by the application's listener.
- */
- void acknowledge(AckHandle ackHandle);
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationClientConfig.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationClientConfig.java
deleted file mode 100644
index 2d89b92de9d..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationClientConfig.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client;
-
-/**
- * Application-provided configuration for an invalidation client.
- *
- */
-public class InvalidationClientConfig {
-
- /** Client type code as assigned by the notification system's backend. */
- public final int clientType;
-
- /** Id/name of the client in the application's own naming scheme. */
- public final byte[] clientName;
-
- /** Name of the application using the library (for debugging/monitoring) */
- public final String applicationName;
-
- /** If false, invalidateUnknownVersion() is called whenever suppression occurs. */
- public final boolean allowSuppression;
-
- public InvalidationClientConfig(int clientType, byte[] clientName, String applicationName,
- boolean allowSuppression) {
- this.clientType = clientType;
- this.clientName = clientName;
- this.applicationName = applicationName;
- this.allowSuppression = allowSuppression;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationClientFactory.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationClientFactory.java
deleted file mode 100644
index 20c66154a78..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationClientFactory.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client;
-
-import com.google.ipc.invalidation.ticl.InvalidationClientCore;
-import com.google.ipc.invalidation.ticl.InvalidationClientImpl;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientConfigP;
-
-import java.util.Random;
-
-/**
- * Factory for creating invalidation clients.
- *
- */
-public class InvalidationClientFactory {
- /**
- * Constructs an invalidation client library instance.
- *
- * @param resources {@link SystemResources} to use for logging, scheduling, persistence, and
- * network connectivity
- * @param clientConfig application provided configuration for the client.
- * @param listener callback object for invalidation events
- */
- public static InvalidationClient createClient(SystemResources resources,
- InvalidationClientConfig clientConfig, InvalidationListener listener) {
- ClientConfigP internalConfig = InvalidationClientCore.createConfig()
- .setAllowSuppression(clientConfig.allowSuppression)
- .build();
- Random random = new Random(resources.getInternalScheduler().getCurrentTimeMs());
- return new InvalidationClientImpl(resources, random, clientConfig.clientType,
- clientConfig.clientName, internalConfig, clientConfig.applicationName, listener);
- }
-
- private InvalidationClientFactory() {} // Prevents instantiation.
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationClientTestHelper.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationClientTestHelper.java
deleted file mode 100644
index c8b4c114014..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationClientTestHelper.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client;
-
-import com.google.ipc.invalidation.ticl.InvalidationClientCore;
-import com.google.ipc.invalidation.ticl.InvalidationClientImpl;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientConfigP;
-
-import java.util.Random;
-
-/**
- * Helper utility functions for testing with the invalidation client.
- *
- *
- */
-public class InvalidationClientTestHelper {
-
- /**
- * Constructs an invalidation client library instance with parameters set for unit tests.
- *
- * @param clientType client type code as assigned by the notification system's backend
- * @param clientName id/name of the client in the application's own naming scheme
- * @param applicationName name of the application using the library (for debugging/monitoring)
- * @param listener callback object for invalidation events
- */
- public static InvalidationClient createForTest(SystemResources resources,
- int clientType, byte[] clientName, String applicationName, InvalidationListener listener) {
- ClientConfigP config = InvalidationClientCore.createConfigForTest().build();
- Random random = new Random(resources.getInternalScheduler().getCurrentTimeMs());
- return new InvalidationClientImpl(resources, random, clientType, clientName, config,
- applicationName, listener);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationListener.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationListener.java
deleted file mode 100644
index 3d17d1c884d..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/InvalidationListener.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client;
-
-import com.google.ipc.invalidation.external.client.types.AckHandle;
-import com.google.ipc.invalidation.external.client.types.ErrorInfo;
-import com.google.ipc.invalidation.external.client.types.Invalidation;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-
-/**
- * Listener Interface that must be implemented by clients to receive object invalidations,
- * registration status events, and error events.
- * <p>
- * After the application publishes an invalidation (oid, version) to , guarantees to send
- * at least one of the following events to listeners that have registered for oid:
- * <ol>
- * <li> Invalidate(oid, version)
- * <li> Invalidate(oid, laterVersion) where laterVersion >= version
- * <li> InvalidateUnknownVersion(oid)
- * </ol>
- * <p>
- * Each invalidation must be acknowledged by the application. Each includes an AckHandle that
- * the application must use to call {@link InvalidationClient#acknowledge} after it is done handling
- * that event.
- * <p>
- * Please see http://go/-api for additional information on the API and semantics.
- * <p>
- * Please see {@link com.google.ipc.invalidation.external.client.contrib.SimpleListener} for a
- * base class that implements some events on behalf of the application.
- * <p>
- */
-public interface InvalidationListener {
- /** Possible registration states for an object. */
- public enum RegistrationState {
- REGISTERED,
- UNREGISTERED
- }
-
- /**
- * Called in response to the {@code InvalidationClient.start} call. Indicates that the
- * InvalidationClient is now ready for use, i.e., calls such as register/unregister can be
- * performed on that object.
- * <p>
- * The application MUST NOT issue calls such as register/unregister on the InvalidationClient
- * before receiving this event.
- *
- * @param client the {@link InvalidationClient} invoking the listener
- */
- void ready(InvalidationClient client);
-
- /**
- * Indicates that an object has been updated to a particular version.
- * <ul>
- * <li> When it receives this call, the application MUST hit its backend to fetch the
- * updated state of the object, unless it already has has a version at least as recent as that
- * of the invalidation.
- *
- * <li> MAY choose to drop older versions of invalidations, as long as it calls
- * {@link #invalidate} with a later version of the same object, or calls
- * {@link #invalidateUnknownVersion}.
- *
- * <li> MAY reorder or duplicate invalidations.
- *
- * <li> MAY drop a published payload without notice.
- *
- * <li> The application MUST acknowledge this event by calling
- * {@link InvalidationClient#acknowledge} with the provided {@code ackHandle}, otherwise the
- * event will be redelivered.
- * </ul>
- *
- * @param client the {@link InvalidationClient} invoking the listener
- * @param ackHandle event acknowledgement handle
- */
- void invalidate(InvalidationClient client, Invalidation invalidation, AckHandle ackHandle);
-
- /**
- * Indicates that an object has been updated, but the version number and payload are unknown.
- *
- * <ul>
- * <li> When it receives this call, the application MUST hit its backend to fetch the updated
- * state of the object, regardless of what version it has in its cache.
- *
- * <li> The application MUST acknowledge this event by calling
- * {@link InvalidationClient#acknowledge} with the provided {@code ackHandle}, otherwise the
- * event will be redelivered.
- * </ul>
- *
- * @param client the {@link InvalidationClient} invoking the listener
- * @param ackHandle event acknowledgement handle
- */
- void invalidateUnknownVersion(InvalidationClient client, ObjectId objectId,
- AckHandle ackHandle);
-
- /**
- * Indicates that the application should consider all objects to have changed. This event is sent
- * extremely rarely.
- *
- * <ul>
- * <li> The application MUST hit its backend to fetch the updated state of all objects,
- * regardless of what version it has in its cache.
- *
- * <li> The application MUST acknowledge this event by calling
- * {@link InvalidationClient#acknowledge} with the provided {@code ackHandle}, otherwise the
- * event will be redelivered.
- * </ul>
- *
- * @param client the {@link InvalidationClient} invoking the listener
- * @param ackHandle event acknowledgement handle
- */
- void invalidateAll(InvalidationClient client, AckHandle ackHandle);
-
- /**
- * Indicates that the registration state of an object has changed.
- *
- * @param client the {@link InvalidationClient} invoking the listener
- * @param objectId the id of the object whose state changed
- * @param regState the new state
- */
- void informRegistrationStatus(InvalidationClient client, ObjectId objectId,
- RegistrationState regState);
-
- /**
- * Indicates that an object registration or unregistration operation may have failed.
- * <p>
- * For transient failures, the application MAY retry the registration later. If it chooses to do
- * so, it MUST use exponential backoff or other sensible backoff policy..
- * <p>
- * For permanent failures, the application MUST NOT automatically retry without fixing the
- * situation (e.g., by presenting a dialog box to the user).
- *
- * @param client the {@link InvalidationClient} invoking the listener
- * @param objectId the id of the object whose state changed
- * @param isTransient whether the error is transient or permanent
- * @param errorMessage extra information about the message
- */
- void informRegistrationFailure(InvalidationClient client, ObjectId objectId,
- boolean isTransient, String errorMessage);
-
- /**
- * Indicates that all registrations for the client are in an unknown state (e.g., may have
- * dropped registrations.)
- *
- * The application MUST call {@link InvalidationClient#register} for all objects that it wishes
- * to be registered for.
- *
- * @param client the {@link InvalidationClient} invoking the listener
- * @param ignored clients can ignore this argument.
- * @param ignored2 clients can ignore this argument.
- */
- void reissueRegistrations(InvalidationClient client, byte[] ignored, int ignored2);
-
- /**
- * Informs the listener about errors that have occurred in the backend.
- *
- * If the error reason is AUTH_FAILURE, the application may notify the user.
- * Otherwise, the application should log the error info for debugging purposes but take no
- * other action.
- *
- * @param client the {@link InvalidationClient} invoking the listener
- * @param errorInfo information about the error
- */
- void informError(InvalidationClient client, ErrorInfo errorInfo);
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/SystemResources.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/SystemResources.java
deleted file mode 100644
index e93b73a91e6..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/SystemResources.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client;
-
-import com.google.ipc.invalidation.external.client.types.Callback;
-import com.google.ipc.invalidation.external.client.types.SimplePair;
-import com.google.ipc.invalidation.external.client.types.Status;
-import com.google.ipc.invalidation.util.BaseLogger;
-
-/**
- * Interfaces for the system resources used by the Ticl. System resources are an abstraction layer
- * over the host operating system that provides the Ticl with the ability to schedule events, send
- * network messages, store data, and perform logging.
- * <p>
- * NOTE: All the resource types and SystemResources are required to be thread-safe.
- *
- */
-public interface SystemResources {
-
- /** Interface specifying the logging functionality provided by {@link SystemResources}. */
- public interface Logger extends BaseLogger, ResourceComponent {}
-
- /** Interface specifying the scheduling functionality provided by {@link SystemResources}. */
- public interface Scheduler extends ResourceComponent {
-
- /** Symbolic constant representing no scheduling delay, for readability. */
- static final int NO_DELAY = 0;
-
- /**
- * Schedules {@code runnable} to be run on scheduler's thread after at least {@code delayMs}
- * milliseconds.
- */
- void schedule(int delayMs, Runnable runnable);
-
- /** Returns whether the current code is executing on the scheduler's thread. */
- boolean isRunningOnThread();
-
- /**
- * Returns the current time in milliseconds since *some* epoch (NOT necessarily the UNIX epoch).
- * The only requirement is that this time advance at the rate of real time.
- */
- long getCurrentTimeMs();
- }
-
- /** Interface specifying the network functionality provided by {@link SystemResources}. */
- public interface NetworkChannel extends ResourceComponent {
- /** Interface implemented by listeners for network events. */
- public interface NetworkListener {
- /** Upcall made when a network message has been received from the data center. */
- // Implementation note: this is currently a serialized ServerToClientMessage protocol buffer.
- // Implementors MAY NOT rely on this fact.
- void onMessageReceived(byte[] message);
-
- /**
- * Upcall made when the network online status has changed. It will be invoked with
- * a boolean indicating whether the network is connected.
- * <p>
- * This is a best-effort upcall. Note that indicating incorrectly that the network is
- * connected can result in unnecessary calls for {@link #sendMessage}. Incorrect information
- * that the network is disconnected can result in messages not being sent by the client
- * library.
- */
- void onOnlineStatusChange(boolean isOnline);
-
- /**
- * Upcall made when the network address has changed. Note that the network channel
- * implementation is responsible for determining what constitutes the network address and what
- * it means to have it change.
- * <p>
- * This is a best-effort call; however, failure to invoke it may prevent the client from
- * receiving messages and cause it to behave as though offline until its next heartbeat.
- */
- void onAddressChange();
- }
-
- /** Sends {@code outgoingMessage} to the data center. */
- // Implementation note: this is currently a serialized ClientToServerMessage protocol buffer.
- // Implementors MAY NOT rely on this fact.
- void sendMessage(byte[] outgoingMessage);
-
- /**
- * Sets the {@link NetworkListener} to which events will be delivered.
- * <p>
- * REQUIRES: no listener already be registered.
- */
- void setListener(NetworkListener listener);
- }
-
- /**
- * Interface specifying the storage functionality provided by {@link SystemResources}. Basically,
- * the required functionality is a small subset of the method of a regular hash map.
- */
- public interface Storage extends ResourceComponent {
-
- /**
- * Attempts to persist {@code value} for the given {@code key}. Invokes {@code done} when
- * finished, passing a value that indicates whether it was successful.
- * <p>
- * Note: If a wrie W1 finishes unsuccessfully and then W2 is issued for the same key and W2
- * finishes successfully, W1 must NOT later overwrite W2.
- * <p>
- * REQUIRES: Neither {@code key} nor {@code value} is null.
- */
- void writeKey(String key, byte[] value, Callback<Status> done);
-
- /**
- * Reads the value corresponding to {@code key} and calls {@code done} with the result.
- * If it finds the key, passes a success status and the value. Else passes a failure status
- * and a null value.
- */
- void readKey(String key, Callback<SimplePair<Status, byte[]>> done);
-
- /**
- * Deletes the key, value pair corresponding to {@code key}. If the deletion succeeds, calls
- * {@code done} with true; else calls it with false. A deletion of a key that does not exist
- * is considered to have succeeded.
- */
- void deleteKey(String key, Callback<Boolean> done);
-
- /**
- * Reads all the keys from the underlying store and then calls {@code keyCallback} with
- * each key that was written earlier and not deleted. When all the keys are done, calls
- * {@code keyCallback} with {@code null}. With each key, the code can indicate a
- * failed status, in which case the iteration stops.
- */
- void readAllKeys(Callback<SimplePair<Status, String>> keyCallback);
- }
-
- /**
- * Interface for a component of a {@link SystemResources} implementation constructed by calls to
- * set* methods of {@link SystemResourcesBuilder}.
- * <p>
- * The SystemResourcesBuilder allows applications to create a single {@link SystemResources}
- * implementation by composing individual building blocks, each of which implements one of the
- * four required interfaces ({@link Logger}, {@link Storage}, {@link NetworkChannel},
- * {@link Scheduler}).
- * <p>
- * However, each interface implementation may require functionality from another. For example, the
- * network implementation may need to do logging. In order to allow this, we require that the
- * interface implementations also implement {@code ResourceComponent}, which specifies the single
- * method {@link #setSystemResources}. It is guaranteed that this method will be invoked exactly
- * once on each interface implementation and before any other calls are made. Implementations can
- * then save a reference to the provided resources for later use.
- * <p>
- * Note: for the obvious reasons of infinite recursion, implementations should not attempt to
- * access themselves through the provided {@link SystemResources}.
- */
- public interface ResourceComponent {
-
- /** Supplies a {@link SystemResources} instance to the component. */
- void setSystemResources(SystemResources resources);
- }
-
- //
- // End of nested interfaces
- //
-
- /**
- * Starts the resources.
- * <p>
- * REQUIRES: This method is called before the resources are used.
- */
- void start();
-
- /**
- * Stops the resources. After this point, all the resources will eventually stop doing any work
- * (e.g., scheduling, sending/receiving messages from the network etc). They will eventually
- * convert any further operations to no-ops.
- * <p>
- * REQUIRES: Start has been called.
- */
- void stop();
-
- /** Returns whether the resources are started. */
- boolean isStarted();
-
- /**
- * Returns information about the client operating system/platform, e.g., Windows, ChromeOS (for
- * debugging/monitoring purposes).
- */
- String getPlatform();
-
- /** Returns an object that can be used to do logging. */
- Logger getLogger();
-
- /** Returns an object that can be used to persist data locally. */
- Storage getStorage();
-
- /** Returns an object that can be used to send and receive messages. */
- NetworkChannel getNetwork();
-
- /** Returns an object that can be used by the client library to schedule its internal events. */
- Scheduler getInternalScheduler();
-
- /** Returns an object that can be used to schedule events for the application. */
- Scheduler getListenerScheduler();
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/SystemResourcesBuilder.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/SystemResourcesBuilder.java
deleted file mode 100644
index f735f67f242..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/SystemResourcesBuilder.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.SystemResources.NetworkChannel;
-import com.google.ipc.invalidation.external.client.SystemResources.Scheduler;
-import com.google.ipc.invalidation.external.client.SystemResources.Storage;
-import com.google.ipc.invalidation.ticl.BasicSystemResources;
-
-
-/**
- * A builder to override some or all resource components in {@code SystemResources} . See
- * discussion in {@code ResourceComponent} as well.
- *
- */
-
- // The resources used for constructing the SystemResources in builder.
-public class SystemResourcesBuilder {
- private Scheduler internalScheduler;
- private Scheduler listenerScheduler;
- private Logger logger;
- private NetworkChannel network;
- private Storage storage;
- private String platform;
-
- /** If the build method has been called on this builder. */
- private boolean sealed;
-
- /** See specs at {@code DefaultResourcesFactory.createDefaultResourcesBuilder}. */
- public SystemResourcesBuilder(Logger logger, Scheduler internalScheduler,
- Scheduler listenerScheduler, NetworkChannel network, Storage storage) {
- this.logger = logger;
- this.internalScheduler = internalScheduler;
- this.listenerScheduler = listenerScheduler;
- this.network = network;
- this.storage = storage;
- }
-
- /** Returns a new builder that shares all the resources of {@code builder} but is not sealed. */
- public SystemResourcesBuilder(SystemResourcesBuilder builder) {
- this.logger = builder.logger;
- this.internalScheduler = builder.internalScheduler;
- this.listenerScheduler = builder.listenerScheduler;
- this.network = builder.network;
- this.storage = builder.storage;
- this.sealed = false;
- }
-
- /** Returns the internal scheduler. */
- public Scheduler getInternalScheduler() {
- return internalScheduler;
- }
-
- /** Returns the listener scheduler. */
- public Scheduler getListenerScheduler() {
- return listenerScheduler;
- }
-
- /** Returns the network channel. */
- public NetworkChannel getNetwork() {
- return network;
- }
-
- /** Returns the logger. */
- public Logger getLogger() {
- return logger;
- }
-
- /** Returns the storage. */
- public Storage getStorage() {
- return storage;
- }
-
- /**
- * Sets the scheduler for scheduling internal events to be {@code internalScheduler}.
- * <p>
- * REQUIRES: {@link #build} has not been called.
- */
- public SystemResourcesBuilder setInternalScheduler(Scheduler internalScheduler) {
- Preconditions.checkState(!sealed, "Builder's build method has already been called");
- this.internalScheduler = internalScheduler;
- return this;
- }
-
- /**
- * Sets the scheduler for scheduling listener events to be {@code listenerScheduler}.
- * <p>
- * REQUIRES: {@link #build} has not been called.
- */
- public SystemResourcesBuilder setListenerScheduler(Scheduler listenerScheduler) {
- Preconditions.checkState(!sealed, "Builder's build method has already been called");
- this.listenerScheduler = listenerScheduler;
- return this;
- }
-
- /**
- * Sets the logger to be {@code logger}.
- * <p>
- * REQUIRES: {@link #build} has not been called.
- */
- public SystemResourcesBuilder setLogger(Logger logger) {
- Preconditions.checkState(!sealed, "Builder's build method has already been called");
- this.logger = logger;
- return this;
- }
-
- /**
- * Sets the network channel for communicating with the server to be {@code network}.
- * <p>
- * REQUIRES: {@link #build} has not been called.
- */
- public SystemResourcesBuilder setNetwork(NetworkChannel network) {
- Preconditions.checkState(!sealed, "Builder's build method has already been called");
- this.network = network;
- return this;
- }
-
- /**
- * Sets the persistence layer to be {@code storage}.
- * <p>
- * REQUIRES: {@link #build} has not been called.
- */
- public SystemResourcesBuilder setStorage(Storage storage) {
- Preconditions.checkState(!sealed, "Builder's build method has already been called");
- this.storage = storage;
- return this;
- }
-
- /**
- * Sets the platform to be {@code platform}.
- * <p>
- * REQUIRES: {@link #build} has not been called.
- */
- public SystemResourcesBuilder setPlatform(String platform) {
- Preconditions.checkState(!sealed, "Builder's build method has already been called");
- this.platform = platform;
- return this;
- }
-
- /**
- * Builds the {@code SystemResources} object with the given resource components and returns it.
- * <p>
- * Caller must not call any mutation method (on this SystemResourcesBuilder) after
- * {@code build} has been called (i.e., build and the set* methods)
- */
- public SystemResources build() {
- Preconditions.checkState(!sealed, "Builder's build method has already been called");
- seal();
- return new BasicSystemResources(logger, internalScheduler, listenerScheduler, network, storage,
- platform);
- }
-
- /** Seals the builder so that no mutation method can be called on this. */
- protected void seal() {
- Preconditions.checkState(!sealed, "Builder's already sealed");
- sealed = true;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/AndroidClientFactory.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/AndroidClientFactory.java
deleted file mode 100644
index a0c3c2a0135..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/AndroidClientFactory.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android;
-
-import com.google.common.base.Preconditions;
-
-import android.accounts.Account;
-import android.content.Context;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * Factory for obtaining an {@code InvalidationClient} for the Android platform. The {@link #create}
- * method will create a invalidation client associated with a particular application and user
- * account.
- * <p>
- * Applications should persist the unique client key for the new client so invalidation activity can
- * restart later if the application is removed from memory. An application can obtain an
- * invalidation client instance to resume activity by calling the {@link #resume} method with the
- * same application id that was originally passed to {@link #create}.
- *
- */
-public class AndroidClientFactory {
- /**
- * A mapping of application id to invalidation client instances that can be used to
- * resume/reassociate an existing invalidation client. Client instances are not guaranteed (nor
- * required) to be reused.
- */
- private static final Map<String, AndroidInvalidationClientImpl> clientMap =
- new ConcurrentHashMap<String, AndroidInvalidationClientImpl>();
-
- /**
- * Starts a new invalidation client for the provided application and account token that will
- * deliver invalidation events to an instance of the provided listener component.
- * <p>
- * The implementation of this method is idempotent. If you call {@link #create} more than once
- * with the same application id, account, and listenerName values, all calls after the first one
- * are equivalent to just calling {@link #resume} with the same application id.
- *
- * @param context the context for the client.
- * @param clientKey a unique id that identifies the created client within the scope of the
- * application.
- * @param account user account that is registering the invalidations.
- * @param authType the authentication token type that should be used to authenticate the client.
- * @param listenerClass the {@link AndroidInvalidationListener} subclass that is registered to
- * receive the broadcast intents for invalidation events.
- */
- public static AndroidInvalidationClient create(Context context, String clientKey, int clientType,
- Account account, String authType,
- Class<? extends AndroidInvalidationListener> listenerClass) {
- Preconditions.checkNotNull(context, "context");
- Preconditions.checkNotNull(account, "account");
- Preconditions.checkArgument((authType != null) && (authType.length() != 0),
- "authType must be a non-empty string value");
- Preconditions.checkNotNull(listenerClass, "listenerClass");
-
- AndroidInvalidationClientImpl client = null;
- if (clientMap.containsKey(clientKey)) {
- return resume(context, clientKey);
- }
- if (client == null) {
- client = new AndroidInvalidationClientImpl(context, clientKey, clientType, account, authType,
- listenerClass);
- client.initialize();
- clientMap.put(clientKey, client);
- }
- return client;
- }
-
- /**
- * Creates a new AndroidInvalidationClient instance that is resuming processing for an existing
- * application id.
- * <p>
- * Use of this method is not recommended: use {@link #create} instead.
- *
- * @param context the context for the client.
- * @param clientKey a unique key that identifies the created client within the scope of the
- * device.
- */
- public static AndroidInvalidationClient resume(Context context, String clientKey) {
- return resume(context, clientKey, true);
- }
-
- /**
- * Creates a new AndroidInvalidationClient instance that is resuming processing for an existing
- * application id.
- * <p>
- * Use of this method is not recommended: use {@link #create} instead.
- *
- * @param context the context for the client.
- * @param clientKey a unique key that identifies the created client within the scope of the
- * device.
- * @param sendTiclResumeRequest whether to send a request to the service to resume the Ticl. If
- * {@code false}, assumes the Ticl is already loaded at the service. This is used in the
- * listener implementation and should not be set by clients.
- */
- public static AndroidInvalidationClient resume(Context context, String clientKey,
- boolean sendTiclResumeRequest) {
- Preconditions.checkNotNull(context, "context");
-
- // See if a cached entry is available with a matching application id
- AndroidInvalidationClientImpl client = clientMap.get(clientKey);
- if (client != null) {
- // Notify the client instance that it has multiple references.
- client.addReference();
- } else {
- // Attempt to resume the client using the invalidation service
- client = new AndroidInvalidationClientImpl(context, clientKey);
- client.initResumed(sendTiclResumeRequest);
- }
- return client;
- }
-
- /**
- * Release the client instance associated with the provided key. Any transient resources
- * associated with the client in the factory will be released.
- *
- * @param clientKey the client to remove
- * @return {@code true} if a client with the provided key was found and releasedUUUU .
- */
- static boolean release(String clientKey) {
- return clientMap.remove(clientKey) != null;
- }
-
- /**
- * Resets the state of the factory by dropping all cached client references.
- */
-
- static void resetForTest() {
- clientMap.clear();
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/AndroidInvalidationClient.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/AndroidInvalidationClient.java
deleted file mode 100644
index 04aa2b0b194..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/AndroidInvalidationClient.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android;
-
-import com.google.ipc.invalidation.external.client.InvalidationClient;
-
-/**
- * Extends the {@link InvalidationClient} interface to add Android-specific
- * client functionality.
- *
- */
-public interface AndroidInvalidationClient extends InvalidationClient {
- /**
- * Returns the client key that uniquely identifies this client. The client key can be passed
- * to {@link AndroidClientFactory#resume} to resume processing with the client instance that
- * is identified by this.
- */
- public String getClientKey();
-
- /**
- * Releases any transient resources associated with the client such as connections to bound
- * services.
- */
- public void release();
-
- /**
- * Permanently destroys the client and all associated state.
- */
- public void destroy();
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/AndroidInvalidationClientImpl.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/AndroidInvalidationClientImpl.java
deleted file mode 100644
index 4331e64ab2a..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/AndroidInvalidationClientImpl.java
+++ /dev/null
@@ -1,341 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android;
-
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.external.client.android.service.Event;
-import com.google.ipc.invalidation.external.client.android.service.InvalidationBinder;
-import com.google.ipc.invalidation.external.client.android.service.InvalidationService;
-import com.google.ipc.invalidation.external.client.android.service.Request;
-import com.google.ipc.invalidation.external.client.android.service.Request.Action;
-import com.google.ipc.invalidation.external.client.android.service.Response;
-import com.google.ipc.invalidation.external.client.android.service.ServiceBinder.BoundWork;
-import com.google.ipc.invalidation.external.client.types.AckHandle;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-
-import android.accounts.Account;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.RemoteException;
-
-import java.util.Collection;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * Implementation of the {@code InvalidationClient} interface for Android. Instances of the class
- * are obtained using {@link AndroidClientFactory#create} or {@link AndroidClientFactory#resume}.
- * <p>
- * The class provides implementations of the {@code InvalidationClient} methods that delegate to the
- * invalidation service running on the device using the bound service model defined in
- * {@link InvalidationService}.
- *
- */
-final class AndroidInvalidationClientImpl implements AndroidInvalidationClient {
- /** Logger */
- private static final Logger logger = AndroidLogger.forTag("InvClient");
-
- /**
- * The application context associated with the client.
- */
- public final Context context;
-
- /**
- * Contains the device-unique client key associated with this client.
- */
- private final String clientKey;
-
- /**
- * Contains the client type for this client.
- */
- private final int clientType;
-
- /**
- * The Account associated with this client. May be {@code null} for resumed clients.
- */
- private Account account;
-
- /**
- * The authentication type that is used to authenticate the client.
- */
- private String authType;
-
- /**
- * A service binder used to bind to the invalidation service.
- */
- private final InvalidationBinder serviceBinder;
-
- /**
- * The {@code InvalidationListener} service class that handles events for this client. May be
- * {@code null} for resumed clients.
- */
- private final Class<? extends AndroidInvalidationListener> listenerClass;
-
- /**
- * The number of callers that are sharing a reference to this client instance. Used to decide when
- * the service binding can be safely released.
- */
- private AtomicInteger refcnt = new AtomicInteger(0);
-
- /** Whether {@link #release} was ever called with a non-positive {@code refcnt}. */
-
- AtomicBoolean wasOverReleasedForTest = new AtomicBoolean(false);
-
- /**
- * Creates a new invalidation client with the provided client key and account that sends
- * invalidation events to the specified component.
- *
- * @param context the execution context for the client.
- * @param clientKey a unique id that identifies the created client within the scope of the
- * application.
- * @param account the user account associated with the client.
- * @param listenerClass the {@link AndroidInvalidationListener} subclass that will handle
- * invalidation events.
- */
- AndroidInvalidationClientImpl(Context context,
- String clientKey,
- int clientType,
- Account account,
- String authType,
- Class<? extends AndroidInvalidationListener> listenerClass) {
- this.context = context;
- this.clientKey = clientKey;
- this.clientType = clientType;
- this.account = account;
- this.authType = authType;
- this.listenerClass = listenerClass;
- this.serviceBinder = new InvalidationBinder(context);
- }
-
- /**
- * Constructs a resumed invalidation client with the provided client key and context.
- *
- * @param context the application context for the client.
- * @param clientKey a unique id that identifies the resumed client within the scope of the device.
- */
- AndroidInvalidationClientImpl(Context context, String clientKey) {
- this.clientKey = clientKey;
- this.context = context;
- this.account = null;
- this.authType = null;
- this.listenerClass = null;
- this.clientType = -1;
- this.serviceBinder = new InvalidationBinder(context);
- }
-
- /**
- * Returns the {@link Context} within which the client was created or resumed.
- */
- Context getContext() {
- return context;
- }
-
- @Override
- public String getClientKey() {
- return clientKey;
- }
-
- /**
- * Returns the event listener class associated with the client or {@code null} if unknown (when
- * resumed).
- */
- Class<? extends AndroidInvalidationListener> getListenerClass() {
- return listenerClass;
- }
-
- @Override
- public void start() {
- Request request = Request.newBuilder(Action.START).setClientKey(clientKey).build();
- executeServiceRequest(request);
- }
-
- @Override
- public void stop() {
- Request request = Request.newBuilder(Action.STOP).setClientKey(clientKey).build();
- executeServiceRequest(request);
- }
-
- /**
- * Registers to receive invalidation notifications for an object.
- *
- * @param objectId object id.
- */
- @Override
- public void register(ObjectId objectId) {
- Request request =
- Request.newBuilder(Action.REGISTER).setClientKey(clientKey).setObjectId(objectId).build();
- executeServiceRequest(request);
- }
-
- /**
- * Registers to receive invalidation notifications for a collection of objects.
- *
- * @param objectIds object id collection.
- */
- @Override
- public void register(Collection<ObjectId> objectIds) {
- Request request =
- Request.newBuilder(Action.REGISTER).setClientKey(clientKey).setObjectIds(objectIds).build();
- executeServiceRequest(request);
- }
-
- /**
- * Unregisters to disable receipt of invalidations on an object.
- *
- * @param objectId object id.
- */
- @Override
- public void unregister(ObjectId objectId) {
- Request request =
- Request.newBuilder(Action.UNREGISTER).setClientKey(clientKey).setObjectId(objectId).build();
- executeServiceRequest(request);
- }
-
- /**
- * Unregisters to disable receipt of invalidations for a collection of objects.
- *
- * @param objectIds object id collection.
- */
- @Override
- public void unregister(Collection<ObjectId> objectIds) {
- Request request = Request
- .newBuilder(Action.UNREGISTER)
- .setClientKey(clientKey)
- .setObjectIds(objectIds)
- .build();
- executeServiceRequest(request);
- }
-
- @Override
- public void acknowledge(AckHandle ackHandle) {
- Request request = Request
- .newBuilder(Action.ACKNOWLEDGE)
- .setClientKey(clientKey)
- .setAckHandle(ackHandle)
- .build();
- executeServiceRequest(request);
- }
-
- @Override
- public void release() {
- // Release the binding and remove from the client factory when the last reference is
- // released.
- final int refsRemaining = refcnt.decrementAndGet();
- if (refsRemaining < 0) {
- wasOverReleasedForTest.set(true);
- logger.warning("Over-release of client %s", clientKey);
- } else if (refsRemaining == 0) {
- AndroidClientFactory.release(clientKey);
- serviceBinder.release();
- }
- }
-
- @Override
- public void destroy() {
- Request request = Request
- .newBuilder(Action.DESTROY)
- .setClientKey(clientKey)
- .build();
- executeServiceRequest(request);
- }
-
- /**
- * Called to initialize a newly created client instance with the invalidation service.
- */
- void initialize() {
- // Create an intent that can be used to fire listener events back to the
- // provided listener service. Use setComponent and not setPackage/setClass so the
- // intent is guaranteed to be valid even if the service is not in the same application
- Intent eventIntent = new Intent(Event.LISTENER_INTENT);
- ComponentName component = new ComponentName(context.getPackageName(), listenerClass.getName());
- eventIntent.setComponent(component);
-
- Request request = Request
- .newBuilder(Action.CREATE)
- .setClientKey(clientKey)
- .setClientType(clientType)
- .setAccount(account)
- .setAuthType(authType)
- .setIntent(eventIntent)
- .build();
- executeServiceRequest(request);
- addReference();
- }
-
- /**
- * Called to resume an existing client instance with the invalidation service. Iff
- * {@code sendTiclResumeRequest}, a request is sent to the invalidatation service to ensure
- * that the Ticl is loaded.
- */
- void initResumed(boolean sendTiclResumeRequest) {
- if (sendTiclResumeRequest) {
- Request request = Request.newBuilder(Action.RESUME).setClientKey(clientKey).build();
- executeServiceRequest(request);
- }
- addReference();
- }
-
- /**
- * Called to indicate that a client instance is being returned as a reference.
- */
- void addReference() {
- refcnt.incrementAndGet();
- }
-
- /**
- * Returns the number of references to this client instance.
- */
-
- int getReferenceCountForTest() {
- return refcnt.get();
- }
-
- /**
- * Returns {@code true} if the client has a binding to the invalidation service.
- */
-
- boolean hasServiceBindingForTest() {
- return serviceBinder.isBoundForTest();
- }
-
- /**
- * Executes a request against the invalidation service and does common error processing against
- * the resulting response. If unable to connect to the service or an error status is received from
- * it, a warning will be logged and the request will be dropped.
- *
- * @param request the request to execute.
- */
- private void executeServiceRequest(final Request request) {
- serviceBinder.runWhenBound(new BoundWork<InvalidationService>() {
- @Override
- public void run(InvalidationService service) {
- Bundle outBundle = new Bundle();
- try {
- service.handleRequest(request.getBundle(), outBundle);
- } catch (RemoteException exception) {
- logger.warning("Remote exeption executing request %s: %s", request,
- exception.getMessage());
- }
- Response response = new Response(outBundle);
- response.warnOnFailure();
- }
- });
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/AndroidInvalidationListener.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/AndroidInvalidationListener.java
deleted file mode 100644
index 5687d2d8b47..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/AndroidInvalidationListener.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android;
-
-import com.google.ipc.invalidation.external.client.InvalidationListener;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.external.client.android.service.Event;
-import com.google.ipc.invalidation.external.client.android.service.Event.Action;
-import com.google.ipc.invalidation.external.client.android.service.ListenerService;
-import com.google.ipc.invalidation.external.client.android.service.Response;
-import com.google.ipc.invalidation.external.client.types.AckHandle;
-import com.google.ipc.invalidation.external.client.types.ErrorInfo;
-import com.google.ipc.invalidation.external.client.types.Invalidation;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-
-import android.app.Service;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.IBinder;
-
-/**
- * An abstract base class for implementing a {@link Service} component
- * that handles events from the invalidation service. This class should be
- * subclassed and concrete implementations of the {@link InvalidationListener}
- * methods added to provide application-specific handling of invalidation
- * events.
- * <p>
- * This implementing subclass should be registered in {@code
- * AndroidManifest.xml} as a service of the invalidation
- * listener binding intent, as in the following sample fragment:
- *
- * <pre>
- * {@code
- * <manifest ...>
- * <application ...>
- * ...
- * service android:name="com.myco.example.AppListenerService" ...>
- * <intent-filter>
- * <action android:name="com.google.ipc.invalidation.LISTENER"/>
- * </intent-filter>
- * </receiver>
- * ...
- * <application>
- * ...
- * </manifest>
- * }
- * </pre>
- *
- */
-public abstract class AndroidInvalidationListener extends Service
- implements InvalidationListener {
-
- /** Logger */
- private static final Logger logger = AndroidLogger.forTag("InvListener");
-
- /**
- * Simple service stub that delegates back to methods on the service.
- */
- private final ListenerService.Stub listenerBinder = new ListenerService.Stub() {
-
- @Override
- public void handleEvent(Bundle input, Bundle output) {
- AndroidInvalidationListener.this.handleEvent(input, output);
- }
- };
-
- /** Lock over all state in this class. */
- private final Object lock = new Object();
-
- /** Whether the service is in the created state. */
- private boolean isCreated = false;
-
- @Override
- public void onCreate() {
- synchronized (lock) {
- super.onCreate();
- logger.fine("onCreate: %s", this.getClass());
- this.isCreated = true;
- }
- }
-
- @Override
- public void onDestroy() {
- synchronized (lock) {
- logger.fine("onDestroy: %s", this.getClass());
- this.isCreated = false;
- super.onDestroy();
- }
- }
-
- @Override
- public IBinder onBind(Intent arg0) {
- synchronized (lock) {
- logger.fine("Binding: %s", arg0);
- return listenerBinder;
- }
- }
-
- /**
- * Handles a {@link ListenerService#handleEvent} call received by the
- * listener service.
- *
- * @param input bundle containing event parameters.
- * @param output bundled used to return response to the invalidation service.
- */
- protected void handleEvent(Bundle input, Bundle output) {
- synchronized (lock) {
- if (!isCreated) {
- logger.warning("Dropping bundle since not created: %s", input);
- return;
- }
- Event event = new Event(input);
- Response.Builder response = Response.newBuilder(event.getActionOrdinal(), output);
- // All events should contain an action and client id
- Action action = event.getAction();
- String clientKey = event.getClientKey();
- logger.fine("Received %s event for %s", action, clientKey);
-
- AndroidInvalidationClient client = null;
- try {
- if (clientKey == null) {
- throw new IllegalStateException("Missing client id:" + event);
- }
-
- // Obtain the client instance for the client receiving the event. Do not attempt to load it
- // at the service: if a Ticl has been unloaded, the listener shouldn't resurrect it, because
- // that can lead to a zombie client.
- client = AndroidClientFactory.resume(this, clientKey, false);
-
- // Determine the event type based upon the request action, extract parameters
- // from extras, and invoke the listener event handler method.
- logger.fine("%s event for %s", action, clientKey);
- switch(action) {
- case READY:
- {
- ready(client);
- break;
- }
- case INVALIDATE:
- {
- Invalidation invalidation = event.getInvalidation();
- AckHandle ackHandle = event.getAckHandle();
- invalidate(client, invalidation, ackHandle);
- break;
- }
- case INVALIDATE_UNKNOWN:
- {
- ObjectId objectId = event.getObjectId();
- AckHandle ackHandle = event.getAckHandle();
- invalidateUnknownVersion(client, objectId, ackHandle);
- break;
- }
- case INVALIDATE_ALL:
- {
- AckHandle ackHandle = event.getAckHandle();
- invalidateAll(client, ackHandle);
- break;
- }
- case INFORM_REGISTRATION_STATUS:
- {
- ObjectId objectId = event.getObjectId();
- RegistrationState state = event.getRegistrationState();
- informRegistrationStatus(client, objectId, state);
- break;
- }
- case INFORM_REGISTRATION_FAILURE:
- {
- ObjectId objectId = event.getObjectId();
- String errorMsg = event.getError();
- boolean isTransient = event.getIsTransient();
- informRegistrationFailure(client, objectId, isTransient, errorMsg);
- break;
- }
- case REISSUE_REGISTRATIONS:
- {
- byte[] prefix = event.getPrefix();
- int prefixLength = event.getPrefixLength();
- reissueRegistrations(client, prefix, prefixLength);
- break;
- }
- case INFORM_ERROR:
- {
- ErrorInfo errorInfo = event.getErrorInfo();
- informError(client, errorInfo);
- break;
- }
- default:
- logger.warning("Urecognized event: %s", event);
- }
- response.setStatus(Response.Status.SUCCESS);
- } catch (RuntimeException re) {
- // If an exception occurs during processing, log it, and store the
- // result in the response sent back to the service.
- logger.severe("Failure in handleEvent", re);
- response.setError(re.getMessage());
- } finally {
- // Listeners will only use a client reference for the life of the event and release
- // it immediately since there is no way to know if additional events are coming.
- if (client != null) {
- client.release();
- }
- }
- }
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/AndroidClientException.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/AndroidClientException.java
deleted file mode 100644
index fffe397b2b4..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/AndroidClientException.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android.service;
-
-/**
- * Represents an invalidation runtime exception that will be raised to the client.
- *
- */
-public class AndroidClientException extends RuntimeException {
-
- final int status;
- final String message;
-
- /**
- * Creates a new client exception with the provided status value and message
- * @param status the integer status value that describes the error.
- * @param message an error message string.
- *
- * @see Response.Status
- */
- public AndroidClientException(int status, String message) {
- super(message);
- this.status = status;
- this.message = message;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/AndroidLogger.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/AndroidLogger.java
deleted file mode 100644
index e423db6bbfc..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/AndroidLogger.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android.service;
-
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.util.Formatter;
-
-import android.util.Log;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.logging.Level;
-
-
-/**
- * Provides the implementation of {@link Logger} for Android. The logging tag will be based upon the
- * top-level class name containing the code invoking the logger (the outer class, not an inner or
- * anonymous class name). For severe and warning level messages, the Android logger will also
- * dump the stack trace of the first argument if it is a throwable.
- */
-public class AndroidLogger implements Logger {
-
- /** Creates a new AndroidLogger that uses the provided value as the Android logging tag */
- public static AndroidLogger forTag(String tag) {
- return new AndroidLogger(tag, null);
- }
-
- /** Creates a new AndroidLogger that will compute a tag value dynamically based upon the class
- * that calls into the logger and will prepend the provided prefix (if any) on all
- * logged messages.
- */
- public static AndroidLogger forPrefix(String prefix) {
- return new AndroidLogger(null, prefix);
- }
-
- /**
- * If {@code false}, then Log.isLoggable() is called to filter log messages
- */
- private static boolean filteringDisabled = false;
-
- /**
- * Maps from a Java {@link Level} to the android {@link Log} priority value used to log
- * messages at that level.
- */
- private static Map<Level, Integer> levelToPriority = new HashMap<Level, Integer>();
-
- static {
- // Define the mappings for Java log levels to the associated Android log priorities
- levelToPriority.put(Level.INFO, Log.INFO);
- levelToPriority.put(Level.WARNING, Log.WARN);
- levelToPriority.put(Level.SEVERE, Log.ERROR);
- levelToPriority.put(Level.FINE, Log.DEBUG);
- levelToPriority.put(Level.FINER, Log.VERBOSE);
- levelToPriority.put(Level.FINEST, Log.VERBOSE);
- levelToPriority.put(Level.CONFIG, Log.INFO);
- }
-
- /**
- * Disables log filtering so all logged messages will be captured.
- */
- public static void disableFilteringForTest() {
- filteringDisabled = true;
- }
-
- /**
- * The default minimum Android log level. We default to 0 to ensure everything is logged.
- * This should be a value from the {@link Log} constants.
- */
- private static int minimumLogLevel = 0;
-
- /**
- * The maximum length of an Android logging tag. There's no formal constants but the constraint is
- * mentioned in the Log javadoc
- */
- private static final int MAX_TAG_LENGTH = 23;
-
- /** Constant tag to use for logged messages (or {@code null} to use topmost class on stack */
- private final String tag;
-
- /** Prefix added to Android logging messages */
- private final String logPrefix;
-
- /** Creates a logger that prefixes every logging stmt with {@code logPrefix}. */
- private AndroidLogger(String tag, String logPrefix) {
- this.tag = tag;
- this.logPrefix = logPrefix;
- }
-
- @Override
- public boolean isLoggable(Level level) {
- return isLoggable(getTag(), levelToPriority(level));
- }
-
- @Override
- public void log(Level level, String template, Object... args) {
- int androidLevel = levelToPriority(level);
- String tag = getTag();
- if (isLoggable(tag, androidLevel)) {
- Log.println(androidLevel, tag, format(template, args));
- }
- }
-
- @Override
- public void severe(String template, Object...args) {
- String tag = getTag();
- if (isLoggable(tag, Log.ERROR)) {
- // If the first argument is an exception, use the form of Log that will dump a stack trace
- if ((args.length > 0) && (args[0] instanceof Throwable)) {
- Log.e(tag, format(template, args), (Throwable) args[0]);
- } else {
- Log.e(tag, format(template, args));
- }
- }
- }
-
- @Override
- public void warning(String template, Object...args) {
- String tag = getTag();
- if (isLoggable(tag, Log.WARN)){
- // If the first argument is an exception, use the form of Log that will dump a stack trace
- if ((args.length > 0) && (args[0] instanceof Throwable)) {
- Log.w(tag, format(template, args), (Throwable) args[0]);
- } else {
- Log.w(tag, format(template, args));
- }
- }
- }
-
- @Override
- public void info(String template, Object...args) {
- String tag = getTag();
- if (isLoggable(tag, Log.INFO)) {
- Log.i(tag, format(template, args));
- }
- }
-
- @Override
- public void fine(String template, Object...args) {
- String tag = getTag();
- if (isLoggable(tag, Log.DEBUG)) {
- Log.d(tag, format(template, args));
- }
- }
-
- @Override
- public void setSystemResources(SystemResources resources) {
- // No-op.
- }
-
- /** Given a Java logging level, returns the corresponding Android log priority. */
- private static int levelToPriority(Level level) {
- Integer priority = levelToPriority.get(level);
- if (priority != null) {
- return priority;
- }
- throw new IllegalArgumentException("Unsupported level: " + level);
- }
-
- /** Formats the content of a logged messages for output, prepending the log prefix if any. */
- private String format(String template, Object...args) {
- return (logPrefix != null) ?
- ("[" + logPrefix + "] " + Formatter.format(template, args)) :
- Formatter.format(template, args);
- }
-
- /** Returns the Android logging tag that should be placed on logged messages */
- private String getTag() {
- if (tag != null) {
- return tag;
- }
-
- StackTraceElement[] stackTrace = new Throwable().getStackTrace();
- String className = null;
- for (int i = 0; i < stackTrace.length; i++) {
- className = stackTrace[i].getClassName();
-
- // Skip over this class's methods
- if (!className.equals(AndroidLogger.class.getName())) {
- break;
- }
- }
-
- // Compute the unqualified class name w/out any inner class, then truncate to the
- // maximum tag length.
- int unqualBegin = className.lastIndexOf('.') + 1;
- if (unqualBegin < 0) { // should never happen, but be safe
- unqualBegin = 0;
- }
- int unqualEnd = className.indexOf('$', unqualBegin);
- if (unqualEnd < 0) {
- unqualEnd = className.length();
- }
- if ((unqualEnd - unqualBegin) > MAX_TAG_LENGTH) {
- unqualEnd = unqualBegin + MAX_TAG_LENGTH;
- }
- return className.substring(unqualBegin, unqualEnd);
- }
-
- /**
- * Add additional constraint on logging. In addition to the normal check of
- * {@link Log.isLoggable(String, int)} for logging, this also requires a minimum
- * log level of the given value. This should be a value from the {@link Log} constants.
- */
- public static void setMinimumAndroidLogLevel(int logLevel) {
- minimumLogLevel = logLevel;
- }
-
- /**
- * Returns {@code true} is the provided tag/level will produce logged output.
- */
-
- boolean isLoggable(String tag, int priority) {
- return filteringDisabled || (priority >= minimumLogLevel && Log.isLoggable(tag, priority));
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/Event.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/Event.java
deleted file mode 100644
index e9fa90f9508..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/Event.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android.service;
-
-import com.google.ipc.invalidation.external.client.InvalidationListener.RegistrationState;
-import com.google.ipc.invalidation.external.client.types.ErrorInfo;
-import com.google.ipc.invalidation.external.client.types.Invalidation;
-
-import android.content.Intent;
-import android.os.Bundle;
-
-/**
- * Creates and interprets event message bundles sent from the invalidation
- * service to its application clients.
- *
- */
-public class Event extends Message {
-
- /** An intent that can be used to bind to the event listener service */
- public static final Intent LISTENER_INTENT = new Intent("com.google.ipc.invalidation.EVENT");
-
- /** The set of event action types */
- public static enum Action {
-
- /** Indicates client is ready for use */
- READY,
-
- /** Invalidate an object */
- INVALIDATE,
-
- /** Invalidation an object with an unknown version */
- INVALIDATE_UNKNOWN,
-
- /** Invalidate all objects */
- INVALIDATE_ALL,
-
- /** Registration status change notification */
- INFORM_REGISTRATION_STATUS,
-
- /** Registration failure */
- INFORM_REGISTRATION_FAILURE,
-
- /** Request to reissue registrations */
- REISSUE_REGISTRATIONS,
-
- /** Processing error */
- INFORM_ERROR,
- }
-
- /** The set of parameters that can be found in event message bundles */
- public class Parameter extends Message.Parameter {
-
- /** Contains a {@link ParcelableErrorInfo} that represents an error */
- public static final String ERROR_INFO = "errorInfo";
-
- /** Contains an {@link ParcelableInvalidation} */
- public static final String INVALIDATION = "invalidation";
-
- /** Contains a boolean value indicating whether an event error is transient */
- public static final String IS_TRANSIENT = "isTransient";
-
- /** Contains an integer ordinal value representing a registration state */
- public static final String REGISTRATION_STATE = "registrationState";
-
- /** Byte array prefix of registrations requested or -1 if no prefix is present */
- public static final String PREFIX = "prefix";
-
- /** The integer number of bits in {@link #PREFIX} */
- public static final String PREFIX_LENGTH = "prefixLength";
- }
-
- /**
- * A builder class for constructing new event messages.
- *
- * @see #newBuilder
- */
- public static class Builder extends Message.Builder<Event, Builder> {
-
- // Use newBuilder()
- private Builder(Action action) {
- super(action.ordinal(), new Bundle());
- }
-
- /**
- * Stores error information within an event message.
- */
- public Builder setErrorInfo(ErrorInfo errorInfo) {
- bundle.putParcelable(Parameter.ERROR, new ParcelableErrorInfo(errorInfo));
- return this;
- }
-
- /**
- * Stores in invalidation within an event message.
- */
- public Builder setInvalidation(Invalidation invalidation) {
- bundle.putParcelable(Parameter.INVALIDATION, new ParcelableInvalidation(invalidation, true));
- return this;
- }
-
- /*
- * Stores in registrations requested prefix within an event message.
- *
- * @param prefix the registration digest prefix
- * @param prefixLength the number of significant bits in the prefix
- */
- public Builder setPrefix(byte [] prefix, int prefixLength) {
- bundle.putByteArray(Parameter.PREFIX, prefix);
- bundle.putInt(Parameter.PREFIX_LENGTH, prefixLength);
- return this;
- }
-
- /**
- * Stores the isTransient flag within an event message.
- */
- public Builder setIsTransient(boolean isTransient) {
- bundle.putBooleanArray(Parameter.IS_TRANSIENT, new boolean [] { isTransient });
- return this;
- }
-
- /**
- * Stores registration state information within an event message.
- */
- public Builder setRegistrationState(RegistrationState state) {
- bundle.putInt(Parameter.REGISTRATION_STATE, state.ordinal());
- return this;
- }
-
- /**
- * Returns an event containing the set parameters.
- */
- @Override
- public Event build() {
- return new Event(bundle);
- }
- }
-
- /**
- * Constructs a new builder for an event associated with the provided action.
- */
- public static Builder newBuilder(Action action) {
- return new Builder(action);
- }
-
- /**
- * Constructs a new event using the contents of the provided parameter bundle.
- */
- public Event(Bundle bundle) {
- super(bundle);
- }
-
- /**
- * Returns the action from an event message.
- */
- public Action getAction() {
- return Action.values()[getActionOrdinal()];
- }
-
- /**
- * Returns the error information from an event message, or {@code null} if not present.
- */
- public ErrorInfo getErrorInfo() {
- ParcelableErrorInfo parcelableErrorInfo = parameters.getParcelable(Parameter.ERROR);
- return parcelableErrorInfo != null ? parcelableErrorInfo.errorInfo : null;
- }
-
- /**
- * Returns an invalidation from an event message, or {@code null} if not present.
- */
- public Invalidation getInvalidation() {
- ParcelableInvalidation parcelableInvalidation =
- parameters.getParcelable(Parameter.INVALIDATION);
- return parcelableInvalidation != null ? parcelableInvalidation.invalidation : null;
- }
-
- /**
- * Returns the isTransient flag from within an event, or {@code null} if not present.
- */
- public boolean getIsTransient() {
- boolean [] isTransient = parameters.getBooleanArray(Parameter.IS_TRANSIENT);
- return isTransient != null ? isTransient[0] : null;
- }
-
- /**
- * Returns the registration prefix from the event, or {@code null} if not present.
- */
- public byte [] getPrefix() {
- return parameters.getByteArray(Parameter.PREFIX);
- }
-
- /**
- * Returns the length of the registration prefix in bits or {@code -1} if not present.
- */
- public int getPrefixLength() {
- return parameters.getInt(Parameter.PREFIX_LENGTH, -1);
- }
-
- /**
- * Returns the registration state from an event message, or {@code null} if not present.
- */
- public RegistrationState getRegistrationState() {
- int ordinal = parameters.getInt(Parameter.REGISTRATION_STATE, -1);
- return ordinal < 0 ? null : RegistrationState.values()[ordinal];
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/InvalidationBinder.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/InvalidationBinder.java
deleted file mode 100644
index de6c02fc24b..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/InvalidationBinder.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android.service;
-
-import android.content.Context;
-import android.os.IBinder;
-
-/**
- * A service binder implementation for connecting to the {@link InvalidationService}.
- *
- */
-public class InvalidationBinder extends ServiceBinder<InvalidationService> {
-
- /**
- * Contains the name of the service implementation class that will be explicit bound to or
- * {@code null} if implicitly binding
- */
- private static String serviceClassName;
-
- static {
- try {
- // If the expected service class if found in the current application, use an explicit binding
- // otherwise an implicit, intent-based binding will be used. The latter capability is
- // generally only to support mock and test service bindings.
- Class<?> serviceClass =
- Class.forName("com.google.ipc.invalidation.ticl.android.AndroidInvalidationService");
- serviceClassName = serviceClass.getName();
- } catch (ClassNotFoundException e) {
- serviceClassName = null;
- }
- }
-
- /**
- * Constructs a new InvalidationBinder that connects to the invalidation service.
- */
- public InvalidationBinder(Context context) {
- super(context, Request.SERVICE_INTENT, InvalidationService.class, serviceClassName);
- }
-
- @Override
- protected InvalidationService asInterface(IBinder binder) {
- return InvalidationService.Stub.asInterface(binder);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/InvalidationService.aidl b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/InvalidationService.aidl
deleted file mode 100644
index 6cc37321af7..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/InvalidationService.aidl
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android.service;
-
-import android.os.Bundle;
-
-/**
- * Defines the bound service interface for the Invalidation service. The service exposes
- * an intent-like model with a single {@link #handleRrequest} entry point that packages the
- * action and its parameters into a {@link Bundle} but uses a synchronous calling model where
- * a response bundle is also returned to the client containing status and any result or
- * failure information.
- * <p>
- * Having a single entry point (as compared to a interface method per action with explicit
- * parameters) will make it easier to evolve the interface over time. New action types or
- * additional optional parameters can be added in subsequent versions without changing the
- * service interface in ways that would be incompatible with existing clients. This is
- * important because the service will be packaged (and updated) independently from clients
- * of the invalidation service.
- * <p>
- * The synchronous nature of the interface (having a response object that can indicate success
- * or failure of an action) is important to support reliable registrations. If a client
- * sends a registration request, it's important to know that it has been successfully received
- * by the local invalidation service.
- *
- * Before binding, the invalidation service should first ensure that the service is started by
- * calling the {@code Context#startService} with the {@link ServiceParameter#SERVICE_INTENT}.
- * The client can then bind to the service using {@code Context#bindService} with the same
- * intent. Clients should never explicitly stop the service; the service itself will decide
- * when it has successfully processed all requests from active clients and will stop itself.
- */
-interface InvalidationService {
-
- /**
- * Sends a request to the invalidation service and retrieves the response containing any
- * return data or status/error information. The {@code action} parameter in the request
- * bundle will indicate the type of request to be executed and the request parameters will
- * also be stored in the bundle. The service will acknowledge successful processing of
- * the request by returning a response bundle that contains a {@code status} parameter
- * indicating the success or failure of the request. If successful, any other output
- * parameters will be included as values in the response bundle. On failure, additional
- * error or debug information will be included in the response bundle.
- *
- * @see Request
- * @see Response
- */
- void handleRequest(in Bundle request, out Bundle response);
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ListenerBinder.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ListenerBinder.java
deleted file mode 100644
index ae371e5c213..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ListenerBinder.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android.service;
-
-import android.content.Context;
-import android.content.Intent;
-import android.os.IBinder;
-
-/**
- * A service binder for connecting to a client {@link ListenerService}.
- *
- */
-public class ListenerBinder extends ServiceBinder<ListenerService> {
-
- /**
- * Constructs a new ListenerBinder that connects to the ListenerService bound by the provided
- * intent. The intent should contain the component or class name of the target listener.
- */
- public ListenerBinder(Context context, Intent listenerIntent, String listenerClassName) {
- super(context, listenerIntent, ListenerService.class, listenerClassName);
- }
-
- @Override
- protected ListenerService asInterface(IBinder binder) {
- return ListenerService.Stub.asInterface(binder);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ListenerService.aidl b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ListenerService.aidl
deleted file mode 100644
index fdbbb89e84e..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ListenerService.aidl
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android.service;
-
-import android.os.Bundle;
-
-/**
- * Defines the bound service interface for an Invalidation listener service. The service
- * exposes an intent-like model with a single {@link #handleEvent} entry point that packages
- * the event action and its parameters into a {@link Bundle} but uses a synchronous calling
- * model where a response bundle is also returned to the service containing status and/or
- * <p>
- * Having a single entry point (as compared to a interface method per action with explicit
- * parameters) will make it easier to evolve the interface over time. New event types or
- * additional optional parameters can be added in subsequent versions without changing the
- * service interface in ways that would be incompatible with existing clients. This is
- * important because the listener services will be packaged (and updated) independently from
- * the invalidation service.
- * <p>
- * The synchronous nature of the interface (having a response object that can indicate success
- * or failure of event handling) is important to support reliable events. If the service
- * sends a registration request, it's important to know that it has been successfully received
- * by the local invalidation service.
- *
- * The invalidation service will bind to the invalidation listener using an intent that
- * contains the {@link Event.LISTENER} action along with the explicit listener class name
- * that was provided to {@code AndroidClientFactory.create()}.
- */
-interface ListenerService {
-
- /**
- * Sends a request to the invalidation service and retrieves the response containing any
- * return data or status/error information. The {@code action} parameter in the request
- * bundle will indicate the type of request to be executed and the request parameters will
- * also be stored in the bundle. The service will acknowledge successful processing of
- * the request by returning a response bundle that contains a {@code status} parameter
- * indicating the success or failure of the request. If successful, any other output
- * parameters will be included as values in the response bundle. On failure, additional
- * error or debug information will be included in the response bundle.
- *
- * @see Event
- * @see Response
- */
- void handleEvent(in Bundle event, out Bundle response);
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/Message.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/Message.java
deleted file mode 100644
index 6749a30e4eb..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/Message.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android.service;
-
-import com.google.ipc.invalidation.external.client.android.service.Request.Action;
-import com.google.ipc.invalidation.external.client.types.AckHandle;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-
-import android.accounts.Account;
-import android.os.Bundle;
-
-/**
- * A base class for message bundles sent to/from the invalidation service. This
- * class provides the declaration of the base parameter names, a basic builder
- * class for storing them in messages, and the accessor methods to read them.
- *
- */
-public abstract class Message {
- protected final Bundle parameters;
-
- /** The list of parameter names that are common across message types */
- public static class Parameter {
- protected Parameter() {} // can subclass but not instantiate
-
- public static final String ACTION = "action";
-
- public static final String ACCOUNT = "account";
-
- public static final String AUTH_TYPE = "authType";
-
- public static final String ACK_TOKEN = "ackToken";
-
- public static final String CLIENT = "client";
-
- public static final String OBJECT_ID = "objectId";
-
- /** A string value describing any error in processing */
- public static final String ERROR = "error";
- }
-
- /**
- * A base builder class for constructing new messages and populating
- * them with parameter values.
- *
- * @param <MessageType> the message type constructed by the builder
- * @param <BuilderType> the concrete builder subtype
- */
- protected abstract static class Builder<MessageType extends Message,
- BuilderType extends Builder<?, ?>> {
- protected final Bundle bundle;
-
- // Typed pointer to 'this' that's set once in constructor for return by setters,
- // to avoid unchecked warning suppression throughout the code
- private BuilderType thisInstance;
-
- @SuppressWarnings("unchecked")
- protected Builder(int actionOrdinal, Bundle b) {
- this.bundle = b;
- this.thisInstance = (BuilderType) this; // requires unchecked but is safe
- b.putInt(Parameter.ACTION, actionOrdinal);
- }
-
- /** Stores an account in the built parameters. */
- public BuilderType setAccount(Account account) {
- bundle.putParcelable(Parameter.ACCOUNT, account);
- return thisInstance;
- }
-
- /** Stores an acknowledgement handle in the built parameters. */
- public BuilderType setAckHandle(AckHandle ackHandle) {
- bundle.putByteArray(Parameter.ACK_TOKEN, ackHandle.getHandleData());
- return thisInstance;
- }
-
- /** Stores the authentication type in the built parameters */
- public BuilderType setAuthType(String authType) {
- bundle.putString(Parameter.AUTH_TYPE, authType);
- return thisInstance;
- }
-
- /** Stores a client key in the built parameters. */
- public BuilderType setClientKey(String clientKey) {
- bundle.putString(Parameter.CLIENT, clientKey);
- return thisInstance;
- }
-
-
- /** Stores an error message value within a response message.*/
- public BuilderType setError(String message) {
- bundle.putString(Parameter.ERROR, message);
- return thisInstance;
- }
-
- /** Stores an object ID in the built parameters. */
- public BuilderType setObjectId(ObjectId objectId) {
- bundle.putParcelable(Parameter.OBJECT_ID, new ParcelableObjectId(objectId));
- return thisInstance;
- }
-
- /**
- * Returns the message associated with the builder. Concrete subclasses
- * will override to return a concrete message instance.
- */
- public abstract MessageType build();
- }
-
- /**
- * Constructs a new message containing the the parameters in the provide bundle.
- */
- protected Message(Bundle bundle) {
- this.parameters = bundle;
- }
-
- /**
- * Returns the parameter bundle associated with the message.
- */
- public Bundle getBundle() {
- return parameters;
- }
-
- /**
- * Returns the action set on the message or {@code null} if not set. For
- * request or event messages, this will be the action associated with the
- * message. For response messages, it will be the action associated with the
- * original request or event that is being responded to.
- */
- public int getActionOrdinal() {
- return parameters.getInt(Parameter.ACTION);
- }
-
- /** Returns the account set on the message or {@code null} if not set. */
- public Account getAccount() {
- return parameters.getParcelable(Parameter.ACCOUNT);
- }
-
- /** Returns the acknowledgement handle set on the message or {@code null} if not set */
- public AckHandle getAckHandle() {
- byte [] tokenData = parameters.getByteArray(Parameter.ACK_TOKEN);
- return tokenData != null ? AckHandle.newInstance(tokenData) : null;
- }
-
- /** Returns the authentication type set on the message or {@code null} if not set */
- public String getAuthType() {
- return parameters.getString(Parameter.AUTH_TYPE);
- }
-
- /** Returns the client key set on the message or {@code null} if not set */
- public String getClientKey() {
- return parameters.getString(Parameter.CLIENT);
- }
-
- /**
- * Returns the error message string or {@code null} if not present.
- */
- public String getError() {
- return parameters.getString(Parameter.ERROR);
- }
-
- /** Returns the object id set on the message or {@code null} if not set */
- public ObjectId getObjectId() {
- ParcelableObjectId parcelableObjectId = parameters.getParcelable(Parameter.OBJECT_ID);
- return parcelableObjectId != null ? parcelableObjectId.objectId : null;
- }
-
- @Override
- public String toString() {
- String actionStr = (getActionOrdinal() < Action.values().length) ?
- Action.values()[getActionOrdinal()].toString() : "invalid";
- return "Message ACTION = " + actionStr + " CLIENT = " + getClientKey();
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ParcelableErrorInfo.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ParcelableErrorInfo.java
deleted file mode 100644
index 4d06e55acc6..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ParcelableErrorInfo.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android.service;
-
-import com.google.ipc.invalidation.external.client.types.ErrorInfo;
-
-import android.os.Parcel;
-import android.os.Parcelable;
-
-/**
- * Wraps an {link ErrorInfo} to enable writing to and reading from a
- * {@link Parcel}.
- */
-class ParcelableErrorInfo implements Parcelable {
- final ErrorInfo errorInfo;
-
- /**
- * Creator required by the Parcelable implementation conventions.
- */
- public static final Parcelable.Creator<ParcelableErrorInfo> CREATOR =
- new Parcelable.Creator<ParcelableErrorInfo>() {
- @Override
- public ParcelableErrorInfo createFromParcel(Parcel in) {
- return new ParcelableErrorInfo(in);
- }
-
- @Override
- public ParcelableErrorInfo[] newArray(int size) {
- return new ParcelableErrorInfo[size];
- }
- };
-
- /**
- * Creates a new wrapper around the provided error info.
- */
- ParcelableErrorInfo(ErrorInfo errorInfo) {
- this.errorInfo = errorInfo;
- }
-
- /**
- * Creates a new ErrorInfo wrapper by reading data from a parcel.
- */
- public ParcelableErrorInfo(Parcel in) {
- int reason = in.readInt();
- boolean isTransient = in.createBooleanArray()[0];
- String message = in.readString();
- this.errorInfo = ErrorInfo.newInstance(reason, isTransient, message, null);
- }
-
- @Override
- public int describeContents() {
- return 0; // no special contents
- }
-
- @Override
- public void writeToParcel(Parcel parcel, int flags) {
-
- // Data written to parcel is:
- // 1. int errorReason
- // 2. boolean [] { isTransient }
- // 3. String error message
- // TODO: Add support for object marshaling when needed
- parcel.writeInt(errorInfo.getErrorReason());
- parcel.writeBooleanArray(new boolean[]{errorInfo.isTransient()});
- parcel.writeString(errorInfo.getErrorMessage());
- }
-
- @Override
- public boolean equals(Object object) {
- return object instanceof ParcelableErrorInfo
- && errorInfo.equals(((ParcelableErrorInfo) object).errorInfo);
- }
-
- @Override
- public int hashCode() {
- return errorInfo.hashCode();
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ParcelableInvalidation.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ParcelableInvalidation.java
deleted file mode 100644
index da47e2c30ee..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ParcelableInvalidation.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android.service;
-
-import com.google.ipc.invalidation.external.client.types.Invalidation;
-
-import android.os.Parcel;
-import android.os.Parcelable;
-
-/**
- * Wraps an {link Invalidation} to enable writing to and reading from a
- * {@link Parcel}.
- */
-class ParcelableInvalidation implements Parcelable {
- final Invalidation invalidation;
- final boolean includePayload;
-
- /**
- * Creator required by the Parcelable implementation conventions.
- */
- public static final Parcelable.Creator<ParcelableInvalidation> CREATOR =
- new Parcelable.Creator<ParcelableInvalidation>() {
- @Override
- public ParcelableInvalidation createFromParcel(Parcel in) {
- return new ParcelableInvalidation(in);
- }
-
- @Override
- public ParcelableInvalidation[] newArray(int size) {
- return new ParcelableInvalidation[size];
- }
- };
-
- /**
- * Creates a new wrapper around the provided invalidation
- */
- ParcelableInvalidation(Invalidation invalidation, boolean includePayload) {
- this.invalidation = invalidation;
- this.includePayload = includePayload;
- }
-
- /**
- * Creates a new invalidation wrapper by reading data from a parcel.
- */
- public ParcelableInvalidation(Parcel in) {
- // Read parcelable object id from parcel using the application class loader
- ParcelableObjectId objectId = in.readParcelable(getClass().getClassLoader());
- long version = in.readLong();
- boolean isTrickleRestart = in.createBooleanArray()[0];
- boolean[] values = in.createBooleanArray();
- byte[] payload = null;
- if (values[0]) { // hasPayload
- payload = in.createByteArray();
- }
- this.invalidation = Invalidation.newInstance(objectId.objectId, version, payload,
- isTrickleRestart);
- this.includePayload = payload != null;
- }
-
- @Override
- public int describeContents() {
- return 0; // no special contents
- }
-
- @Override
- public void writeToParcel(Parcel parcel, int flags) {
-
- // Data written to parcel is:
- // 1. object id (as ParcelableObjectId)
- // 2. long version
- // 3. boolean [] { isTrickleRestart }
- // 4. boolean [] { hasPayload }
- // 5. byte array for payload (if hasPayload)
- parcel.writeParcelable(new ParcelableObjectId(invalidation.getObjectId()), 0);
- parcel.writeLong(invalidation.getVersion());
- parcel.writeBooleanArray(new boolean[] {invalidation.getIsTrickleRestartForInternalUse()});
- byte[] payload = invalidation.getPayload();
- if (includePayload && payload != null) {
- parcel.writeBooleanArray(new boolean[] {true});
- parcel.writeByteArray(payload);
- } else {
- parcel.writeBooleanArray(new boolean[] {false});
- }
- }
-
- @Override
- public boolean equals(Object object) {
- return object instanceof ParcelableInvalidation
- && invalidation.equals(((ParcelableInvalidation) object).invalidation);
- }
-
- @Override
- public int hashCode() {
- return invalidation.hashCode();
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ParcelableObjectId.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ParcelableObjectId.java
deleted file mode 100644
index e7da8211153..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ParcelableObjectId.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android.service;
-
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-
-import android.os.Parcel;
-import android.os.Parcelable;
-
-/**
- * Wraps an {link ObjectId} to enable writing to and reading from a
- * {@link Parcel}.
- */
-class ParcelableObjectId implements Parcelable {
- final ObjectId objectId;
-
- /**
- * Creator required by the Parcelable implementation conventions.
- */
- public static final Parcelable.Creator<ParcelableObjectId> CREATOR =
- new Parcelable.Creator<ParcelableObjectId>() {
- @Override
- public ParcelableObjectId createFromParcel(Parcel in) {
- return new ParcelableObjectId(in);
- }
-
- @Override
- public ParcelableObjectId[] newArray(int size) {
- return new ParcelableObjectId[size];
- }
- };
-
- /**
- * Creates a new wrapper around the provided object id.
- */
- ParcelableObjectId(ObjectId objectId) {
- this.objectId = objectId;
- }
-
- /**
- * Creates a new wrapper and object id by reading data from a parcel.
- */
- private ParcelableObjectId(Parcel in) {
- int source = in.readInt();
- byte[] value = in.createByteArray();
- objectId = ObjectId.newInstance(source, value);
- }
-
- @Override
- public int describeContents() {
- return 0; // no special contents
- }
-
- @Override
- public void writeToParcel(Parcel parcel, int flags) {
-
- // Data written to parcel is:
- // 1. numeric value of source type
- // 2. byte array for name
- parcel.writeInt(objectId.getSource());
- parcel.writeByteArray(objectId.getName());
- }
-
- @Override
- public boolean equals(Object object) {
- return object instanceof ParcelableObjectId
- && objectId.equals(((ParcelableObjectId) object).objectId);
- }
-
- @Override
- public int hashCode() {
- return objectId.hashCode();
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/Request.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/Request.java
deleted file mode 100644
index e6848439c0d..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/Request.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android.service;
-
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-
-import android.content.Intent;
-import android.os.Bundle;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-/**
- * Creates and interprets request message bundles sent to the invalidation
- * service from its application clients.
- *
- */
-public final class Request extends Message {
-
- /**
- * An intent that can be used to bind to the invalidation service.
- */
- public static final Intent SERVICE_INTENT = new Intent("com.google.ipc.invalidation.SERVICE");
-
- /**
- * Contains the list of request action names.
- */
- public static enum Action {
-
- /** Creates a new invalidation client instance */
- CREATE,
-
- /** Resumes an invalidation client instances */
- RESUME,
-
- /** Starts the invalidation client */
- START,
-
- /** Stops an invalidation client */
- STOP,
-
- /** Registers for invalidation notifications on an object */
- REGISTER,
-
- /** Unregisters for invalidation notifications on an object */
- UNREGISTER,
-
- /** Acknowledges an event recieved from the invalidations service */
- ACKNOWLEDGE,
-
- /** Destroys the client permanently */
- DESTROY;
- }
-
- /**
- * Contains the list of parameter names that are valid for request bundles
- */
- public static class Parameter extends Message.Parameter {
- private Parameter() {} // not instantiable
-
- /** Contains the integer client type */
- public static final String CLIENT_TYPE = "clientType";
-
- /** Contains an {@link Intent} value that can be used to bind for event delivery */
- public static final String INTENT = "intent";
-
- /** Contains an {@link ArrayList} of {@link ObjectId} instances */
- public static final String OBJECT_ID_LIST = "objectIdList";
- }
-
- /**
- * A builder class for constructing new request messages.
- *
- * @see #newBuilder
- */
- public static class Builder extends Message.Builder<Request, Builder> {
-
- // Constructed using newBuilder()
- private Builder(Action action) {
- super(action.ordinal(), new Bundle());
- }
-
- /**
- * Stores the client type within a request message.
- */
- public Builder setClientType(int clientType) {
- bundle.putInt(Parameter.CLIENT_TYPE, clientType);
- return this;
- }
-
- /**
- * Stores an intent within a request message.
- */
- public Builder setIntent(Intent eventIntent) {
- bundle.putParcelable(Parameter.INTENT, eventIntent);
- return this;
- }
-
-
- /** Stores a collection object IDs in the built parameters */
- public Builder setObjectIds(Collection<ObjectId> objectIds) {
- ArrayList<ParcelableObjectId> objectList =
- new ArrayList<ParcelableObjectId>(objectIds.size());
- for (ObjectId objectId : objectIds) {
- objectList.add(new ParcelableObjectId(objectId));
- }
- bundle.putParcelableArrayList(Parameter.OBJECT_ID_LIST, objectList);
- return this;
- }
-
- /**
- * Returns an event containing the set parameters.
- */
- @Override
- public Request build() {
- return new Request(bundle);
- }
- }
-
- /**
- * Constructs a new builder for a request associated with the provided action.
- */
- public static Builder newBuilder(Action action) {
- return new Builder(action);
- }
-
- /**
- * Constructs a new request using the contents of the provided parameter bundle.
- */
- public Request(Bundle bundle) {
- super(bundle);
- }
-
- /**
- * Returns the action from a request message.
- */
- public Action getAction() {
- return Action.values()[getActionOrdinal()];
- }
-
- /**
- * Returns the client type from a request message, or {@code -1} if not present.
- */
- public int getClientType() {
- return parameters.getInt(Parameter.CLIENT_TYPE, -1);
- }
-
- /**
- * Returns the intent from a request message, or {@code null} if not present.
- */
- public Intent getIntent() {
- return parameters.getParcelable(Parameter.INTENT);
- }
-
-
- /** Returns the object ID set on the message or {@code null} if not set */
- public Collection<ObjectId> getObjectIds() {
- List<ParcelableObjectId> parcelableObjectIds =
- parameters.getParcelableArrayList(Parameter.OBJECT_ID_LIST);
- if (parcelableObjectIds == null) {
- return null;
- }
- List<ObjectId> objectIds = new ArrayList<ObjectId>(parcelableObjectIds.size());
- for (ParcelableObjectId parcelableObjectId : parcelableObjectIds) {
- objectIds.add(parcelableObjectId.objectId);
- }
- return objectIds;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/Response.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/Response.java
deleted file mode 100644
index f189d0365cb..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/Response.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android.service;
-
-import android.os.Bundle;
-
-/**
- * Creates and interprets response message bundles returned by the invalidation
- * service or application clients in response to request or event messages.
- *
- */
-public final class Response extends Message {
- private static final AndroidLogger logger = AndroidLogger.forTag("Response");
-
- /** Contains the list of parameter names that are valid for response bundles. */
- public static class Parameter extends Message.Parameter {
- private Parameter() {} // not instantiable
-
- /**
- * An integer status code indicating success or failure.
- *
- * @see Status
- */
- public static final String STATUS = "status";
- }
-
- /** Defined values for the {@link Parameter#STATUS} parameter. */
- public static class Status {
- public static final int SUCCESS = 0;
- public static final int INVALID_CLIENT = 1;
- public static final int RUNTIME_ERROR = -1;
- public static final int UNKNOWN = -2;
- }
-
- /**
- * A builder class for constructing new response messages.
- *
- * @see #newBuilder
- */
- public static class Builder extends Message.Builder<Response, Builder> {
-
- // Instantiate using newBuilder()
- private Builder(int actionOrdinal, Bundle b) {
- super(actionOrdinal, b);
- }
-
- /**
- * Stores a status value within a response message.
- */
- public Builder setStatus(int status) {
- bundle.putInt(Parameter.STATUS, status);
- return this;
- }
-
- /**
- * Sets the status to {@link Status#RUNTIME_ERROR} and the error message to
- * the exception message within a response message.
- */
- public void setException(Exception exception) {
- if (exception instanceof AndroidClientException) {
- AndroidClientException ace = (AndroidClientException) exception;
- setStatus(ace.status);
- setError(ace.message);
- } else {
- setStatus(Status.RUNTIME_ERROR);
- setError(exception.getMessage());
- }
- }
-
- /**
- * Returns an response containing the set parameters.
- */
- @Override
- public Response build() {
- return new Response(bundle);
- }
- }
-
- /**
- * Constructs a new builder for a response associated with the provided action
- * that will store parameters into the provided bundle.
- */
- public static Builder newBuilder(int actionOrdinal, Bundle b) {
- return new Builder(actionOrdinal, b);
- }
-
- /**
- * Constructs a new response using the contents of the provided parameter bundle.
- */
- public Response(Bundle bundle) {
- super(bundle);
- }
-
- /**
- * Returns the status from a response message or {@link Status#UNKNOWN} if not
- * set by the callee (presumed failure).
- */
- public int getStatus() {
- return parameters.getInt(Parameter.STATUS, Status.UNKNOWN);
- }
-
- /**
- * Logs an error if the response message contains a status value other than
- * {@link Status#SUCCESS}.
- */
- public void warnOnFailure() {
- int status = getStatus();
- if (status != Status.SUCCESS) {
- String error = parameters.getString(Parameter.ERROR);
- if (error == null) {
- error = "Unexpected status value:" + status;
- }
- logger.warning("Error from AndroidInvalidationService: %s", error);
- }
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ServiceBinder.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ServiceBinder.java
deleted file mode 100644
index 4856cdc7e09..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ServiceBinder.java
+++ /dev/null
@@ -1,280 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android.service;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.ServiceConnection;
-import android.os.IBinder;
-
-import java.util.LinkedList;
-import java.util.Queue;
-
-
-/**
- * Abstract base class that assists in making connections to a bound service. Subclasses can define
- * a concrete binding to a particular bound service interface by binding to an explicit type on
- * declaration, providing a public constructor, and providing an implementation of the
- * {@link #asInterface} method.
- * <p>
- * This class has two main methods: {@link #runWhenBound} and {@link #release()}.
- * {@code runWhenBound} submits a {@code receiver} to be invoked once the service is bound,
- * initiating a bind if necessary. {@code release} releases the binding if one exists.
- * <p>
- * Interestingly, invocations of receivers passed to {@code runWhenBound} and calls to
- * {@code release} will be executed in program order. I.e., a call to runWhenBound followed by
- * a call to release will result in the receiver passed to runWhenBound being invoked before the
- * release, even if the binder had to wait for the service to be bound.
- * <p>
- * It is legal to call runWhenBound after a call to release.
- *
- * @param <BoundService> the bound service interface associated with the binder.
- *
- */
-public abstract class ServiceBinder<BoundService> {
- /**
- * Interface for a work unit to be executed when the service is bound.
- * @param <ServiceType> the bound service interface type
- */
- public interface BoundWork<ServiceType> {
- /** Function called with the bound service once the service is bound. */
- void run(ServiceType service);
- }
- /** Logger */
- private static final Logger logger = AndroidLogger.forTag("InvServiceBinder");
-
- /** Intent that can be used to bind to the service */
- private final Intent serviceIntent;
-
- /** Class that represents the bound service interface */
- private final Class<BoundService> serviceClass;
-
- /** Name of the component that implements the service interface. */
- private final String componentClassName;
-
- /** Work waiting to be run when the service becomes bound. */
- private final Queue<BoundWork<BoundService>> pendingWork =
- new LinkedList<BoundWork<BoundService>>();
-
- /** Used to synchronize. */
- private final Object lock = new Object();
-
- /** Bound service instance held by the binder or {@code null} if not bound. */
- private BoundService serviceInstance = null;
-
- /** Context to use when binding and unbinding. */
- private final Context context;
-
- /** Whether bindService has been called. */
- private boolean hasCalledBind = false;
-
- /** Whether we are currently executing an event from the queue. */
- private boolean queueHandlingInProgress = false;
-
- /** Number of times {@link #startBind()} has been called, for tests. */
- private int numStartBindForTest = 0;
-
- /**
- * Service connection implementation that handles connection/disconnection
- * events for the binder.
- */
- private final ServiceConnection serviceConnection = new ServiceConnection() {
-
- @Override
- public void onServiceConnected(ComponentName serviceName, IBinder binder) {
- logger.fine("onServiceConnected: %s", serviceName);
- synchronized (lock) {
- // Once the service is bound, save it and run any work that was waiting for it.
- serviceInstance = asInterface(binder);
- handleQueue();
- }
- }
-
- @Override
- public void onServiceDisconnected(ComponentName serviceName) {
- logger.fine("onServiceDisconnected: %s", serviceClass);
- synchronized (lock) {
- serviceInstance = null;
- }
- }
- };
-
- /**
- * Constructs a new ServiceBinder that uses the provided intent to bind to the service of the
- * specific type. Subclasses should expose a public constructor that passes the appropriate intent
- * and type into this constructor.
- *
- * @param context context to use for (un)binding.
- * @param serviceIntent intent that can be used to connect to the bound service.
- * @param serviceClass interface exposed by the bound service.
- * @param componentClassName name of component implementing the bound service. If non-null, then
- * an explicit binding to the named component within the same class is guaranteed.
- */
- protected ServiceBinder(Context context, Intent serviceIntent, Class<BoundService> serviceClass,
- String componentClassName) {
- this.context = Preconditions.checkNotNull(context);
- this.serviceIntent = Preconditions.checkNotNull(serviceIntent);
- this.serviceClass = Preconditions.checkNotNull(serviceClass);
- this.componentClassName = componentClassName;
- }
-
- /** Returns the intent used to bind to the service */
- public Intent getIntent() {
- Intent bindIntent;
- if (componentClassName == null) {
- return serviceIntent;
- }
- bindIntent = new Intent(serviceIntent);
- bindIntent.setClassName(context, componentClassName);
- return bindIntent;
- }
-
- /** Runs {@code receiver} when the service becomes bound. */
- public void runWhenBound(BoundWork<BoundService> receiver) {
- synchronized (lock) {
- pendingWork.add(receiver);
- handleQueue();
- }
- }
-
- /** Unbinds the service associated with the binder. No-op if not bound. */
- public void release() {
- synchronized (lock) {
- if (!hasCalledBind) {
- logger.fine("Release is a no-op since not bound: %s", serviceClass);
- return;
- }
- // We need to release using a runWhenBound to avoid having a release jump ahead of
- // pending work waiting for a bind (i.e., to preserve program order).
- runWhenBound(new BoundWork<BoundService>() {
- @Override
- public void run(BoundService ignored) {
- synchronized (lock) {
- // Do the unbind.
- logger.fine("Unbinding %s from %s", serviceClass, serviceInstance);
- try {
- context.unbindService(serviceConnection);
- } catch (IllegalArgumentException exception) {
- logger.fine("Exception unbinding from %s: %s", serviceClass,
- exception.getMessage());
- }
- // Clear the now-stale reference and reset hasCalledBind so that we will initiate a
- // bind on a subsequent call to runWhenBound.
- serviceInstance = null;
- hasCalledBind = false;
-
- // This isn't necessarily wrong, but it's slightly odd.
- if (!pendingWork.isEmpty()) {
- logger.info("Still have %s work items in release of %s", pendingWork.size(),
- serviceClass);
- }
- }
- }
- });
- }
- }
-
- /**
- * Returns {@code true} if the service binder is currently connected to the
- * bound service.
- */
- public boolean isBoundForTest() {
- synchronized (lock) {
- return hasCalledBind;
- }
- }
-
- @Override
- public String toString() {
- synchronized (lock) {
- return this.getClass().getSimpleName() + "[" + serviceIntent + "]";
- }
- }
-
- /** Returns the number of times {@code startBind} has been called, for tests. */
- public int getNumStartBindForTest() {
- return numStartBindForTest;
- }
-
- /**
- * Recursively process the queue of {@link #pendingWork}. Initiates a bind to the service if
- * required. Else, if the service instance is available, removes the head of the queue and invokes
- * it with the service instance.
- * <p>
- * Note: this function differs from {@link #runWhenBound} only in that {@code runWhenBound}
- * enqueues into {@link #pendingWork}.
- */
- private void handleQueue() {
- if (queueHandlingInProgress) {
- // Someone called back into runWhenBound from receiver.accept. We don't want to start another
- // recursive call, since we're already handling the queue.
- return;
- }
- if (pendingWork.isEmpty()) {
- // Recursive base case.
- return;
- }
- if (!hasCalledBind) {
- // Initiate a bind if not bound.
- Preconditions.checkState(serviceInstance == null,
- "Bind not called but service instance is set: %s", serviceClass);
-
- // May fail, but does its own logging. If it fails, we will never dispatch the work in the
- // queue, but it's unclear what we can do in this case other than log.
- startBind();
- return;
- }
- if (serviceInstance == null) {
- // Wait for the service to become bound if it is not yet available and a bind is in progress.
- Preconditions.checkState(hasCalledBind, "No service instance and not waiting for bind: %s",
- serviceClass);
- return;
- }
-
- // Service is bound and available. Remove and invoke the head of the queue, then recurse to
- // process the rest. We recurse because the head of the queue may have been a release(), which
- // would have unbound the service, and we would need to reinvoke the binding code.
- BoundWork<BoundService> work = pendingWork.remove();
- queueHandlingInProgress = true;
- work.run(serviceInstance);
- queueHandlingInProgress = false;
- handleQueue();
- }
-
- /**
- * Binds to the service associated with the binder within the provided context. Returns whether
- * binding was successfully initiated.
- */
- private boolean startBind() {
- Preconditions.checkState(!hasCalledBind, "Bind already called for %s", serviceClass);
- ++numStartBindForTest;
- Intent bindIntent = getIntent();
- if (!context.bindService(bindIntent, serviceConnection, Context.BIND_AUTO_CREATE)) {
- logger.severe("Unable to bind to service: %s", bindIntent);
- return false;
- }
- hasCalledBind = true;
- return true;
- }
-
- /** Returns a bound service stub of the expected type. */
- protected abstract BoundService asInterface(IBinder binder);
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android2/AndroidClientFactory.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android2/AndroidClientFactory.java
deleted file mode 100644
index d4cd3d83d10..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android2/AndroidClientFactory.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.android2;
-
-import com.google.ipc.invalidation.ticl.InvalidationClientCore;
-import com.google.ipc.invalidation.ticl.android2.AndroidTiclManifest;
-import com.google.ipc.invalidation.ticl.android2.ProtocolIntents;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientConfigP;
-import com.google.protos.ipc.invalidation.Types.ClientType;
-
-import android.content.Context;
-import android.content.Intent;
-
-/**
- * Factory for creating Android clients.
- *
- */
-public final class AndroidClientFactory {
- /**
- * Creates a new client.
- * <p>
- * REQUIRES: no client exist, or a client exists with the same type and name as provided. In
- * the latter case, this call is a no-op.
- *
- * @param context Android system context
- * @param clientType type of the client to create
- * @param clientName name of the client to create
- */
- public static void createClient(Context context, ClientType.Type clientType, byte[] clientName) {
- ClientConfigP config = InvalidationClientCore.createConfig().build();
- Intent intent = ProtocolIntents.InternalDowncalls.newCreateClientIntent(
- clientType.getNumber(), clientName, config, false);
- intent.setClassName(context, new AndroidTiclManifest(context).getTiclServiceClass());
- context.startService(intent);
- }
-
- private AndroidClientFactory() {
- // Disallow instantiation.
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android2/AndroidManifest.xml b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android2/AndroidManifest.xml
deleted file mode 100644
index 840c41f8e8a..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android2/AndroidManifest.xml
+++ /dev/null
@@ -1,58 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
- <!-- Copyright 2011 Google Inc. All Rights Reserved. -->
- <!-- Common configuration settings for application using client invalidation library. -->
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.google.ipc.invalidation.client.android2">
-
- <!-- App receives GCM messages. -->
- <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
- <!-- GCM connects to Google Services. -->
- <uses-permission android:name="android.permission.INTERNET" />
- <!-- GCM requires a Google account. -->
- <uses-permission android:name="android.permission.GET_ACCOUNTS" />
- <uses-permission android:name="android.permission.USE_CREDENTIALS" />
- <!-- Keeps the processor from sleeping when a message is received. -->
- <uses-permission android:name="android.permission.WAKE_LOCK" />
-
- <application>
- <!-- Ticl service. -->
- <service android:exported="false"
- android:name="com.google.ipc.invalidation.ticl.android2.TiclService"/>
-
- <!-- Ticl sender. -->
- <service android:exported="false"
- android:name="com.google.ipc.invalidation.ticl.android2.channel.AndroidMessageSenderService"/>
-
- <!-- Receiver for scheduler alarms. -->
- <receiver android:exported="false"
- android:name="com.google.ipc.invalidation.ticl.android2.AndroidInternalScheduler$AlarmReceiver"/>
-
- <!-- GCM Broadcast Receiver -->
- <receiver android:exported="true"
- android:name="com.google.ipc.invalidation.external.client.contrib.MultiplexingGcmListener$GCMReceiver"
- android:permission="com.google.android.c2dm.permission.SEND">
- <intent-filter>
- <action android:name="com.google.android.c2dm.intent.RECEIVE" />
- <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
- <category android:name="com.google.ipc.invalidation.ticl.android2" />
- </intent-filter>
- </receiver>
-
- <!-- GCM multiplexer -->
- <service android:exported="false"
- android:name="com.google.ipc.invalidation.external.client.contrib.MultiplexingGcmListener">
- <meta-data android:name="sender_ids" android:value="ipc.invalidation@gmail.com"/>
- </service>
-
- <!-- Invalidation service multiplexed GCM receiver -->
- <service android:exported="false"
- android:name="com.google.ipc.invalidation.ticl.android2.channel.AndroidMessageReceiverService"
- android:enabled="true"/>
- <receiver android:exported="false"
- android:name="com.google.ipc.invalidation.ticl.android2.channel.AndroidMessageReceiverService$Receiver">
- <intent-filter>
- <action android:name="com.google.ipc.invalidation.gcmmplex.EVENT" />
- </intent-filter>
- </receiver>
- </application>
-</manifest>
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListener.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListener.java
deleted file mode 100644
index 72e56a3753d..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListener.java
+++ /dev/null
@@ -1,598 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.contrib;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.InvalidationClient;
-import com.google.ipc.invalidation.external.client.InvalidationListener;
-import com.google.ipc.invalidation.external.client.InvalidationListener.RegistrationState;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.external.client.types.AckHandle;
-import com.google.ipc.invalidation.external.client.types.ErrorInfo;
-import com.google.ipc.invalidation.external.client.types.Invalidation;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-import com.google.ipc.invalidation.ticl.ProtoConverter;
-import com.google.ipc.invalidation.ticl.android2.AndroidClock;
-import com.google.ipc.invalidation.ticl.android2.AndroidInvalidationListenerIntentMapper;
-import com.google.ipc.invalidation.ticl.android2.ProtocolIntents;
-import com.google.ipc.invalidation.ticl.android2.channel.AndroidChannelConstants.AuthTokenConstants;
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protos.ipc.invalidation.AndroidListenerProtocol;
-import com.google.protos.ipc.invalidation.AndroidListenerProtocol.RegistrationCommand;
-import com.google.protos.ipc.invalidation.AndroidListenerProtocol.StartCommand;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientConfigP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ObjectIdP;
-
-import android.app.IntentService;
-import android.app.PendingIntent;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-
-import java.util.concurrent.TimeUnit;
-
-
-/**
- * Simplified listener contract for Android clients. Takes care of exponential back-off when
- * register or unregister are called for an object after a failure has occurred. Also suppresses
- * redundant register requests.
- *
- * <p>A sample implementation of an {@link AndroidListener} is shown below:
- *
- * <p><code>
- * class ExampleListener extends AndroidListener {
- * @Override
- * public void reissueRegistrations(byte[] clientId) {
- * List<ObjectId> desiredRegistrations = ...;
- * register(clientId, desiredRegistrations);
- * }
- *
- * @Override
- * public void invalidate(Invalidation invalidation, final byte[] ackHandle) {
- * // Track the most recent version of the object (application-specific) and then acknowledge
- * // the invalidation.
- * ...
- * acknowledge(ackHandle);
- * }
- *
- * @Override
- * public void informRegistrationFailure(byte[] clientId, ObjectId objectId,
- * boolean isTransient, String errorMessage) {
- * // Try again if there is a transient failure and we still care whether the object is
- * // registered or not.
- * if (isTransient) {
- * boolean shouldRetry = ...;
- * if (shouldRetry) {
- * boolean shouldBeRegistered = ...;
- * if (shouldBeRegistered) {
- * register(clientId, ImmutableList.of(objectId));
- * } else {
- * unregister(clientId, ImmutableList.of(objectId));
- * }
- * }
- * }
- * }
- *
- * ...
- * }
- * </code>
- *
- * <p>See {@link com.google.ipc.invalidation.examples.android2} for a complete sample.
- *
- */
-public abstract class AndroidListener extends IntentService {
-
- /** External alarm receiver that allows the listener to respond to alarm intents. */
- public static final class AlarmReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- Preconditions.checkNotNull(context);
- Preconditions.checkNotNull(intent);
- if (intent.hasExtra(AndroidListenerIntents.EXTRA_REGISTRATION)) {
- AndroidListenerIntents.issueAndroidListenerIntent(context, intent);
- }
- }
- }
-
- /** The logger. */
- private static final Logger logger = AndroidLogger.forPrefix("");
-
- /** Initial retry delay for exponential backoff (1 minute). */
-
- static int initialMaxDelayMs = (int) TimeUnit.SECONDS.toMillis(60);
-
- /** Maximum delay factor for exponential backoff (6 hours). */
-
- static int maxDelayFactor = 6 * 60;
-
- /** The last client ID passed to the ready up-call. */
-
- static byte[] lastClientIdForTest;
-
- /**
- * Invalidation listener implementation. We implement the interface on a private field rather
- * than directly to avoid leaking methods that should not be directly called by the client
- * application. The listener must be called only on intent service thread.
- */
- private final InvalidationListener invalidationListener = new InvalidationListener() {
- @Override
- public final void ready(final InvalidationClient client) {
- byte[] clientId = state.getClientId().toByteArray();
- AndroidListener.lastClientIdForTest = clientId;
- AndroidListener.this.ready(clientId);
- }
-
- @Override
- public final void reissueRegistrations(final InvalidationClient client, byte[] prefix,
- int prefixLength) {
- AndroidListener.this.reissueRegistrations(state.getClientId().toByteArray());
- }
-
- @Override
- public final void informRegistrationStatus(final InvalidationClient client,
- final ObjectId objectId, final RegistrationState regState) {
- state.informRegistrationSuccess(objectId);
- AndroidListener.this.informRegistrationStatus(state.getClientId().toByteArray(),
- objectId, regState);
- }
-
- @Override
- public final void informRegistrationFailure(final InvalidationClient client,
- final ObjectId objectId, final boolean isTransient, final String errorMessage) {
- state.informRegistrationFailure(objectId, isTransient);
- AndroidListener.this.informRegistrationFailure(state.getClientId().toByteArray(), objectId,
- isTransient, errorMessage);
- }
-
- @Override
- public void invalidate(InvalidationClient client, Invalidation invalidation,
- AckHandle ackHandle) {
- AndroidListener.this.invalidate(invalidation, ackHandle.getHandleData());
- }
-
- @Override
- public void invalidateUnknownVersion(InvalidationClient client, ObjectId objectId,
- AckHandle ackHandle) {
- AndroidListener.this.invalidateUnknownVersion(objectId, ackHandle.getHandleData());
- }
-
- @Override
- public void invalidateAll(InvalidationClient client, AckHandle ackHandle) {
- AndroidListener.this.invalidateAll(ackHandle.getHandleData());
- }
-
- @Override
- public void informError(InvalidationClient client, ErrorInfo errorInfo) {
- AndroidListener.this.informError(errorInfo);
- }
- };
-
- /**
- * The internal state of the listener. Lazy initialization, triggered by {@link #onHandleIntent}.
- */
- private AndroidListenerState state;
-
- /** The clock to use when scheduling retry call-backs. */
- private final AndroidClock clock = new AndroidClock.SystemClock();
-
- /**
- * The mapper used to route intents to the invalidation listener. Lazy initialization triggered
- * by {@link #onCreate}.
- */
- private AndroidInvalidationListenerIntentMapper intentMapper;
-
- /** Initializes {@link AndroidListener}. */
- protected AndroidListener() {
- super("");
-
- // If the process dies before an intent is handled, setIntentRedelivery(true) ensures that the
- // last intent is redelivered. This optimization is not necessary for correctness: on restart,
- // all registrations will be reissued and unacked invalidations will be resent anyways.
- setIntentRedelivery(true);
- }
-
- /** See specs for {@link InvalidationClient#start}. */
- public static Intent createStartIntent(Context context, int clientType, byte[] clientName) {
- Preconditions.checkNotNull(context);
- Preconditions.checkNotNull(clientName);
-
- return AndroidListenerIntents.createStartIntent(context, clientType, clientName);
- }
-
- /** See specs for {@link InvalidationClient#stop}. */
- public static Intent createStopIntent(Context context) {
- Preconditions.checkNotNull(context);
-
- return AndroidListenerIntents.createStopIntent(context);
- }
-
- /**
- * See specs for {@link InvalidationClient#register}.
- *
- * @param context the context
- * @param clientId identifier for the client service for which we are registering
- * @param objectIds the object ids being registered
- */
- public static Intent createRegisterIntent(Context context, byte[] clientId,
- Iterable<ObjectId> objectIds) {
- Preconditions.checkNotNull(context);
- Preconditions.checkNotNull(clientId);
- Preconditions.checkNotNull(objectIds);
-
- final boolean isRegister = true;
- return AndroidListenerIntents.createRegistrationIntent(context, clientId, objectIds,
- isRegister);
- }
-
- /**
- * See specs for {@link InvalidationClient#register}.
- *
- * @param clientId identifier for the client service for which we are registering
- * @param objectIds the object ids being registered
- */
- public void register(byte[] clientId, Iterable<ObjectId> objectIds) {
- Preconditions.checkNotNull(clientId);
- Preconditions.checkNotNull(objectIds);
-
- Context context = getApplicationContext();
- context.startService(createRegisterIntent(context, clientId, objectIds));
- }
-
- /**
- * See specs for {@link InvalidationClient#unregister}.
- *
- * @param context the context
- * @param clientId identifier for the client service for which we are unregistering
- * @param objectIds the object ids being unregistered
- */
- public static Intent createUnregisterIntent(Context context, byte[] clientId,
- Iterable<ObjectId> objectIds) {
- Preconditions.checkNotNull(context);
- Preconditions.checkNotNull(clientId);
- Preconditions.checkNotNull(objectIds);
-
- final boolean isRegister = false;
- return AndroidListenerIntents.createRegistrationIntent(context, clientId, objectIds,
- isRegister);
- }
-
- /**
- * Sets the authorization token and type used by the invalidation client. Call in response to
- * {@link #requestAuthToken} calls.
- *
- * @param pendingIntent pending intent passed to {@link #requestAuthToken}
- * @param authToken authorization token
- * @param authType authorization token typo
- */
- public static void setAuthToken(Context context, PendingIntent pendingIntent, String authToken,
- String authType) {
- Preconditions.checkNotNull(pendingIntent);
- Preconditions.checkNotNull(authToken);
- Preconditions.checkNotNull(authType);
-
- AndroidListenerIntents.issueAuthTokenResponse(context, pendingIntent, authToken, authType);
- }
-
- /**
- * See specs for {@link InvalidationClient#unregister}.
- *
- * @param clientId identifier for the client service for which we are registering
- * @param objectIds the object ids being unregistered
- */
- public void unregister(byte[] clientId, Iterable<ObjectId> objectIds) {
- Preconditions.checkNotNull(clientId);
- Preconditions.checkNotNull(objectIds);
-
- Context context = getApplicationContext();
- context.startService(createUnregisterIntent(context, clientId, objectIds));
- }
-
- /** See specs for {@link InvalidationClient#acknowledge}. */
- public static Intent createAcknowledgeIntent(Context context, byte[] ackHandle) {
- Preconditions.checkNotNull(context);
- Preconditions.checkNotNull(ackHandle);
-
- return AndroidListenerIntents.createAckIntent(context, ackHandle);
- }
-
- /** See specs for {@link InvalidationClient#acknowledge}. */
- public void acknowledge(byte[] ackHandle) {
- Preconditions.checkNotNull(ackHandle);
-
- Context context = getApplicationContext();
- context.startService(createAcknowledgeIntent(context, ackHandle));
- }
-
- /**
- * See specs for {@link InvalidationListener#ready}.
- *
- * @param clientId the client identifier that must be passed to {@link #createRegisterIntent}
- * and {@link #createUnregisterIntent}
- */
- public abstract void ready(byte[] clientId);
-
- /**
- * See specs for {@link InvalidationListener#reissueRegistrations}.
- *
- * @param clientId the client identifier that must be passed to {@link #createRegisterIntent}
- * and {@link #createUnregisterIntent}
- */
- public abstract void reissueRegistrations(byte[] clientId);
-
- /**
- * See specs for {@link InvalidationListener#informError}.
- */
- public abstract void informError(ErrorInfo errorInfo);
-
- /**
- * See specs for {@link InvalidationListener#invalidate}.
- *
- * @param invalidation the invalidation
- * @param ackHandle event acknowledgment handle
- */
- public abstract void invalidate(Invalidation invalidation, byte[] ackHandle);
-
- /**
- * See specs for {@link InvalidationListener#invalidateUnknownVersion}.
- *
- * @param objectId identifier for the object with unknown version
- * @param ackHandle event acknowledgment handle
- */
- public abstract void invalidateUnknownVersion(ObjectId objectId, byte[] ackHandle);
-
- /**
- * See specs for {@link InvalidationListener#invalidateAll}.
- *
- * @param ackHandle event acknowledgment handle
- */
- public abstract void invalidateAll(byte[] ackHandle);
-
- /**
- * Read listener state.
- *
- * @return serialized state or {@code null} if it is not available
- */
- public abstract byte[] readState();
-
- /** Write listener state to some location. */
- public abstract void writeState(byte[] data);
-
- /**
- * See specs for {@link InvalidationListener#informRegistrationFailure}.
- */
- public abstract void informRegistrationFailure(byte[] clientId, ObjectId objectId,
- boolean isTransient, String errorMessage);
-
- /**
- * See specs for (@link InvalidationListener#informRegistrationStatus}.
- */
- public abstract void informRegistrationStatus(byte[] clientId, ObjectId objectId,
- RegistrationState regState);
-
- /**
- * Called when an authorization token is needed. Respond by calling {@link #setAuthToken}.
- *
- * @param pendingIntent pending intent that must be used in {@link #setAuthToken} response.
- * @param invalidAuthToken the existing invalid token or null if none exists. Implementation
- * should invalidate the token.
- */
- public abstract void requestAuthToken(PendingIntent pendingIntent,
- String invalidAuthToken);
-
- @Override
- public void onCreate() {
- super.onCreate();
-
- // Initialize the intent mapper (now that context is available).
- intentMapper = new AndroidInvalidationListenerIntentMapper(invalidationListener, this);
- }
-
- @Override
- protected void onHandleIntent(Intent intent) {
- if (intent == null) {
- return;
- }
-
- // We lazily initialize state in calls to onHandleIntent rather than initializing in onCreate
- // because onCreate runs on the UI thread and initializeState performs I/O.
- if (state == null) {
- initializeState();
- }
-
- // Handle any intents specific to the AndroidListener. For other intents, defer to the
- // intentMapper, which handles listener upcalls corresponding to the InvalidationListener
- // methods.
- if (!tryHandleAuthTokenRequestIntent(intent) &&
- !tryHandleRegistrationIntent(intent) &&
- !tryHandleStartIntent(intent) &&
- !tryHandleStopIntent(intent) &&
- !tryHandleAckIntent(intent)) {
- intentMapper.handleIntent(intent);
- }
-
- // Always check to see if we need to persist state changes after handling an intent.
- if (state.getIsDirty()) {
- writeState(state.marshal().toByteArray());
- state.resetIsDirty();
- }
- }
-
- /** Returns invalidation client that can be used to trigger intents against the TICL service. */
- private InvalidationClient getClient() {
- return intentMapper.client;
- }
-
- /**
- * Initializes listener state either from persistent proto (if available) or from scratch.
- */
- private void initializeState() {
- AndroidListenerProtocol.AndroidListenerState proto = getPersistentState();
- if (proto != null) {
- state = new AndroidListenerState(initialMaxDelayMs, maxDelayFactor, proto);
- } else {
- state = new AndroidListenerState(initialMaxDelayMs, maxDelayFactor);
- }
- }
-
- /**
- * Reads and parses persistent state for the listener. Returns {@code null} if the state does not
- * exist or is invalid.
- */
- private AndroidListenerProtocol.AndroidListenerState getPersistentState() {
- // Defer to application code to read the blob containing the state proto.
- byte[] stateData = readState();
- try {
- if (null != stateData) {
- AndroidListenerProtocol.AndroidListenerState state =
- AndroidListenerProtocol.AndroidListenerState.parseFrom(stateData);
- if (!AndroidListenerProtos.isValidAndroidListenerState(state)) {
- logger.warning("Invalid listener state.");
- return null;
- }
- return state;
- }
- } catch (InvalidProtocolBufferException exception) {
- logger.warning("Failed to parse listener state: %s", exception);
- }
- return null;
- }
-
- /**
- * Tries to handle a request for an authorization token. Returns {@code true} iff the intent is
- * an auth token request.
- */
- private boolean tryHandleAuthTokenRequestIntent(Intent intent) {
- if (!AndroidListenerIntents.isAuthTokenRequest(intent)) {
- return false;
- }
- Context context = getApplicationContext();
-
- // Check for invalid auth token. Subclass may have to invalidate it if it exists in the call
- // to getNewAuthToken.
- String invalidAuthToken = intent.getStringExtra(
- AuthTokenConstants.EXTRA_INVALIDATE_AUTH_TOKEN);
- // Intent also includes a pending intent that we can use to pass back our response.
- PendingIntent pendingIntent = intent.getParcelableExtra(
- AuthTokenConstants.EXTRA_PENDING_INTENT);
- if (pendingIntent == null) {
- logger.warning("Authorization request without pending intent extra.");
- } else {
- // Delegate to client application to figure out what the new token should be and the auth
- // type.
- requestAuthToken(pendingIntent, invalidAuthToken);
- }
- return true;
- }
-
- /** Tries to handle a stop intent. Returns {@code true} iff the intent is a stop intent. */
- private boolean tryHandleStopIntent(Intent intent) {
- if (!AndroidListenerIntents.isStopIntent(intent)) {
- return false;
- }
- getClient().stop();
- return true;
- }
-
- /**
- * Tries to handle a registration intent. Returns {@code true} iff the intent is a registration
- * intent.
- */
- private boolean tryHandleRegistrationIntent(Intent intent) {
- RegistrationCommand command = AndroidListenerIntents.findRegistrationCommand(intent);
- if ((command == null) || !AndroidListenerProtos.isValidRegistrationCommand(command)) {
- return false;
- }
- // Make sure the registration is intended for this client. If not, we ignore it (suggests
- // there is a new client now).
- if (!command.getClientId().equals(state.getClientId())) {
- logger.warning("Ignoring registration request for old client. Old ID = {0}, New ID = {1}",
- command.getClientId(), state.getClientId());
- return true;
- }
- boolean isRegister = command.getIsRegister();
- for (ObjectIdP objectIdP : command.getObjectIdList()) {
- ObjectId objectId = ProtoConverter.convertFromObjectIdProto(objectIdP);
- // We may need to delay the registration command (if it is not already delayed).
- int delayMs = 0;
- if (!command.getIsDelayed()) {
- delayMs = state.getNextDelay(objectId);
- }
- if (delayMs == 0) {
- issueRegistration(objectId, isRegister);
- } else {
- AndroidListenerIntents.issueDelayedRegistrationIntent(getApplicationContext(), clock,
- state.getClientId(), objectId, isRegister, delayMs, state.getNextRequestCode());
- }
- }
- return true;
- }
-
- /**
- * Called when the client application requests a new registration. If a redundant register request
- * is made -- i.e. when the application attempts to register an object that is already in the
- * {@code AndroidListenerState#desiredRegistrations} collection -- the method returns immediately.
- * Unregister requests are never ignored since we can't reliably determine whether an unregister
- * request is redundant: our policy on failures of any kind is to remove the registration from
- * the {@code AndroidListenerState#desiredRegistrations} collection.
- */
- private void issueRegistration(ObjectId objectId, boolean isRegister) {
- if (isRegister) {
- if (state.addDesiredRegistration(objectId)) {
- // Don't bother if we think it's already registered. Note that we remove the object from the
- // collection when there is a failure.
- getClient().register(objectId);
- }
- } else {
- // Remove the object ID from the desired registration collection so that subsequent attempts
- // to re-register are not ignored.
- state.removeDesiredRegistration(objectId);
- getClient().unregister(objectId);
- }
- }
-
- /** Tries to handle a start intent. Returns {@code true} iff the intent is a start intent. */
- private boolean tryHandleStartIntent(Intent intent) {
- StartCommand command = AndroidListenerIntents.findStartCommand(intent);
- if ((command == null) || !AndroidListenerProtos.isValidStartCommand(command)) {
- return false;
- }
- // Reset the state so that we make no assumptions about desired registrations and can ignore
- // messages directed at the wrong instance.
- state = new AndroidListenerState(initialMaxDelayMs, maxDelayFactor);
- boolean skipStartForTest = false;
- Intent startIntent = ProtocolIntents.InternalDowncalls.newCreateClientIntent(
- command.getClientType(), command.getClientName().toByteArray(),
- ClientConfigP.getDefaultInstance(), skipStartForTest);
- AndroidListenerIntents.issueTiclIntent(getApplicationContext(), startIntent);
- return true;
- }
-
- /** Tries to handle an ack intent. Returns {@code true} iff the intent is an ack intent. */
- private boolean tryHandleAckIntent(Intent intent) {
- byte[] data = AndroidListenerIntents.findAckHandle(intent);
- if (data == null) {
- return false;
- }
- getClient().acknowledge(AckHandle.newInstance(data));
- return true;
- }
-
- /** Returns the current state of the listener, for tests. */
- AndroidListenerState getStateForTest() {
- return state;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerIntents.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerIntents.java
deleted file mode 100644
index bd66ae53aa8..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerIntents.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.contrib;
-
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.external.client.contrib.AndroidListener.AlarmReceiver;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-import com.google.ipc.invalidation.ticl.android2.AndroidClock;
-import com.google.ipc.invalidation.ticl.android2.AndroidTiclManifest;
-import com.google.ipc.invalidation.ticl.android2.channel.AndroidChannelConstants.AuthTokenConstants;
-import com.google.protobuf.ByteString;
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protos.ipc.invalidation.AndroidListenerProtocol.RegistrationCommand;
-import com.google.protos.ipc.invalidation.AndroidListenerProtocol.StartCommand;
-
-import android.app.AlarmManager;
-import android.app.PendingIntent;
-import android.app.PendingIntent.CanceledException;
-import android.content.Context;
-import android.content.Intent;
-
-
-/**
- * Static helper class supporting construction and decoding of intents issued and handled by the
- * {@link AndroidListener}.
- *
- */
-class AndroidListenerIntents {
-
- /** The logger. */
- private static final Logger logger = AndroidLogger.forPrefix("");
-
- /** Key of Intent byte[] holding a {@link RegistrationCommand} protocol buffer. */
- static final String EXTRA_REGISTRATION =
- "com.google.ipc.invalidation.android_listener.REGISTRATION";
-
- /** Key of Intent byte[] holding a {@link StartCommand} protocol buffer. */
- static final String EXTRA_START =
- "com.google.ipc.invalidation.android_listener.START";
-
- /** Key of Intent extra indicating that the client should stop. */
- static final String EXTRA_STOP =
- "com.google.ipc.invalidation.android_listener.STOP";
-
- /** Key of Intent extra holding a byte[] that is ack handle data. */
- static final String EXTRA_ACK =
- "com.google.ipc.invalidation.android_listener.ACK";
-
- /**
- * Issues the given {@code intent} to the TICL service class registered in the {@code context}.
- */
- static void issueTiclIntent(Context context, Intent intent) {
- context.startService(intent.setClassName(context,
- new AndroidTiclManifest(context).getTiclServiceClass()));
- }
-
- /**
- * Issues the given {@code intent} to the {@link AndroidListener} class registered in the
- * {@code context}.
- */
- static void issueAndroidListenerIntent(Context context, Intent intent) {
- context.startService(setAndroidListenerClass(context, intent));
- }
-
- /**
- * Returns the ack handle from the given intent if it has the appropriate extra. Otherwise,
- * returns {@code null}.
- */
- static byte[] findAckHandle(Intent intent) {
- return intent.getByteArrayExtra(EXTRA_ACK);
- }
-
- /**
- * Returns {@link RegistrationCommand} extra from the given intent or null if no valid
- * registration command exists.
- */
- static RegistrationCommand findRegistrationCommand(Intent intent) {
- // Check that the extra exists.
- byte[] data = intent.getByteArrayExtra(EXTRA_REGISTRATION);
- if (null == data) {
- return null;
- }
-
- // Attempt to parse the extra.
- try {
- return RegistrationCommand.parseFrom(data);
- } catch (InvalidProtocolBufferException exception) {
- logger.warning("Received invalid proto: %s", exception);
- return null;
- }
- }
-
- /**
- * Returns {@link StartCommand} extra from the given intent or null if no valid start command
- * exists.
- */
- static StartCommand findStartCommand(Intent intent) {
- // Check that the extra exists.
- byte[] data = intent.getByteArrayExtra(EXTRA_START);
- if (null == data) {
- return null;
- }
-
- // Attempt to parse the extra.
- try {
- return StartCommand.parseFrom(data);
- } catch (InvalidProtocolBufferException exception) {
- logger.warning("Received invalid proto: %s", exception);
- return null;
- }
- }
-
- /** Returns {@code true} if the intent has the 'stop' extra. */
- static boolean isStopIntent(Intent intent) {
- return intent.hasExtra(EXTRA_STOP);
- }
-
- /** Issues a registration retry with delay. */
- static void issueDelayedRegistrationIntent(Context context, AndroidClock clock,
- ByteString clientId, ObjectId objectId, boolean isRegister, int delayMs, int requestCode) {
- RegistrationCommand command = isRegister ?
- AndroidListenerProtos.newDelayedRegisterCommand(clientId, objectId) :
- AndroidListenerProtos.newDelayedUnregisterCommand(clientId, objectId);
- Intent intent = new Intent()
- .putExtra(EXTRA_REGISTRATION, command.toByteArray())
- .setClass(context, AlarmReceiver.class);
-
- // Create a pending intent that will cause the AlarmManager to fire the above intent.
- PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent,
- PendingIntent.FLAG_ONE_SHOT);
-
- // Schedule the pending intent after the appropriate delay.
- AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
- long executeMs = clock.nowMs() + delayMs;
- alarmManager.set(AlarmManager.RTC, executeMs, pendingIntent);
- }
-
- /** Creates a 'start-client' intent. */
- static Intent createStartIntent(Context context, int clientType, byte[] clientName) {
- Intent intent = new Intent();
- // Create proto for the start command.
- StartCommand command = AndroidListenerProtos.newStartCommand(clientType,
- ByteString.copyFrom(clientName));
- intent.putExtra(EXTRA_START, command.toByteArray());
- return setAndroidListenerClass(context, intent);
- }
-
- /** Creates a 'stop-client' intent. */
- static Intent createStopIntent(Context context) {
- // Stop command just has the extra (its content doesn't matter).
- Intent intent = new Intent();
- intent.putExtra(EXTRA_STOP, true);
- return setAndroidListenerClass(context, intent);
- }
-
- /** Create an ack intent. */
- static Intent createAckIntent(Context context, byte[] ackHandle) {
- // Ack intent has an extra containing the ack handle data.
- Intent intent = new Intent();
- intent.putExtra(EXTRA_ACK, ackHandle);
- return setAndroidListenerClass(context, intent);
- }
-
- /** Constructs an intent with {@link RegistrationCommand} proto. */
- static Intent createRegistrationIntent(Context context, byte[] clientId,
- Iterable<ObjectId> objectIds, boolean isRegister) {
- // Registration intent has an extra containing the RegistrationCommand proto.
- Intent intent = new Intent();
- RegistrationCommand command = isRegister
- ? AndroidListenerProtos.newRegisterCommand(ByteString.copyFrom(clientId), objectIds)
- : AndroidListenerProtos.newUnregisterCommand(ByteString.copyFrom(clientId), objectIds);
- intent.putExtra(EXTRA_REGISTRATION, command.toByteArray());
- return setAndroidListenerClass(context, intent);
- }
-
- /** Sets the appropriate class for {@link AndroidListener} service intents. */
- static Intent setAndroidListenerClass(Context context, Intent intent) {
- String simpleListenerClass = new AndroidTiclManifest(context).getListenerServiceClass();
- return intent.setClassName(context, simpleListenerClass);
- }
-
- /** Returns {@code true} iff the given intent is an authorization token request. */
- static boolean isAuthTokenRequest(Intent intent) {
- return AuthTokenConstants.ACTION_REQUEST_AUTH_TOKEN.equals(intent.getAction());
- }
-
- /**
- * Given an authorization token request intent and authorization information ({@code authToken}
- * and {@code authType}) issues a response.
- */
- static void issueAuthTokenResponse(Context context, PendingIntent pendingIntent, String authToken,
- String authType) {
- Intent responseIntent = new Intent()
- .putExtra(AuthTokenConstants.EXTRA_AUTH_TOKEN, authToken)
- .putExtra(AuthTokenConstants.EXTRA_AUTH_TOKEN_TYPE, authType);
- try {
- pendingIntent.send(context, 0, responseIntent);
- } catch (CanceledException exception) {
- logger.warning("Canceled auth request: %s", exception);
- }
- }
-
- // Prevent instantiation.
- private AndroidListenerIntents() {
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerManifest.xml b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerManifest.xml
deleted file mode 100644
index 06084f67014..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerManifest.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
- <!-- Copyright 2011 Google Inc. All Rights Reserved. -->
- <!-- Manifest for AndroidListener. Must be merged with
- j/c/g/ipc/invalidation/external/client2/android2/AndroidManifest.xml. -->
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.google.ipc.invalidation.external.client2.contrib">
- <application>
- <!-- Receiver for scheduler alarms. -->
- <receiver android:exported="false"
- android:name="com.google.ipc.invalidation.external.client2.contrib.AndroidListener$AlarmReceiver"/>
- </application>
-</manifest>
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerProtos.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerProtos.java
deleted file mode 100644
index ca8bd9383bf..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerProtos.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.contrib;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-import com.google.ipc.invalidation.ticl.ProtoConverter;
-import com.google.ipc.invalidation.ticl.TiclExponentialBackoffDelayGenerator;
-import com.google.protobuf.ByteString;
-import com.google.protos.ipc.invalidation.AndroidListenerProtocol.AndroidListenerState;
-import com.google.protos.ipc.invalidation.AndroidListenerProtocol.AndroidListenerState.RetryRegistrationState;
-import com.google.protos.ipc.invalidation.AndroidListenerProtocol.RegistrationCommand;
-import com.google.protos.ipc.invalidation.AndroidListenerProtocol.StartCommand;
-
-import java.util.Map;
-import java.util.Map.Entry;
-
-/**
- * Static helper class supporting construction of valid {code AndroidListenerProtocol} messages.
- *
- */
-class AndroidListenerProtos {
-
- /** Creates a register command for the given objects and client. */
- static RegistrationCommand newRegisterCommand(ByteString clientId, Iterable<ObjectId> objectIds) {
- final boolean isRegister = true;
- return newRegistrationCommand(clientId, objectIds, isRegister);
- }
-
- /** Creates an unregister command for the given objects and client. */
- static RegistrationCommand newUnregisterCommand(ByteString clientId,
- Iterable<ObjectId> objectIds) {
- final boolean isRegister = false;
- return newRegistrationCommand(clientId, objectIds, isRegister);
- }
-
- /** Creates a retry register command for the given object and client. */
- static RegistrationCommand newDelayedRegisterCommand(ByteString clientId, ObjectId objectId) {
- final boolean isRegister = true;
- return newDelayedRegistrationCommand(clientId, objectId, isRegister);
- }
-
- /** Creates a retry unregister command for the given object and client. */
- static RegistrationCommand newDelayedUnregisterCommand(ByteString clientId, ObjectId objectId) {
- final boolean isRegister = false;
- return newDelayedRegistrationCommand(clientId, objectId, isRegister);
- }
-
- /** Creates proto for {@link AndroidListener} state. */
- static AndroidListenerState newAndroidListenerState(ByteString clientId, int requestCodeSeqNum,
- Map<ObjectId, TiclExponentialBackoffDelayGenerator> delayGenerators,
- Iterable<ObjectId> desiredRegistrations) {
- AndroidListenerState.Builder builder = AndroidListenerState.newBuilder()
- .setClientId(clientId)
- .setRequestCodeSeqNum(requestCodeSeqNum);
- for (ObjectId objectId : desiredRegistrations) {
- builder.addRegistration(ProtoConverter.convertToObjectIdProto(objectId));
- }
- for (Entry<ObjectId, TiclExponentialBackoffDelayGenerator> entry : delayGenerators.entrySet()) {
- builder.addRetryRegistrationState(
- newRetryRegistrationState(entry.getKey(), entry.getValue()));
- }
- return builder.build();
- }
-
- /** Creates proto for retry registration state. */
- static RetryRegistrationState newRetryRegistrationState(ObjectId objectId,
- TiclExponentialBackoffDelayGenerator delayGenerator) {
- return RetryRegistrationState.newBuilder()
- .setObjectId(ProtoConverter.convertToObjectIdProto(objectId))
- .setExponentialBackoffState(delayGenerator.marshal())
- .build();
- }
-
- /** Returns {@code true} iff the given proto is valid. */
- static boolean isValidAndroidListenerState(AndroidListenerState state) {
- return state.hasClientId() && state.hasRequestCodeSeqNum();
- }
-
- /** Returns {@code true} iff the given proto is valid. */
- static boolean isValidRegistrationCommand(RegistrationCommand command) {
- return command.hasIsRegister() && command.hasClientId() && command.hasIsDelayed();
- }
-
- /** Returns {@code true} iff the given proto is valid. */
- static boolean isValidStartCommand(StartCommand command) {
- return command.hasClientType() && command.hasClientName();
- }
-
- /** Creates start command proto. */
- static StartCommand newStartCommand(int clientType, ByteString clientName) {
- return StartCommand.newBuilder()
- .setClientType(clientType)
- .setClientName(clientName)
- .build();
- }
-
- private static RegistrationCommand newRegistrationCommand(ByteString clientId,
- Iterable<ObjectId> objectIds, boolean isRegister) {
- RegistrationCommand.Builder builder = RegistrationCommand.newBuilder()
- .setIsRegister(isRegister)
- .setClientId(clientId)
- .setIsDelayed(false);
- for (ObjectId objectId : objectIds) {
- Preconditions.checkNotNull(objectId);
- builder.addObjectId(ProtoConverter.convertToObjectIdProto(objectId));
- }
- return builder.build();
- }
-
- private static RegistrationCommand newDelayedRegistrationCommand(ByteString clientId,
- ObjectId objectId, boolean isRegister) {
- return RegistrationCommand.newBuilder()
- .setIsRegister(isRegister)
- .addObjectId(ProtoConverter.convertToObjectIdProto(objectId))
- .setClientId(clientId)
- .setIsDelayed(true)
- .build();
- }
-
- // Prevent instantiation.
- private AndroidListenerProtos() {
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerState.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerState.java
deleted file mode 100644
index 026b5ef8475..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerState.java
+++ /dev/null
@@ -1,300 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.contrib;
-
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-import com.google.ipc.invalidation.ticl.ProtoConverter;
-import com.google.ipc.invalidation.ticl.TiclExponentialBackoffDelayGenerator;
-import com.google.ipc.invalidation.util.Bytes;
-import com.google.ipc.invalidation.util.Marshallable;
-import com.google.ipc.invalidation.util.TypedUtil;
-import com.google.protobuf.ByteString;
-import com.google.protos.ipc.invalidation.AndroidListenerProtocol;
-import com.google.protos.ipc.invalidation.AndroidListenerProtocol.AndroidListenerState.RetryRegistrationState;
-import com.google.protos.ipc.invalidation.ClientProtocol.ObjectIdP;
-
-import java.nio.ByteBuffer;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Random;
-import java.util.Set;
-import java.util.UUID;
-
-
-/**
- * Encapsulates state to simplify persistence and tracking of changes. Internally maintains an
- * {@link #isDirty} bit. Call {@link #resetIsDirty} to indicate that changes have been persisted.
- *
- * <p>Notes on the {@link #desiredRegistrations} (DR) and {@link #delayGenerators} (DG) collections:
- * When the client application registers for an object, it is immediately added to DR. Similarly,
- * an object is removed from DR when the application unregisters. If a registration failure is
- * reported, the object is removed from DR if it exists and a delay generator is added to DG if one
- * does not already exist. (In the face of a failure, we assume that the registration is not desired
- * by the application unless/until the application retries.) When there is a successful
- * registration, the corresponding DG entry is removed. There are two independent collections rather
- * than one since we may be applying exponential backoff for an object when it is not in DR, and we
- * may have no reason to delay operations against an object in DR as well.
- *
- * <p>By removing objects from the {@link #desiredRegistrations} collection on failures, we are
- * essentially assuming that the client application doesn't care about the registration until we're
- * told otherwise -- by a subsequent call to register or unregister.
- *
- */
-final class AndroidListenerState
- implements Marshallable<AndroidListenerProtocol.AndroidListenerState> {
-
- /**
- * Exponential backoff delay generators used to determine delay before registration retries.
- * There is a delay generator for every failing object.
- */
- private final Map<ObjectId, TiclExponentialBackoffDelayGenerator> delayGenerators =
- new HashMap<ObjectId, TiclExponentialBackoffDelayGenerator>();
-
- /** The set of registrations for which the client wants to be registered. */
- private final Set<ObjectId> desiredRegistrations;
-
- /** Random generator used for all delay generators. */
- private final Random random = new Random();
-
- /** Initial maximum retry delay for exponential backoff. */
- private final int initialMaxDelayMs;
-
- /** Maximum delay factor for exponential backoff (relative to {@link #initialMaxDelayMs}). */
- private final int maxDelayFactor;
-
- /** Sequence number for alarm manager request codes. */
- private int requestCodeSeqNum;
-
- /**
- * Dirty flag. {@code true} whenever changes are made, reset to false when {@link #resetIsDirty}
- * is called. State initialized from a proto is assumed to be initially clean.
- */
- private boolean isDirty;
-
- /**
- * The identifier for the current client. The ID is randomly generated and is used to ensure that
- * messages are not handled by the wrong client instance.
- */
- private final ByteString clientId;
-
- /** Initializes state for a new client. */
- AndroidListenerState(int initialMaxDelayMs, int maxDelayFactor) {
- desiredRegistrations = new HashSet<ObjectId>();
- clientId = createGloballyUniqueClientId();
- // Assigning a client ID dirties the state because calling the constructor twice produces
- // different results.
- isDirty = true;
- requestCodeSeqNum = 0;
- this.initialMaxDelayMs = initialMaxDelayMs;
- this.maxDelayFactor = maxDelayFactor;
- }
-
- /** Initializes state from proto. */
- AndroidListenerState(int initialMaxDelayMs, int maxDelayFactor,
- AndroidListenerProtocol.AndroidListenerState state) {
- desiredRegistrations = new HashSet<ObjectId>();
- for (ObjectIdP objectIdProto : state.getRegistrationList()) {
- desiredRegistrations.add(ProtoConverter.convertFromObjectIdProto(objectIdProto));
- }
- for (RetryRegistrationState retryState : state.getRetryRegistrationStateList()) {
- ObjectId objectId = ProtoConverter.convertFromObjectIdProto(retryState.getObjectId());
- delayGenerators.put(objectId, new TiclExponentialBackoffDelayGenerator(random,
- initialMaxDelayMs, maxDelayFactor, retryState.getExponentialBackoffState()));
- }
- clientId = state.getClientId();
- requestCodeSeqNum = state.getRequestCodeSeqNum();
- isDirty = false;
- this.initialMaxDelayMs = initialMaxDelayMs;
- this.maxDelayFactor = maxDelayFactor;
- }
-
- /** Increments and returns sequence number for alarm manager request codes. */
- int getNextRequestCode() {
- isDirty = true;
- return ++requestCodeSeqNum;
- }
-
- /**
- * See specs for {@link TiclExponentialBackoffDelayGenerator#getNextDelay}. Gets next delay for
- * the given {@code objectId}. If a delay generator does not yet exist for the object, one is
- * created.
- */
- int getNextDelay(ObjectId objectId) {
- TiclExponentialBackoffDelayGenerator delayGenerator =
- delayGenerators.get(objectId);
- if (delayGenerator == null) {
- delayGenerator = new TiclExponentialBackoffDelayGenerator(random, initialMaxDelayMs,
- maxDelayFactor);
- delayGenerators.put(objectId, delayGenerator);
- }
- // Requesting a delay from a delay generator modifies its internal state.
- isDirty = true;
- return delayGenerator.getNextDelay();
- }
-
- /** Inform that there has been a successful registration for an object. */
- void informRegistrationSuccess(ObjectId objectId) {
- // Since registration was successful, we can remove exponential backoff (if any) for the given
- // object.
- resetDelayGeneratorFor(objectId);
- }
-
- /**
- * Inform that there has been a registration failure.
- *
- * <p>Remove the object from the desired registrations collection whenever there's a failure. We
- * don't care if the op that failed was actually an unregister because we never suppress an
- * unregister request (even if the object is not in the collection). See
- * {@link AndroidListener#issueRegistration}.
- */
- public void informRegistrationFailure(ObjectId objectId, boolean isTransient) {
- removeDesiredRegistration(objectId);
- if (!isTransient) {
- // There should be no retries for the object, so remove any backoff state associated with it.
- resetDelayGeneratorFor(objectId);
- }
- }
-
- /**
- * If there is a backoff delay generator for the given object, removes it and sets dirty flag.
- */
- private void resetDelayGeneratorFor(ObjectId objectId) {
- if (TypedUtil.remove(delayGenerators, objectId) != null) {
- isDirty = true;
- }
- }
-
- /** Adds the given registration. Returns {@code true} if it was not already tracked. */
- boolean addDesiredRegistration(ObjectId objectId) {
- if (desiredRegistrations.add(objectId)) {
- isDirty = true;
- return true;
- }
- return false;
- }
-
- /** Removes the given registration. Returns {@code true} if it was actually tracked. */
- boolean removeDesiredRegistration(ObjectId objectId) {
- if (desiredRegistrations.remove(objectId)) {
- isDirty = true;
- return true;
- }
- return false;
- }
-
- /**
- * Resets the {@link #isDirty} flag to {@code false}. Call after marshalling and persisting state.
- */
- void resetIsDirty() {
- isDirty = false;
- }
-
- @Override
- public AndroidListenerProtocol.AndroidListenerState marshal() {
- return AndroidListenerProtos.newAndroidListenerState(clientId, requestCodeSeqNum,
- delayGenerators, desiredRegistrations);
- }
-
- /**
- * Gets the identifier for the current client. Used to determine if registrations commands are
- * relevant to this instance.
- */
- ByteString getClientId() {
- return clientId;
- }
-
- /** Returns {@code true} iff registration is desired for the given object. */
- boolean containsDesiredRegistration(ObjectId objectId) {
- return TypedUtil.contains(desiredRegistrations, objectId);
- }
-
- /**
- * Returns {@code true} if changes have been made since the last successful call to
- * {@link #resetIsDirty}.
- */
- boolean getIsDirty() {
- return isDirty;
- }
-
- @Override
- public int hashCode() {
- // Since the client ID is globally unique, it's sufficient as a hashCode.
- return clientId.hashCode();
- }
-
- /**
- * Overridden for tests which compare listener states to verify that they have been correctly
- * (un)marshalled. We implement equals rather than exposing private data.
- */
- @Override
- public boolean equals(Object object) {
- if (this == object) {
- return true;
- }
-
- if (!(object instanceof AndroidListenerState)) {
- return false;
- }
-
- AndroidListenerState that = (AndroidListenerState) object;
-
- return (this.isDirty == that.isDirty) &&
- (this.requestCodeSeqNum == that.requestCodeSeqNum) &&
- (this.desiredRegistrations.size() == that.desiredRegistrations.size()) &&
- (this.desiredRegistrations.containsAll(that.desiredRegistrations)) &&
- (this.clientId.equals(that.clientId)) &&
- equals(this.delayGenerators, that.delayGenerators);
- }
-
- /** Compares the contents of two {@link #delayGenerators} maps. */
- private static boolean equals(Map<ObjectId, TiclExponentialBackoffDelayGenerator> x,
- Map<ObjectId, TiclExponentialBackoffDelayGenerator> y) {
- if (x.size() != y.size()) {
- return false;
- }
- for (Entry<ObjectId, TiclExponentialBackoffDelayGenerator> xEntry : x.entrySet()) {
- TiclExponentialBackoffDelayGenerator yGenerator = y.get(xEntry.getKey());
- if ((yGenerator == null) || !xEntry.getValue().marshal().toByteString().equals(
- yGenerator.marshal().toByteString())) {
- return false;
- }
- }
- return true;
- }
-
- @Override
- public String toString() {
- return String.format("AndroidListenerState[%s]: isDirty = %b, " +
- "desiredRegistrations.size() = %d, delayGenerators.size() = %d, requestCodeSeqNum = %d",
- Bytes.toString(clientId), isDirty, desiredRegistrations.size(), delayGenerators.size(),
- requestCodeSeqNum);
- }
-
- /**
- * Constructs a new globally unique ID for the client. Can be used to determine if commands
- * originated from this instance of the listener.
- */
- private static ByteString createGloballyUniqueClientId() {
- UUID guid = UUID.randomUUID();
- byte[] bytes = new byte[16];
- ByteBuffer buffer = ByteBuffer.wrap(bytes);
- buffer.putLong(guid.getLeastSignificantBits());
- buffer.putLong(guid.getMostSignificantBits());
- return ByteString.copyFrom(bytes);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/MultiplexingGcmListener.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/MultiplexingGcmListener.java
deleted file mode 100644
index 927ea592f33..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/MultiplexingGcmListener.java
+++ /dev/null
@@ -1,362 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.contrib;
-
-import com.google.android.gcm.GCMBaseIntentService;
-import com.google.android.gcm.GCMBroadcastReceiver;
-import com.google.android.gcm.GCMRegistrar;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.ticl.android.c2dm.WakeLockManager;
-
-import android.app.IntentService;
-import android.content.BroadcastReceiver;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.content.pm.ServiceInfo;
-
-/**
- * A Google Cloud Messaging listener class that rebroadcasts events as package-scoped
- * broadcasts. This allows multiple components to share a single GCM connection.
- * <p>
- * This listener uses an API of broadcasted Intents that is modeled after that provided by
- * {@link GCMBaseIntentService}. For each upcall (e.g., onMessage, on Registered, etc) specified
- * by {@code GCMBaseIntentService}, there is an {@code EXTRA_OP_...} constant defined in
- * {@link Intents}.
- * <p>
- * Note that this class does <b>NOT</b> handle registering with GCM; applications are still required
- * to do that in the usual way (e.g., using the GCMRegistrar class from the GCM library).
- * <p>
- * In order to raise a {@code GCMBaseIntentService} event to listeners, this service will broadcast
- * an Intent with the following properties:
- * 1. The action of the Intent is {@link Intents#ACTION}
- * 2. There is a boolean-valued extra in the Intent whose key is the {@code EXTRA_OP_...} key
- * for that call and whose value is {@code true}. For any intent, exactly one {@code EXTRA_OP}
- * extra will be set.
- * 3. The Intent contains additional call-specific extras required to interpret it. (See note for
- * onMessage, below).
- * <p>
- * Clients of this service <b>MUST NOT</b> assume that there is a one-to-one mapping between
- * issued broadcasts and actual GCM intents. I.e., this service may issue broadcast intents
- * spontaneously, and it may not issue an intent for every GCM event.
- * <p>
- * For the onMessage() call, the broadcast intent will contain key/value extras containing the
- * message payload. These extras are guaranteed to be identical to those that would have been in
- * the Intent provided to the onMessage call. However, clients <b>MUST NOT</b> assume that the
- * Intent broadcast to communicate a GCM message is literally the same Intent generated by the GCM
- * client library.
- * <p>
- * This class does not expose the {@code onError} call, since according to the GCM documentation
- * there is nothing to do except log an error (which this class does).
- *
- */
-public class MultiplexingGcmListener extends GCMBaseIntentService {
- /* This class is public so that it can be instantiated by the Android runtime. */
-
- /** Constants used in broadcast Intents. */
- public static final class Intents {
- /** Prefix of the action and extras. */
- private static final String PREFIX = "com.google.ipc.invalidation.gcmmplex.";
-
- /** Action of all broadcast intents issued. */
- public static final String ACTION = PREFIX + "EVENT";
-
- /** Extra corresponding to an {@code onMessage} upcall. */
- public static final String EXTRA_OP_MESSAGE = PREFIX + "MESSAGE";
-
- /** Extra corresponding to an {@code onRegistered} upcall. */
- public static final String EXTRA_OP_REGISTERED = PREFIX + "REGISTERED";
-
- /** Extra corresponding to an {@code onUnregistered} upcall. */
- public static final String EXTRA_OP_UNREGISTERED = PREFIX + "UNREGISTERED";
-
- /** Extra corresponding to an {@code onDeletedMessages} upcall. */
- public static final String EXTRA_OP_DELETED_MESSAGES = PREFIX + "DELETED_MSGS";
-
- /**
- * Extra set iff the operation is {@link #EXTRA_OP_REGISTERED} or
- * {@link #EXTRA_OP_UNREGISTERED}; it is string-valued and holds the registration id.
- */
- public static final String EXTRA_DATA_REG_ID = PREFIX + "REGID";
-
- /**
- * Extra set iff the operation is {@link #EXTRA_OP_DELETED_MESSAGES}; it is integer-valued
- * and holds the number of deleted messages.
- */
- public static final String EXTRA_DATA_NUM_DELETED_MSGS = PREFIX + "NUM_DELETED_MSGS";
- }
-
- /**
- * {@link GCMBroadcastReceiver} that forwards GCM intents to the {@code MultiplexingGcmListener}
- * class.
- */
- public static class GCMReceiver extends GCMBroadcastReceiver {
- /* This class is public so that it can be instantiated by the Android runtime. */
- @Override
- protected String getGCMIntentServiceClassName(Context context) {
- return MultiplexingGcmListener.class.getName();
- }
- }
-
- /**
- * Convenience base class for client implementations. It provides base classes for a broadcast
- * receiver and an intent service that work together to handle events from the
- * {@code MultiplexingGcmListener} while holding a wake lock.
- * <p>
- * This class guarantees that the {@code onYYY} methods will be called holding a wakelock, and
- * that the wakelock will be automatically released when the method returns.
- * <p>
- * The wakelock will also be automatically released
- * {@link Receiver#WAKELOCK_TIMEOUT_MS} ms after the original Intent was received by the
- * {@link Receiver} class, to guard against leaks. Applications requiring a longer-duration
- * wakelock should acquire one on their own in the appropriate {@code onYYY} method.
- */
- public static abstract class AbstractListener extends IntentService {
- /** Prefix of all wakelocks acquired by the receiver and the intent service. */
- private static final String WAKELOCK_PREFIX = "multiplexing-gcm-listener:";
-
- /** Intent extra key used to hold wakelock names, for runtime checks. */
- private static final String EXTRA_WAKELOCK_NAME =
- "com.google.ipc.invalidation.gcmmplex.listener.WAKELOCK_NAME";
-
- /** Logger for {@code AbstractListener}. */
- private static final Logger logger = AndroidLogger.forTag("MplexGcmAbsListener");
-
- /**
- * A {@code BroadcastReceiver} to receive intents from the {@code MultiplexingGcmListener}
- * service. It acquires a wakelock and forwards the intent to the service named by
- * {@link #getServiceClass}, which must be a subclass of {@code AbstractListener}.
- */
- public static abstract class Receiver extends BroadcastReceiver {
- /** Timeout after which wakelocks will be automatically released. */
- private static final int WAKELOCK_TIMEOUT_MS = 30 * 1000;
-
- @Override
- public final void onReceive(Context context, Intent intent) {
- // This method is final to prevent subclasses from overriding it and introducing errors in
- // the wakelock protocol.
- Class<?> serviceClass = getServiceClass();
-
- // If the service isn't an AbstractListener subclass, then it will not release the wakelock
- // properly, causing bugs.
- if (!AbstractListener.class.isAssignableFrom(serviceClass)) {
- throw new RuntimeException(
- "Service class is not a subclass of AbstractListener: " + serviceClass);
- }
- String wakelockKey = getWakelockKey(serviceClass);
- intent.setClass(context, serviceClass);
-
- // To avoid insidious bugs, tell the service which wakelock we acquired. The service will
- // log a warning if the lock it releases is not this lock.
- intent.putExtra(EXTRA_WAKELOCK_NAME, wakelockKey);
-
- // Acquire the lock and start the service. The service is responsible for releasing the
- // lock.
- WakeLockManager.getInstance(context).acquire(wakelockKey, WAKELOCK_TIMEOUT_MS);
- context.startService(intent);
- }
-
- /** Returns the class of the service that will handle intents. */
- protected abstract Class<?> getServiceClass();
- }
-
- protected AbstractListener(String name) {
- super(name);
-
- // If the process dies during a call to onHandleIntent, redeliver the intent when the service
- // restarts.
- setIntentRedelivery(true);
- }
-
- @Override
- public final void onHandleIntent(Intent intent) {
- if (intent == null) {
- return;
- }
-
- // This method is final to prevent subclasses from overriding it and introducing errors in
- // the wakelock protocol.
- try {
- doHandleIntent(intent);
- } finally {
- // Release the wakelock acquired by the receiver. The receiver provides the name of the
- // lock it acquired in the Intent so that we can sanity-check that we are releasing the
- // right lock.
- String receiverAcquiredWakelock = intent.getStringExtra(EXTRA_WAKELOCK_NAME);
- String wakelockToRelease = getWakelockKey(getClass());
- if (!wakelockToRelease.equals(receiverAcquiredWakelock)) {
- logger.warning("Receiver acquired wakelock '%s' but releasing '%s'",
- receiverAcquiredWakelock, wakelockToRelease);
- }
- WakeLockManager wakelockManager = WakeLockManager.getInstance(this);
- wakelockManager.release(wakelockToRelease);
- }
- }
-
- /** Handles {@code intent} while holding a wake lock. */
- private void doHandleIntent(Intent intent) {
- // Ensure this is an Intent we want to handle.
- if (!MultiplexingGcmListener.Intents.ACTION.equals(intent.getAction())) {
- logger.warning("Ignoring intent with unknown action: %s", intent);
- return;
- }
- // Dispatch based on the extras.
- if (intent.hasExtra(MultiplexingGcmListener.Intents.EXTRA_OP_MESSAGE)) {
- onMessage(intent);
- } else if (intent.hasExtra(MultiplexingGcmListener.Intents.EXTRA_OP_REGISTERED)) {
- onRegistered(intent.getStringExtra(MultiplexingGcmListener.Intents.EXTRA_DATA_REG_ID));
- } else if (intent.hasExtra(MultiplexingGcmListener.Intents.EXTRA_OP_UNREGISTERED)) {
- onUnregistered(intent.getStringExtra(MultiplexingGcmListener.Intents.EXTRA_DATA_REG_ID));
- } else if (intent.hasExtra(MultiplexingGcmListener.Intents.EXTRA_OP_DELETED_MESSAGES)) {
- int numDeleted =
- intent.getIntExtra(MultiplexingGcmListener.Intents.EXTRA_DATA_NUM_DELETED_MSGS, -1);
- if (numDeleted == -1) {
- logger.warning("Could not parse num-deleted field of GCM broadcast: %s", intent);
- return;
- }
- onDeletedMessages(numDeleted);
- } else {
- logger.warning("Broadcast GCM intent with no known operation: %s", intent);
- }
- }
-
- // These methods have the same specs as in {@code GCMBaseIntentService}.
- protected abstract void onMessage(Intent intent);
- protected abstract void onRegistered(String registrationId);
- protected abstract void onUnregistered(String registrationId);
- protected abstract void onDeletedMessages(int total);
-
- /**
- * Returns the name of the wakelock to acquire for the intent service implemented by
- * {@code clazz}.
- */
- private static String getWakelockKey(Class<?> clazz) {
- return WAKELOCK_PREFIX + clazz.getName();
- }
- }
-
- /**
- * Name of the metadata element within the {@code service} element whose value is a
- * comma-delimited list of GCM sender ids.
- */
- private static final String GCM_SENDER_IDS_METADATA_KEY = "sender_ids";
-
- /** Logger. */
- private static final Logger logger = AndroidLogger.forTag("MplexGcmListener");
-
- // All onYYY methods work by constructing an appropriate Intent and broadcasting it.
-
- @Override
- protected void onMessage(Context context, Intent intent) {
- Intent newIntent = new Intent();
- newIntent.putExtra(Intents.EXTRA_OP_MESSAGE, true);
-
- // Copy the extra keys containing the message payload into the new Intent.
- for (String extraKey : intent.getExtras().keySet()) {
- newIntent.putExtra(extraKey, intent.getStringExtra(extraKey));
- }
- rebroadcast(newIntent);
- }
-
- @Override
- protected void onRegistered(Context context, String registrationId) {
- Intent intent = new Intent();
- intent.putExtra(Intents.EXTRA_OP_REGISTERED, true);
- intent.putExtra(Intents.EXTRA_DATA_REG_ID, registrationId);
- rebroadcast(intent);
- }
-
- @Override
- protected void onUnregistered(Context context, String registrationId) {
- Intent intent = new Intent();
- intent.putExtra(Intents.EXTRA_OP_UNREGISTERED, true);
- intent.putExtra(Intents.EXTRA_DATA_REG_ID, registrationId);
- rebroadcast(intent);
- }
-
- @Override
- protected void onDeletedMessages(Context context, int total) {
- Intent intent = new Intent();
- intent.putExtra(Intents.EXTRA_OP_DELETED_MESSAGES, true);
- intent.putExtra(Intents.EXTRA_DATA_NUM_DELETED_MSGS, total);
- rebroadcast(intent);
- }
-
- @Override
- protected void onError(Context context, String errorId) {
- // This is called for unrecoverable errors, so just log a warning.
- logger.warning("GCM error: %s", errorId);
- }
-
- @Override
- protected String[] getSenderIds(Context context) {
- return readSenderIdsFromManifestOrDie(this);
- }
-
- /**
- * Broadcasts {@code intent} with the action set to {@link Intents#ACTION} and the package name
- * set to the package name of this service.
- */
- private void rebroadcast(Intent intent) {
- intent.setAction(Intents.ACTION);
- intent.setPackage(getPackageName());
- sendBroadcast(intent);
- }
-
- /**
- * Registers with GCM if not already registered. Also verifies that the device supports GCM
- * and that the manifest is correctly configured. Returns the existing registration id, if one
- * exists, or the empty string if one does not.
- *
- * @throws UnsupportedOperationException if the device does not have all GCM dependencies
- * @throws IllegalStateException if the manifest is not correctly configured
- */
- public static String initializeGcm(Context context) {
- GCMRegistrar.checkDevice(context);
- GCMRegistrar.checkManifest(context);
- final String regId = GCMRegistrar.getRegistrationId(context);
- if (regId.equals("")) {
- GCMRegistrar.register(context, readSenderIdsFromManifestOrDie(context));
- }
- return regId;
- }
-
- /**
- * Returns the GCM sender ids from {@link #GCM_SENDER_IDS_METADATA_KEY} or throws a
- * {@code RuntimeException} if they are not defined.
- */
-
- static String[] readSenderIdsFromManifestOrDie(Context context) {
- try {
- ServiceInfo serviceInfo = context.getPackageManager().getServiceInfo(
- new ComponentName(context, MultiplexingGcmListener.class), PackageManager.GET_META_DATA);
- if (serviceInfo.metaData == null) {
- throw new RuntimeException("Service has no metadata");
- }
- String senderIds = serviceInfo.metaData.getString(GCM_SENDER_IDS_METADATA_KEY);
- if (senderIds == null) {
- throw new RuntimeException("Service does not have the sender-ids metadata");
- }
- return senderIds.split(",");
- } catch (NameNotFoundException exception) {
- throw new RuntimeException("Could not read service info from manifest", exception);
- }
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/AckHandle.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/AckHandle.java
deleted file mode 100644
index 67d5e08950f..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/AckHandle.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.types;
-
-import java.util.Arrays;
-
-/**
- * Represents an opaque handle that can be used to acknowledge an invalidation event by calling
- * {@code InvalidationClient.acknowledge(AckHandle)} to indicate that the client has successfully
- * handled the event.
- *
- */
-public final class AckHandle {
-
- /** The serialized representation of the handle */
- private final byte[] handleData;
-
- /** Creates a new ack handle from the serialized {@code handleData} representation. */
- public static AckHandle newInstance(byte[] handleData) {
- return new AckHandle(handleData);
- }
-
- private AckHandle(byte[] handleData) {
- this.handleData = handleData;
- }
-
- public byte[] getHandleData() {
- return handleData;
- }
-
- @Override
- public boolean equals(Object object) {
- if (object == this) {
- return true;
- }
-
- if (!(object instanceof AckHandle)) {
- return false;
- }
-
- final AckHandle other = (AckHandle) object;
- return Arrays.equals(handleData, other.handleData);
- }
-
- @Override
- public int hashCode() {
- return Arrays.hashCode(handleData);
- }
-
- @Override
- public String toString() {
- return "AckHandle: " + BytesFormatter.toString(handleData);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/ApplicationClientId.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/ApplicationClientId.java
deleted file mode 100644
index 8648408bff6..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/ApplicationClientId.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.types;
-
-import com.google.common.base.Preconditions;
-
-import java.util.Arrays;
-
-/**
- * An identifier for application clients in an application-defined way. I.e., a client name in an
- * application naming scheme. This is not interpreted by the invalidation system - however, it is
- * used opaquely to squelch invalidations for the cient causing an update, e.g., if a client C
- * whose app client id is C.appClientId changes object X and the backend store informs the backend
- * invalidation sytsem that X was modified by X.appClientId, the invalidation to C can then be
- * squelched by the invalidation system.
- *
- */
-public final class ApplicationClientId {
-
- /** The opaque id of the client application. */
- private final byte[] clientName;
-
- /**
- * Creates an application client id for the given {@code clientName} (does not make a copy of the
- * byte array).
- */
- public static ApplicationClientId newInstance(byte[] appClientId) {
- return new ApplicationClientId(appClientId);
- }
-
- /** Creates an application id for the given {@code clientName}. */
- private ApplicationClientId(byte[] clientName) {
- this.clientName = Preconditions.checkNotNull(clientName, "clientName");
- }
-
- public byte[] getClientName() {
- return clientName;
- }
-
- @Override
- public boolean equals(Object object) {
- if (object == this) {
- return true;
- }
-
- if (!(object instanceof ApplicationClientId)) {
- return false;
- }
-
- final ApplicationClientId other = (ApplicationClientId) object;
- return Arrays.equals(clientName, other.clientName);
- }
-
- @Override
- public int hashCode() {
- return Arrays.hashCode(clientName);
- }
-
- @Override
- public String toString() {
- return "AppClientId: <, " + BytesFormatter.toString(clientName) + ">";
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/BytesFormatter.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/BytesFormatter.java
deleted file mode 100644
index 9552cc97616..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/BytesFormatter.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.types;
-
-
-/**
- * A utility class to format bytes to string for ease of reading and debugging.
- *
- */
-class BytesFormatter {
-
- /**
- * Three arrays that store the representation of each character from 0 to 255.
- * The ith number's octal representation is: CHAR_OCTAL_STRINGS1[i],
- * CHAR_OCTAL_STRINGS2[i], CHAR_OCTAL_STRINGS3[i]
- * <p>
- * E.g., if the number 128, these arrays contain 2, 0, 0 at index 128. We use
- * 3 char arrays instead of an array of strings since the code path for a
- * character append operation is quite a bit shorter than the append operation
- * for strings.
- */
- private static final char[] CHAR_OCTAL_STRINGS1 = new char[256];
- private static final char[] CHAR_OCTAL_STRINGS2 = new char[256];
- private static final char[] CHAR_OCTAL_STRINGS3 = new char[256];
-
- static {
- // Initialize the array with the Octal string values so that we do not have
- // to do String.format for every byte during runtime.
- for (int i = 0; i < CHAR_OCTAL_STRINGS1.length; i++) {
- // Unsophisticated way to get an octal string padded to 3 characters.
- String intAsStr = Integer.toOctalString(i);
- switch (intAsStr.length()) {
- case 3:
- break;
- case 2:
- intAsStr = "0" + intAsStr;
- break;
- case 1:
- intAsStr = "00" + intAsStr;
- break;
- default:
- throw new RuntimeException("Bad integer value: " + intAsStr);
- }
- if (intAsStr.length() != 3) {
- throw new RuntimeException("Bad padding: " + intAsStr);
- }
- String value = '\\' + intAsStr;
- CHAR_OCTAL_STRINGS1[i] = value.charAt(1);
- CHAR_OCTAL_STRINGS2[i] = value.charAt(2);
- CHAR_OCTAL_STRINGS3[i] = value.charAt(3);
- }
- }
-
- /** Returns a human-readable string for the contents of {@code bytes}. */
- public static String toString(byte[] bytes) {
- if (bytes == null) {
- return null;
- }
- StringBuilder builder = new StringBuilder(3 * bytes.length);
- for (byte c : bytes) {
- switch(c) {
- case '\n': builder.append('\\'); builder.append('n'); break;
- case '\r': builder.append('\\'); builder.append('r'); break;
- case '\t': builder.append('\\'); builder.append('t'); break;
- case '\"': builder.append('\\'); builder.append('"'); break;
- case '\\': builder.append('\\'); builder.append('\\'); break;
- default:
- if ((c >= 32) && (c < 127) && c != '\'') {
- builder.append((char) c);
- } else {
- int byteValue = c;
- if (c < 0) {
- byteValue = c + 256;
- }
- builder.append('\\');
- builder.append(CHAR_OCTAL_STRINGS1[byteValue]);
- builder.append(CHAR_OCTAL_STRINGS2[byteValue]);
- builder.append(CHAR_OCTAL_STRINGS3[byteValue]);
- }
- }
- }
- return builder.toString();
- }
-
- private BytesFormatter() { // To prevent instantiation.
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/Callback.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/Callback.java
deleted file mode 100644
index a1296cddee7..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/Callback.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.types;
-
-
-/**
- * An interface to receive objects of a single type.
- *
- * @param <T> type of object received in the callback
- *
- */
-public interface Callback<T> {
- /**
- * Accepts the object provided by the caller.
- *
- * @param object received object
- */
- void accept(T object);
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/ErrorContext.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/ErrorContext.java
deleted file mode 100644
index e50d38c2572..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/ErrorContext.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.types;
-
-/**
- * Extra information about the error in {@code ErrorInfo} - cast to appropriate subtype as
- * specified for the given reason.
- *
- */
-public class ErrorContext {
-
- /** A context with numeric data. */
- public static class NumberContext extends ErrorContext {
- private int number;
-
- public NumberContext(int number) {
- this.number = number;
- }
-
- int getNumber() {
- return number;
- }
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/ErrorInfo.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/ErrorInfo.java
deleted file mode 100644
index 68b78b8bd07..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/ErrorInfo.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.types;
-
-/**
- * Information about an error given to the application.
- *
- */
-public final class ErrorInfo {
- /**
- * Possible reasons for error in {@code InvalidationListener.informError}. The application writer
- * must NOT assume that this is complete list since error codes may be added later. That is, for
- * error codes that it cannot handle, it should not necessarily just crash the code. It may want
- * to present a dialog box to the user (say). For each ErrorReason, the ErrorInfo object has a
- * context object. We describe the type and meaning of the context for each named constant below.
- */
- public static class ErrorReason {
- /** The provided authentication/authorization token is not valid for use. */
- public static final int AUTH_FAILURE = 1;
-
- /** An unknown failure - more human-readable information is in the error message. */
- public static final int UNKNOWN_FAILURE = -1;
-
- private ErrorReason() {} // not instantiable
- }
-
- /** The cause of the failure. */
- private final int errorReason;
-
- /**
- * Is the error transient or permanent. See discussion in {@code Status.Code} for permanent and
- * transient failure handling.
- */
- private final boolean isTransient;
-
- /** Human-readable description of the error. */
- private final String errorMessage;
-
- /** Extra information about the error - cast to appropriate object as specified by the reason. */
- private final Object context;
-
- /**
- * Returns a new ErrorInfo object given the reason for the error, whether it is transient or
- * permanent, a helpful error message and extra context about the error.
- */
- public static ErrorInfo newInstance(int errorReason, boolean isTransient,
- String errorMessage, ErrorContext context) {
- return new ErrorInfo(errorReason, isTransient, errorMessage, context);
- }
-
- private ErrorInfo(int errorReason, boolean isTransient, String errorMessage,
- ErrorContext context) {
- this.errorReason = errorReason;
- this.isTransient = isTransient;
- this.errorMessage = errorMessage;
- this.context = context;
- }
-
- public boolean isTransient() {
- return isTransient;
- }
-
- public String getErrorMessage() {
- return errorMessage;
- }
-
- public int getErrorReason() {
- return errorReason;
- }
-
- public Object getContext() {
- return context;
- }
-
- @Override
- public String toString() {
- return "ErrorInfo: " + errorReason + ", " + isTransient + ", " + errorMessage + ", " + context;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/Invalidation.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/Invalidation.java
deleted file mode 100644
index 6c8c5f2834f..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/Invalidation.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.types;
-
-import com.google.common.base.Preconditions;
-
-import java.util.Arrays;
-
-
-/**
- * A class to represent an invalidation for a given object/version and an optional payload.
- *
- */
-public final class Invalidation {
-
- /** The object being invalidated/updated. */
- private final ObjectId objectId;
-
- /** The new version of the object. */
- private final long version;
-
- /** Optional payload for the object. */
- private final byte[] payload;
-
- /** Whether this is a restarted invalidation, for internal use only. */
- private final boolean isTrickleRestart;
-
- /**
- * Creates an invalidation for the given {@code object} and {@code version}.
- */
- public static Invalidation newInstance(ObjectId objectId, long version) {
- return new Invalidation(objectId, version, null, true);
- }
-
- /**
- * Creates an invalidation for the given {@code object} and {@code version} and {@code payload}
- */
- public static Invalidation newInstance(ObjectId objectId, long version,
- byte[] payload) {
- return new Invalidation(objectId, version, payload, true);
- }
-
- /**
- * Creates an invalidation for the given {@code object}, {@code version} and optional
- * {@code payload} and internal {@code isTrickleRestart} flag.
- */
- public static Invalidation newInstance(ObjectId objectId, long version,
- byte[] payload, boolean isTrickleRestart) {
- return new Invalidation(objectId, version, payload, isTrickleRestart);
- }
-
- /**
- * Creates an invalidation for the given {@code object}, {@code version} and optional
- * {@code payload} and optional {@code componentStampLog}.
- */
- private Invalidation(ObjectId objectId, long version, byte[] payload,
- boolean isTrickleRestart) {
- this.objectId = Preconditions.checkNotNull(objectId, "objectId");
- this.version = version;
- this.payload = payload;
- this.isTrickleRestart = isTrickleRestart;
- }
-
- public ObjectId getObjectId() {
- return objectId;
- }
-
- public long getVersion() {
- return version;
- }
-
- /** Returns the optional payload for the object - if none exists, returns {@code null}. */
- public byte[] getPayload() {
- return payload;
- }
-
- @Override
- public boolean equals(Object object) {
- if (object == this) {
- return true;
- }
-
- if (!(object instanceof Invalidation)) {
- return false;
- }
-
- final Invalidation other = (Invalidation) object;
- if ((payload != null) != (other.payload != null)) {
- // One of the objects has a payload and the other one does not.
- return false;
- }
- // Both have a payload or not.
- return objectId.equals(other.objectId) && (version == other.version) &&
- (isTrickleRestart == other.isTrickleRestart) &&
- ((payload == null) || Arrays.equals(payload, other.payload));
- }
-
- @Override
- public int hashCode() {
- int result = 17;
- result = 31 * result + objectId.hashCode();
- result = 31 * result + (int) (version ^ (version >>> 32));
-
- // Booleans.hashCode() inlined here to reduce client library size.
- result = 31 * result + (isTrickleRestart ? 1231 : 1237);
- if (payload != null) {
- result = 31 * result + Arrays.hashCode(payload);
- }
- return result;
- }
-
- @Override
- public String toString() {
- return "Inv: <" + objectId + ", " + version + ", " + isTrickleRestart + ", " +
- BytesFormatter.toString(payload) + ">";
- }
-
- /** Returns whether this is a restarted invalidation, for internal use only. */
- public boolean getIsTrickleRestartForInternalUse() {
- return isTrickleRestart;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/ObjectId.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/ObjectId.java
deleted file mode 100644
index cced110bea4..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/ObjectId.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.types;
-
-import com.google.common.base.Preconditions;
-
-import java.util.Arrays;
-
-/**
- * A class to represent a unique object id that an application can register or
- * unregister for.
- *
- */
-public final class ObjectId {
-
- /** The invalidation source type. */
- private final int source;
-
- /** The name/unique id for the object. */
- private final byte[] name;
-
- /**
- * Creates an object id for the given {@code source} and id {@code name} (does not make a copy of
- * the array).
- */
- public static ObjectId newInstance(int source, byte[] name) {
- return new ObjectId(source, name);
- }
-
- /** Creates an object id for the given {@code source} and id {@code name}. */
- private ObjectId(int source, byte[] name) {
- Preconditions.checkState(source >= 0, "source");
- this.source = source;
- this.name = Preconditions.checkNotNull(name, "name");
- }
-
- public int getSource() {
- return source;
- }
-
- public byte[] getName() {
- return name;
- }
-
- @Override
- public boolean equals(Object object) {
- if (object == this) {
- return true;
- }
-
- if (!(object instanceof ObjectId)) {
- return false;
- }
-
- final ObjectId other = (ObjectId) object;
- if ((source != other.source) || !Arrays.equals(name, other.name)) {
- return false;
- }
- return true;
- }
-
- @Override
- public int hashCode() {
- return source ^ Arrays.hashCode(name);
- }
-
- @Override
- public String toString() {
- return "Oid: <" + source + ", " + BytesFormatter.toString(name) + ">";
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/SimplePair.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/SimplePair.java
deleted file mode 100644
index aa5cb762249..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/SimplePair.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.types;
-
-
-/**
- * An immutable, semantic-free ordered pair of nullable values. These can be
- * accessed using the {@link #getFirst} and {@link #getSecond} methods. Equality
- * and hashing are defined in the natural way.
- *
- * @param <FirstType> The type of the first element
- * @param <SecondType> The type of the second element
- *
- */
-public final class SimplePair<FirstType, SecondType> {
- /**
- * Creates a new pair containing the given elements in order.
- */
- public static <FirstType, SecondType> SimplePair<FirstType, SecondType> of(
- FirstType first, SecondType second) {
- return new SimplePair<FirstType, SecondType>(first, second);
- }
-
- /**
- * The first element of the pair; see also {@link #getFirst}.
- */
- public final FirstType first;
-
- /**
- * The second element of the pair; see also {@link #getSecond}.
- */
- public final SecondType second;
-
- /**
- * Constructor. It is usually easier to call {@link #of}.
- */
- public SimplePair(FirstType first, SecondType second) {
- this.first = first;
- this.second = second;
- }
-
- /**
- * Returns the first element of this pair; see also {@link #first}.
- */
- public FirstType getFirst() {
- return first;
- }
-
- /**
- * Returns the second element of this pair; see also {@link #second}.
- */
- public SecondType getSecond() {
- return second;
- }
-
- @Override
- public boolean equals(Object object) {
- if (object instanceof SimplePair<?, ?>) {
- SimplePair<?, ?> that = (SimplePair<?, ?>) object;
- return areObjectsEqual(this.first, that.first) && areObjectsEqual(this.second, that.second);
- }
- return false;
- }
-
- /**
- * Determines whether two possibly-null objects are equal. Returns:
- *
- * <ul>
- * <li>{@code true} if {@code a} and {@code b} are both null.
- * <li>{@code true} if {@code a} and {@code b} are both non-null and they are
- * equal according to {@link Object#equals(Object)}.
- * <li>{@code false} in all other situations.
- * </ul>
- *
- * <p>This assumes that any non-null objects passed to this function conform
- * to the {@code equals()} contract.
- */
- private static boolean areObjectsEqual(Object a, Object b) {
- return a == b || (a != null && a.equals(b));
- }
-
- @Override
- public int hashCode() {
- int hash1 = first == null ? 0 : first.hashCode();
- int hash2 = second == null ? 0 : second.hashCode();
- return 31 * hash1 + hash2;
- }
-
- /**
- * {@inheritDoc}
- *
- * <p>This implementation returns a string in the form
- * {@code (first, second)}, where {@code first} and {@code second} are the
- * String representations of the first and second elements of this pair, as
- * given by {@link String#valueOf(Object)}. Subclasses are free to override
- * this behavior.
- */
- @Override public String toString() {
- return "(" + first + ", " + second + ")";
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/Status.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/Status.java
deleted file mode 100644
index 0e6d39a9f8e..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/types/Status.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.external.client.types;
-
-/**
- * Information given to about a operation - success, temporary or permanent failure.
- *
- */
-public final class Status {
-
- /** Actual status of the operation: Whether successful, transient or permanent failure. */
- public enum Code {
- /** Operation was successful. */
- SUCCESS,
-
- /**
- * Operation had a transient failure. The application can retry the failed operation later -
- * if it chooses to do so, it must use a sensible backoff policy such as exponential backoff.
- */
- TRANSIENT_FAILURE,
-
- /**
- * Opration has a permanent failure. Application must not automatically retry without fixing
- * the situation (e.g., by presenting a dialog box to the user).
- */
- PERMANENT_FAILURE
- }
-
- /** Success or failure. */
- private final Code code;
-
- /** A message describing why the state was unknown, for debugging. */
- private final String message;
-
- /** Creates a new Status object given the {@code code} and {@code message}. */
- public static Status newInstance(Status.Code code, String message) {
- return new Status(code, message);
- }
-
- private Status(Code code, String message) {
- this.code = code;
- this.message = message;
- }
-
- /** Returns true iff the status corresponds to a successful completion of the operation.*/
- public boolean isSuccess() {
- return code == Code.SUCCESS;
- }
-
- /**
- * Whether the failure is transient for an operation, e.g., for a {@code register} operation.
- * For transient failures, the application can retry the operation but it must use a sensible
- * policy such as exponential backoff so that it does not add significant load to the backend
- * servers.
- */
- public boolean isTransientFailure() {
- return code == Code.TRANSIENT_FAILURE;
- }
-
- /**
- * Whether the failure is transient for an operation, e.g., for a {@code register} operation.
- * See discussion in {@code Status.Code} for permanent and transient failure handling.
- */
- public boolean isPermanentFailure() {
- return code == Code.PERMANENT_FAILURE;
- }
-
- /** A message describing why the state was unknown, for debugging. */
- public String getMessage() {
- return message;
- }
-
- /** Returns the code for this status message. */
- public Code getCode() {
- return code;
- }
-
- @Override
- public String toString() {
- return "Code: " + code + ", " + message;
- }
-
- @Override
- public boolean equals(Object object) {
- if (object == this) {
- return true;
- }
-
- if (!(object instanceof Status)) {
- return false;
- }
-
- final Status other = (Status) object;
- if (code != other.code) {
- return false;
-
- }
- if (message == null) {
- return other.message == null;
- }
- return message.equals(other.message);
- }
-
- @Override
- public int hashCode() {
- return code.hashCode() ^ ((message == null) ? 0 : message.hashCode());
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/testing/android/InvalidationTest.aidl b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/testing/android/InvalidationTest.aidl
deleted file mode 100644
index fb5ab2915a5..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/testing/android/InvalidationTest.aidl
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.testing.android;
-
-import android.os.Bundle;
-
-interface InvalidationTest {
-
- /**
- * Used to set whether the invalidation test service should store incoming
- * actions and outgoing events respectively by {@link getActionEvents()}
- * and {@link getEventIntents()}. If {@code false}, they will be processed
- * and forgotten.
- */
- void setCapture(boolean captureActions, boolean captureEvents);
-
- /**
- * Returns an array of bundle containing the set of invalidation requests
- * received by the test service since the last call to this method.
- */
- Bundle [] getRequests();
-
- /**
- * Returns an array of intents containing the set of invalidation event
- * bundles sent by the test service since the last call to this method.
- */
- Bundle [] getEvents();
-
- /**
- * Instructs the test service to send an event back to the client to support
- * testing of listener functionality.
- */
- void sendEvent(in Bundle eventBundle);
-
- /**
- * Reset all state for the invalidation test service. This will clear all
- * current clients and drop and disable any captured action or event bundles.
- */
- void reset();
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/testing/android/InvalidationTestListener.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/testing/android/InvalidationTestListener.java
deleted file mode 100644
index 8a684d7ce68..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/testing/android/InvalidationTestListener.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.testing.android;
-
-import com.google.ipc.invalidation.external.client.InvalidationClient;
-import com.google.ipc.invalidation.external.client.InvalidationListener;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.AndroidInvalidationClient;
-import com.google.ipc.invalidation.external.client.android.AndroidInvalidationListener;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.external.client.android.service.Event;
-import com.google.ipc.invalidation.external.client.android.service.Response;
-import com.google.ipc.invalidation.external.client.types.AckHandle;
-import com.google.ipc.invalidation.external.client.types.ErrorInfo;
-import com.google.ipc.invalidation.external.client.types.Invalidation;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * TestListener service maintains a mapping of listeners by client key and forwards received events
- * to an InvalidationListener instance. The listener should be registered in
- * {@code Android-Manifest.xml} as follows:
- *
- * {@code
- * <service
- * android:name="com.google.ipc.invalidation.testing.android.InvalidationTestListener">
- * <intent-filter>
- * <action android:name="com.google.ipc.invalidation.EVENTS"/>
- * </intent-filter>
- * </service>
- * }
- *
- */
-public class InvalidationTestListener extends AndroidInvalidationListener {
-
- /** Logger */
- private static final Logger logger = AndroidLogger.forTag("InvTestListener");
-
- private static final Map<String, InvalidationListener> listenerMap =
- new ConcurrentHashMap<String, InvalidationListener>();
-
- /**
- * Creates and returns an intent that is valid for use in creating a new invalidation client
- * that will deliver events to the test listener.
- */
- public static Intent getEventIntent(Context context) {
- Intent eventIntent = new Intent(Event.LISTENER_INTENT);
- ComponentName component = new ComponentName(context.getPackageName(),
- InvalidationTestListener.class.getName());
- eventIntent.setComponent(component);
- return eventIntent;
- }
-
- /**
- * Sets the invalidation listener delegate to receive events for a given clientKey.
- */
- public static void setInvalidationListener(String clientKey, InvalidationListener listener) {
- logger.fine("setListener %s for %s", listener, clientKey);
- listenerMap.put(clientKey, listener);
- }
-
- /**
- * Removes the invalidation listener delegate to receive events for a given clientKey.
- */
- public static void removeInvalidationListener(String clientKey) {
- listenerMap.remove(clientKey);
- }
-
-
- @Override
- protected void handleEvent(Bundle input, Bundle output) {
-
- // Ignore events that target a client key where there is no listener registered
- // It's likely that these are late-delivered events for an earlier test case.
- Event event = new Event(input);
- String clientKey = event.getClientKey();
- if (!listenerMap.containsKey(clientKey)) {
- logger.fine("Ignoring %s event to %s", event.getAction(), clientKey);
- Response.Builder response = Response.newBuilder(event.getActionOrdinal(), output);
- response.setStatus(Response.Status.SUCCESS);
- return;
- }
-
- super.handleEvent(input, output);
- }
-
- @Override
- public void ready(InvalidationClient client) {
- InvalidationListener listener = getListener(client);
- logger.fine("Received READY for %s: %s", getClientKey(client), listener);
- if (listener != null) {
- listener.ready(client);
- }
- }
-
- @Override
- public void invalidate(
- InvalidationClient client, Invalidation invalidation, AckHandle ackHandle) {
- InvalidationListener listener = getListener(client);
- logger.fine("Received INVALIDATE for %s: %s", getClientKey(client), listener);
- if (listener != null) {
- listener.invalidate(client, invalidation, ackHandle);
- }
- }
-
- @Override
- public void invalidateUnknownVersion(
- InvalidationClient client, ObjectId objectId, AckHandle ackHandle) {
- InvalidationListener listener = getListener(client);
- logger.fine("Received INVALIDATE_UNKNOWN_VERSION for %s: %s", getClientKey(client), listener);
- if (listener != null) {
- listener.invalidateUnknownVersion(client, objectId, ackHandle);
- }
- }
-
- @Override
- public void invalidateAll(InvalidationClient client, AckHandle ackHandle) {
- InvalidationListener listener = getListener(client);
- logger.fine("Received INVALIDATE_ALL for %s: %s", getClientKey(client), listener);
- if (listener != null) {
- listener.invalidateAll(client, ackHandle);
- }
- }
-
- @Override
- public void informRegistrationStatus(
- InvalidationClient client, ObjectId objectId, RegistrationState regState) {
- InvalidationListener listener = getListener(client);
- logger.fine("Received INFORM_REGISTRATION_STATUS for %s: %s", getClientKey(client), listener);
- if (listener != null) {
- listener.informRegistrationStatus(client, objectId, regState);
- }
- }
-
- @Override
- public void informRegistrationFailure(
- InvalidationClient client, ObjectId objectId, boolean isTransient, String errorMessage) {
- InvalidationListener listener = getListener(client);
- logger.fine("Received INFORM_REGISTRATION_FAILURE for %s: %s", getClientKey(client), listener);
- if (listener != null) {
- listener.informRegistrationFailure(client, objectId, isTransient, errorMessage);
- }
- }
-
- @Override
- public void reissueRegistrations(InvalidationClient client, byte[] prefix, int prefixLength) {
- InvalidationListener listener = getListener(client);
- logger.fine("Received REISSUE_REGISTRATIONS for %s: %s", getClientKey(client), listener);
- if (listener != null) {
- listener.reissueRegistrations(client, prefix, prefixLength);
- }
- }
-
- @Override
- public void informError(InvalidationClient client, ErrorInfo errorInfo) {
- InvalidationListener listener = getListener(client);
- logger.fine("Received INFORM_ERROR for %s: %s", getClientKey(client), listener);
- if (listener != null) {
- listener.informError(client, errorInfo);
- }
- }
-
- private String getClientKey(InvalidationClient client) {
- return ((AndroidInvalidationClient) client).getClientKey();
- }
-
- private InvalidationListener getListener(InvalidationClient client) {
- String clientKey = getClientKey(client);
- return listenerMap.get(clientKey);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/testing/android/InvalidationTestService.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/testing/android/InvalidationTestService.java
deleted file mode 100644
index 9335b382883..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/testing/android/InvalidationTestService.java
+++ /dev/null
@@ -1,414 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.testing.android;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.external.client.android.service.Event;
-import com.google.ipc.invalidation.external.client.android.service.ListenerBinder;
-import com.google.ipc.invalidation.external.client.android.service.ListenerService;
-import com.google.ipc.invalidation.external.client.android.service.Request;
-import com.google.ipc.invalidation.external.client.android.service.Request.Action;
-import com.google.ipc.invalidation.external.client.android.service.Request.Parameter;
-import com.google.ipc.invalidation.external.client.android.service.Response;
-import com.google.ipc.invalidation.external.client.android.service.ServiceBinder.BoundWork;
-import com.google.ipc.invalidation.ticl.android.AbstractInvalidationService;
-import com.google.ipc.invalidation.util.TypedUtil;
-
-import android.accounts.Account;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.IBinder;
-
-import junit.framework.Assert;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * A stub invalidation service implementation that can be used to test the
- * client library or invalidation applications. The test service will validate
- * all incoming events sent by the client. It also supports the ability to store
- * all incoming action intents and outgoing event intents and make them
- * available for retrieval via the {@link InvalidationTest} interface.
- * <p>
- * The implementation of service intent handling will simply log the invocation
- * and do nothing else.
- *
- */
-public class InvalidationTestService extends AbstractInvalidationService {
-
- private static class ClientState {
- final Account account;
- final String authType;
- final Intent eventIntent;
-
- private ClientState(Account account, String authType, Intent eventIntent) {
- this.account = account;
- this.authType = authType;
- this.eventIntent = eventIntent;
- }
- }
-
- /**
- * Intent that can be used to bind to the InvalidationTest service.
- */
- public static final Intent TEST_INTENT = new Intent("com.google.ipc.invalidation.TEST");
-
- /** Logger */
- private static final Logger logger = AndroidLogger.forTag("InvTestService");
-
- /** Map of currently active clients from key to {@link ClientState} */
- private static Map<String, ClientState> clientMap = new HashMap<String, ClientState>();
-
- /** {@code true} the test service should capture actions */
- private static boolean captureActions;
-
- /** The stored actions that are available for retrieval */
- private static List<Bundle> actions = new ArrayList<Bundle>();
-
- /** {@code true} if the client should capture events */
- private static boolean captureEvents;
-
- /** The stored events that are available for retrieval */
- private static List<Bundle> events = new ArrayList<Bundle>();
-
- /** Lock over all state in all instances. */
- private static final Object LOCK = new Object();
-
- /**
- * InvalidationTest stub to handle calls from clients.
- */
- private final InvalidationTest.Stub testBinder = new InvalidationTest.Stub() {
-
- @Override
- public void setCapture(boolean captureActions, boolean captureEvents) {
- synchronized (LOCK) {
- InvalidationTestService.captureActions = captureActions;
- InvalidationTestService.captureEvents = captureEvents;
- }
- }
-
- @Override
- public Bundle[] getRequests() {
- synchronized (LOCK) {
- logger.fine("Reading actions from %s:%d", actions, actions.size());
- Bundle[] value = new Bundle[actions.size()];
- actions.toArray(value);
- actions.clear();
- return value;
- }
- }
-
- @Override
- public Bundle[] getEvents() {
- synchronized (LOCK) {
- Bundle[] value = new Bundle[events.size()];
- events.toArray(value);
- events.clear();
- return value;
- }
- }
-
- @Override
- public void sendEvent(final Bundle eventBundle) {
- synchronized (LOCK) {
- // Retrive info for that target client
- String clientKey = eventBundle.getString(Parameter.CLIENT);
- ClientState state = clientMap.get(clientKey);
- Preconditions.checkNotNull(state, "No state for %s in %s", clientKey, clientMap.keySet());
-
- // Bind to the listener associated with the client and send the event
- ListenerBinder binder = new ListenerBinder(getBaseContext(), state.eventIntent,
- InvalidationTestListener.class.getName());
- binder.runWhenBound(new BoundWork<ListenerService>() {
- @Override
- public void run(ListenerService service) {
- InvalidationTestService.this.sendEvent(service, new Event(eventBundle));
- }
- });
-
- // Will happen after the runWhenBound invokes the receiver. Could also be done inside
- // the receiver.
- binder.release();
- }
- }
-
- @Override
- public void reset() {
- synchronized (LOCK) {
- logger.info("Resetting test service");
- captureActions = false;
- captureEvents = false;
- clientMap.clear();
- actions.clear();
- events.clear();
- }
- }
- };
-
- @Override
- public void onCreate() {
- synchronized (LOCK) {
- logger.info("onCreate");
- super.onCreate();
- }
- }
-
- @Override
- public void onDestroy() {
- synchronized (LOCK) {
- logger.info("onDestroy");
- super.onDestroy();
- }
- }
-
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- synchronized (LOCK) {
- logger.info("onStart");
- return super.onStartCommand(intent, flags, startId);
- }
- }
-
- @Override
- public IBinder onBind(Intent intent) {
- synchronized (LOCK) {
- logger.info("onBind");
-
- // For InvalidationService binding, delegate to the superclass
- if (Request.SERVICE_INTENT.getAction().equals(intent.getAction())) {
- return super.onBind(intent);
- }
-
- // Otherwise, return the test interface binder
- return testBinder;
- }
- }
-
- @Override
- public boolean onUnbind(Intent intent) {
- synchronized (LOCK) {
- logger.info("onUnbind");
- return super.onUnbind(intent);
- }
- }
-
- @Override
- protected void handleRequest(Bundle input, Bundle output) {
- synchronized (LOCK) {
- super.handleRequest(input, output);
- if (captureActions) {
- actions.add(input);
- }
- validateResponse(input, output);
- }
- }
-
- @Override
- protected void sendEvent(ListenerService listenerService, Event event) {
- synchronized (LOCK) {
- if (captureEvents) {
- events.add(event.getBundle());
- }
- super.sendEvent(listenerService, event);
- }
- }
-
-
- @Override
- protected void create(Request request, Response.Builder response) {
- synchronized (LOCK) {
- validateRequest(request, Action.CREATE, Parameter.ACTION, Parameter.CLIENT,
- Parameter.CLIENT_TYPE, Parameter.ACCOUNT, Parameter.AUTH_TYPE, Parameter.INTENT);
- logger.info("Creating client %s:%s", request.getClientKey(), clientMap.keySet());
- if (!TypedUtil.containsKey(clientMap, request.getClientKey())) {
- // If no client exists with this key, create one.
- clientMap.put(
- request.getClientKey(), new ClientState(request.getAccount(), request.getAuthType(),
- request.getIntent()));
- } else {
- // Otherwise, verify that the existing client has the same account / auth type / intent.
- ClientState existingState = TypedUtil.mapGet(clientMap, request.getClientKey());
- Preconditions.checkState(request.getAccount().equals(existingState.account));
- Preconditions.checkState(request.getAuthType().equals(existingState.authType));
- }
- response.setStatus(Response.Status.SUCCESS);
- }
- }
-
- @Override
- protected void resume(Request request, Response.Builder response) {
- synchronized (LOCK) {
- validateRequest(
- request, Action.RESUME, Parameter.ACTION, Parameter.CLIENT);
- ClientState state = clientMap.get(request.getClientKey());
- if (state != null) {
- logger.info("Resuming client %s:%s", request.getClientKey(), clientMap.keySet());
- response.setStatus(Response.Status.SUCCESS);
- response.setAccount(state.account);
- response.setAuthType(state.authType);
- } else {
- logger.warning("Cannot resume client %s:%s", request.getClientKey(), clientMap.keySet());
- response.setStatus(Response.Status.INVALID_CLIENT);
- }
- }
- }
-
- @Override
- protected void register(Request request, Response.Builder response) {
- synchronized (LOCK) {
- // Ensure that one (and only one) of the variant object id forms is used
- String objectParam =
- request.getBundle().containsKey(Parameter.OBJECT_ID) ?
- Parameter.OBJECT_ID : Parameter.OBJECT_ID_LIST;
- validateRequest(request, Action.REGISTER, Parameter.ACTION, Parameter.CLIENT, objectParam);
- if (!validateClient(request)) {
- response.setStatus(Response.Status.INVALID_CLIENT);
- return;
- }
- response.setStatus(Response.Status.SUCCESS);
- }
- }
-
- @Override
- protected void unregister(Request request, Response.Builder response) {
- synchronized (LOCK) {
- // Ensure that one (and only one) of the variant object id forms is used
- String objectParam =
- request.getBundle().containsKey(Parameter.OBJECT_ID) ?
- Parameter.OBJECT_ID :
- Parameter.OBJECT_ID_LIST;
- validateRequest(request, Action.UNREGISTER, Parameter.ACTION,
- Parameter.CLIENT, objectParam);
- if (!validateClient(request)) {
- response.setStatus(Response.Status.INVALID_CLIENT);
- return;
- }
- response.setStatus(Response.Status.SUCCESS);
- }
- }
-
- @Override
- protected void start(Request request, Response.Builder response) {
- synchronized (LOCK) {
- validateRequest(
- request, Action.START, Parameter.ACTION, Parameter.CLIENT);
- if (!validateClient(request)) {
- response.setStatus(Response.Status.INVALID_CLIENT);
- return;
- }
- response.setStatus(Response.Status.SUCCESS);
- }
- }
-
- @Override
- protected void stop(Request request, Response.Builder response) {
- synchronized (LOCK) {
- validateRequest(request, Action.STOP, Parameter.ACTION, Parameter.CLIENT);
- if (!validateClient(request)) {
- response.setStatus(Response.Status.INVALID_CLIENT);
- return;
- }
- response.setStatus(Response.Status.SUCCESS);
- }
- }
-
- @Override
- protected void acknowledge(Request request, Response.Builder response) {
- synchronized (LOCK) {
- validateRequest(request, Action.ACKNOWLEDGE, Parameter.ACTION, Parameter.CLIENT,
- Parameter.ACK_TOKEN);
- if (!validateClient(request)) {
- response.setStatus(Response.Status.INVALID_CLIENT);
- return;
- }
- response.setStatus(Response.Status.SUCCESS);
- }
- }
-
- @Override
- protected void destroy(Request request, Response.Builder response) {
- synchronized (LOCK) {
- validateRequest(request, Action.DESTROY, Parameter.ACTION, Parameter.CLIENT);
- if (!validateClient(request)) {
- response.setStatus(Response.Status.INVALID_CLIENT);
- return;
- }
- response.setStatus(Response.Status.SUCCESS);
- }
- }
-
- /**
- * Validates that the client associated with the request is one that has
- * previously been created or resumed on the test service.
- */
- private boolean validateClient(Request request) {
- if (!clientMap.containsKey(request.getClientKey())) {
- logger.warning("Client %s is not an active client: %s",
- request.getClientKey(), clientMap.keySet());
- return false;
- }
- return true;
- }
-
- /**
- * Validates that the request contains exactly the set of parameters expected.
- *
- * @param request request to validate
- * @param action expected action
- * @param parameters expected parameters
- */
- private void validateRequest(Request request, Action action, String... parameters) {
- Assert.assertEquals(action, request.getAction());
- List<String> expectedParameters = new ArrayList<String>(Arrays.asList(parameters));
- Bundle requestBundle = request.getBundle();
- for (String parameter : requestBundle.keySet()) {
- Assert.assertTrue("Unexpected parameter: " + parameter, expectedParameters.remove(parameter));
-
- // Validate the value
- Object value = requestBundle.get(parameter);
- Assert.assertNotNull(value);
- }
- Assert.assertTrue("Missing parameter:" + expectedParameters, expectedParameters.isEmpty());
- }
-
- /**
- * Validates a response bundle being returned to a client contains valid
- * success response.
- */
- protected void validateResponse(Bundle input, Bundle output) {
- synchronized (LOCK) {
- int status = output.getInt(Response.Parameter.STATUS, Response.Status.UNKNOWN);
- Assert.assertEquals("Unexpected failure for input = " + input + "; output = " + output,
- Response.Status.SUCCESS, status);
- String error = output.getString(Response.Parameter.ERROR);
- Assert.assertNull(error);
- }
- }
-
- /** Returns whether a client with key {@code clientKey} is known to the service. */
- public static boolean clientExists(String clientKey) {
- synchronized (LOCK) {
- return TypedUtil.containsKey(clientMap, clientKey);
- }
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/BasicSystemResources.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/BasicSystemResources.java
deleted file mode 100644
index d2c3abb25e5..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/BasicSystemResources.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import com.google.ipc.invalidation.external.client.SystemResources;
-
-
-/**
- * A simple implementation of {@code SystemResources} that just takes the resource components
- * and constructs a SystemResources object.
- *
- */
-public class BasicSystemResources implements SystemResources {
-
- // Components comprising the system resources. We delegate calls to these as appropriate.
- private final Scheduler internalScheduler;
- private final Scheduler listenerScheduler;
- private final Logger logger;
- private final NetworkChannel network;
- private final Storage storage;
-
- /** The state of the resources. */
- private RunState runState = new RunState();
-
- /** Information about the client operating system/platform, e.g., Windows, ChromeOS. */
- private final String platform;
-
- /**
- * Constructs an instance from resource components.
- *
- * @param logger implementation of the logger
- * @param internalScheduler scheduler for scheduling the library's internal events
- * @param listenerScheduler scheduler for scheduling the listener's events
- * @param network implementation of the network
- * @param storage implementation of storage
- * @param platform if not {@code null}, platform string for client version. If {@code null},
- * a default string will be constructed.
- */
- public BasicSystemResources(Logger logger, Scheduler internalScheduler,
- Scheduler listenerScheduler, NetworkChannel network, Storage storage,
- String platform) {
- this.logger = logger;
- this.storage = storage;
- this.network = network;
- if (platform != null) {
- this.platform = platform;
- } else {
- // If a platform string was not provided, try to compute a reasonable default.
- this.platform = System.getProperty("os.name") + "/" + System.getProperty("os.version") +
- "/" + System.getProperty("os.arch");
- }
-
- this.internalScheduler = internalScheduler;
- this.listenerScheduler = listenerScheduler;
-
- // Pass a reference to this object to all of the components, so that they can access
- // resources. E.g., so that the network can do logging.
- logger.setSystemResources(this);
- storage.setSystemResources(this);
- network.setSystemResources(this);
- internalScheduler.setSystemResources(this);
- listenerScheduler.setSystemResources(this);
- }
-
- @Override
- public void start() {
- runState.start();
- logger.info("Resources started");
- }
-
- @Override
- public void stop() {
- runState.stop();
- logger.info("Resources stopped");
- }
-
- @Override
- public boolean isStarted() {
- return runState.isStarted();
- }
-
- @Override
- public Logger getLogger() {
- return logger;
- }
-
- @Override
- public Storage getStorage() {
- return storage;
- }
-
- @Override
- public NetworkChannel getNetwork() {
- return network;
- }
-
- @Override
- public Scheduler getInternalScheduler() {
- return internalScheduler;
- }
-
- @Override
- public Scheduler getListenerScheduler() {
- return listenerScheduler;
- }
-
- @Override
- public String getPlatform() {
- return platform;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/CheckingInvalidationListener.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/CheckingInvalidationListener.java
deleted file mode 100644
index 744e1ada582..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/CheckingInvalidationListener.java
+++ /dev/null
@@ -1,178 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import static com.google.ipc.invalidation.external.client.SystemResources.Scheduler.NO_DELAY;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.InvalidationClient;
-import com.google.ipc.invalidation.external.client.InvalidationListener;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.SystemResources.Scheduler;
-import com.google.ipc.invalidation.external.client.types.AckHandle;
-import com.google.ipc.invalidation.external.client.types.ErrorInfo;
-import com.google.ipc.invalidation.external.client.types.Invalidation;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-import com.google.ipc.invalidation.ticl.Statistics.ListenerEventType;
-import com.google.ipc.invalidation.util.NamedRunnable;
-
-
-/**
- * {@link InvalidationListener} wrapper that ensures that a delegate listener is called on the
- * proper thread and calls the listener method on the listener thread.
- *
- */
-class CheckingInvalidationListener implements InvalidationListener {
-
- /** The actual listener to which this listener delegates. */
- private final InvalidationListener delegate;
-
- /** The scheduler for scheduling internal events in the library. */
- private final Scheduler internalScheduler;
-
- /** The scheduler for scheduling events for the delegate. */
- private final Scheduler listenerScheduler;
-
- /** Statistics objects to track number of sent messages, etc. */
- private Statistics statistics;
-
- private final Logger logger;
-
- CheckingInvalidationListener(InvalidationListener delegate, Scheduler internalScheduler,
- Scheduler listenerScheduler, Logger logger) {
- this.delegate = Preconditions.checkNotNull(delegate, "Delegate cannot be null");
- this.internalScheduler = Preconditions.checkNotNull(internalScheduler,
- "Internal scheduler cannot be null");
- this.listenerScheduler = Preconditions.checkNotNull(listenerScheduler,
- "Listener scheduler cannot be null");
- this.logger = Preconditions.checkNotNull(logger, "Logger cannot be null");
- }
-
- void setStatistics(Statistics statistics) {
- this.statistics = Preconditions.checkNotNull(statistics, "Statistics cannot be null");
- }
-
- @Override
- public void invalidate(final InvalidationClient client, final Invalidation invalidation,
- final AckHandle ackHandle) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- Preconditions.checkNotNull(ackHandle);
- listenerScheduler.schedule(NO_DELAY, new NamedRunnable("CheckingInvalListener.invalidate") {
- @Override
- public void run() {
- statistics.recordListenerEvent(ListenerEventType.INVALIDATE);
- delegate.invalidate(client, invalidation, ackHandle);
- }
- });
- }
-
- @Override
- public void invalidateUnknownVersion(final InvalidationClient client, final ObjectId objectId,
- final AckHandle ackHandle) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- Preconditions.checkNotNull(ackHandle);
- listenerScheduler.schedule(NO_DELAY,
- new NamedRunnable("CheckingInvalListener.invalidateUnknownVersion") {
- @Override
- public void run() {
- statistics.recordListenerEvent(ListenerEventType.INVALIDATE_UNKNOWN);
- delegate.invalidateUnknownVersion(client, objectId, ackHandle);
- }
- });
- }
-
- @Override
- public void invalidateAll(final InvalidationClient client, final AckHandle ackHandle) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- Preconditions.checkNotNull(ackHandle);
- listenerScheduler.schedule(NO_DELAY, new NamedRunnable("CheckingInvalListener.invalidateAll") {
- @Override
- public void run() {
- statistics.recordListenerEvent(ListenerEventType.INVALIDATE_ALL);
- delegate.invalidateAll(client, ackHandle);
- }
- });
- }
-
- @Override
- public void informRegistrationFailure(final InvalidationClient client, final ObjectId objectId,
- final boolean isTransient, final String errorMessage) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- listenerScheduler.schedule(NO_DELAY, new NamedRunnable("CheckingInvalListener.regFailure") {
- @Override
- public void run() {
- statistics.recordListenerEvent(ListenerEventType.INFORM_REGISTRATION_FAILURE);
- delegate.informRegistrationFailure(client, objectId, isTransient, errorMessage);
- }
- });
- }
-
- @Override
- public void informRegistrationStatus(final InvalidationClient client, final ObjectId objectId,
- final RegistrationState regState) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- listenerScheduler.schedule(NO_DELAY, new NamedRunnable("CheckingInvalListener.regStatus") {
- @Override
- public void run() {
- statistics.recordListenerEvent(ListenerEventType.INFORM_REGISTRATION_STATUS);
- delegate.informRegistrationStatus(client, objectId, regState);
- }
- });
- }
-
- @Override
- public void reissueRegistrations(final InvalidationClient client, final byte[] prefix,
- final int prefixLen) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- listenerScheduler.schedule(NO_DELAY, new NamedRunnable("CheckingInvalListener.reissueRegs") {
- @Override
- public void run() {
- statistics.recordListenerEvent(ListenerEventType.REISSUE_REGISTRATIONS);
- delegate.reissueRegistrations(client, prefix, prefixLen);
- }
- });
- }
-
- @Override
- public void informError(final InvalidationClient client, final ErrorInfo errorInfo) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- listenerScheduler.schedule(NO_DELAY, new NamedRunnable("CheckingInvalListener.informError") {
- @Override
- public void run() {
- statistics.recordListenerEvent(ListenerEventType.INFORM_ERROR);
- delegate.informError(client, errorInfo);
- }
- });
- }
-
- /** Returns the delegate {@link InvalidationListener}. */
- InvalidationListener getDelegate() {
- return delegate;
- }
-
- @Override
- public void ready(final InvalidationClient client) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- listenerScheduler.schedule(NO_DELAY, new NamedRunnable("CheckingInvalListener.ready") {
- @Override
- public void run() {
- logger.info("Informing app that ticl is ready");
- delegate.ready(client);
- }
- });
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/DigestStore.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/DigestStore.java
deleted file mode 100644
index 05bde244140..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/DigestStore.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import java.util.Collection;
-
-/**
- * Interface for a store that allows objects to be added/removed along with
- * the ability to get the digest for the whole or partial set of those objects.
- *
- * @param <ElementType> the type of the element stored in this
- *
- */
-public interface DigestStore<ElementType> {
-
- /** Returns the number of elements. */
- int size();
-
- /** Returns whether {@code element} is in the store. */
- boolean contains(ElementType element);
-
- /**
- * Returns a digest of the desired objects.
- * <p>
- * NOTE: the digest computations <b>MUST NOT</b> depend on the order in which the elements
- * were added.
- */
- byte[] getDigest();
-
- /**
- * Returns the elements whose digest prefixes begin with the bit prefix {@code digestPrefix}.
- * {@code prefixLen} is the length of {@code digestPrefix} in bits, which may be less than
- * {@code digestPrefix.length} (and may be 0). The implementing class can return *more* objects
- * than what has been specified by {@code digestPrefix}, e.g., it could return all the objects
- * in the store.
- */
- Collection<ElementType> getElements(byte[] digestPrefix, int prefixLen);
-
- /**
- * Adds {@code element} to the store. No-op if {@code element} is already present.
- * @return whether the element was added
- */
- boolean add(ElementType element);
-
- /**
- * Adds {@code elements} to the store. If any element in {@code elements} is already present,
- * the addition is a no-op for that element.
- * @return the elements that were added
- */
- Collection<ElementType> add(Collection<ElementType> elements);
-
- /**
- * Removes {@code element} from the store. No-op if {@code element} is not present.
- * @return whether the element was removed
- */
- boolean remove(ElementType element);
-
- /**
- * Remove {@code elements} to the store. If any element in {@code elements} is not present, the
- * removal is a no-op for that element.
- * @return the elements that were removed
- */
- Collection<ElementType> remove(Collection<ElementType> elements);
-
- /** Removes all elements in this and returns them. */
- Collection<ElementType> removeAll();
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/InvalidationClientCore.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/InvalidationClientCore.java
deleted file mode 100644
index b20353b4b95..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/InvalidationClientCore.java
+++ /dev/null
@@ -1,1563 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import static com.google.ipc.invalidation.external.client.SystemResources.Scheduler.NO_DELAY;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.common.CommonInvalidationConstants2;
-import com.google.ipc.invalidation.common.CommonProtoStrings2;
-import com.google.ipc.invalidation.common.CommonProtos2;
-import com.google.ipc.invalidation.common.DigestFunction;
-import com.google.ipc.invalidation.common.ObjectIdDigestUtils;
-import com.google.ipc.invalidation.common.TiclMessageValidator2;
-import com.google.ipc.invalidation.external.client.InvalidationListener;
-import com.google.ipc.invalidation.external.client.InvalidationListener.RegistrationState;
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.SystemResources.NetworkChannel;
-import com.google.ipc.invalidation.external.client.SystemResources.Scheduler;
-import com.google.ipc.invalidation.external.client.SystemResources.Storage;
-import com.google.ipc.invalidation.external.client.types.AckHandle;
-import com.google.ipc.invalidation.external.client.types.Callback;
-import com.google.ipc.invalidation.external.client.types.ErrorInfo;
-import com.google.ipc.invalidation.external.client.types.Invalidation;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-import com.google.ipc.invalidation.external.client.types.SimplePair;
-import com.google.ipc.invalidation.external.client.types.Status;
-import com.google.ipc.invalidation.ticl.ProtocolHandler.ParsedMessage;
-import com.google.ipc.invalidation.ticl.ProtocolHandler.ProtocolListener;
-import com.google.ipc.invalidation.ticl.ProtocolHandler.ServerMessageHeader;
-import com.google.ipc.invalidation.ticl.Statistics.ClientErrorType;
-import com.google.ipc.invalidation.ticl.Statistics.IncomingOperationType;
-import com.google.ipc.invalidation.ticl.Statistics.ReceivedMessageType;
-import com.google.ipc.invalidation.util.Box;
-import com.google.ipc.invalidation.util.Bytes;
-import com.google.ipc.invalidation.util.InternalBase;
-import com.google.ipc.invalidation.util.Marshallable;
-import com.google.ipc.invalidation.util.Smearer;
-import com.google.ipc.invalidation.util.TextBuilder;
-import com.google.ipc.invalidation.util.TypedUtil;
-import com.google.protobuf.ByteString;
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protos.ipc.invalidation.Channel.NetworkEndpointId;
-import com.google.protos.ipc.invalidation.Client.AckHandleP;
-import com.google.protos.ipc.invalidation.Client.ExponentialBackoffState;
-import com.google.protos.ipc.invalidation.Client.PersistentTiclState;
-import com.google.protos.ipc.invalidation.Client.RunStateP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ApplicationClientIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientConfigP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ErrorMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InfoRequestMessage.InfoType;
-import com.google.protos.ipc.invalidation.ClientProtocol.InvalidationP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ObjectIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationP;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationP.OpType;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationStatus;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSubtree;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSummary;
-import com.google.protos.ipc.invalidation.JavaClient.InvalidationClientState;
-import com.google.protos.ipc.invalidation.JavaClient.ProtocolHandlerState;
-import com.google.protos.ipc.invalidation.JavaClient.RecurringTaskState;
-import com.google.protos.ipc.invalidation.JavaClient.RegistrationManagerStateP;
-import com.google.protos.ipc.invalidation.JavaClient.StatisticsState;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.Set;
-import java.util.logging.Level;
-
-
-/**
- * Core implementation of the Invalidation Client Library (Ticl). Subclasses are required
- * to implement concurrency control for the Ticl.
- *
- */
-public abstract class InvalidationClientCore extends InternalBase
- implements Marshallable<InvalidationClientState>, ProtocolListener,
- TestableInvalidationClient {
-
- /**
- * A subclass of {@link RecurringTask} with simplified constructors to provide common
- * parameters automatically (scheduler, logger, smearer).
- */
- private abstract class TiclRecurringTask extends RecurringTask {
- /**
- * Constructs a task with {@code initialDelayMs} and {@code timeoutDelayMs}. If
- * {@code useExponentialBackoff}, an exponential backoff generator with initial delay
- * {@code timeoutDelayMs} is used as well; if not, exponential backoff is not used.
- */
- TiclRecurringTask(String name, int initialDelayMs, int timeoutDelayMs,
- boolean useExponentialBackoff) {
- super(name, internalScheduler, logger, smearer,
- useExponentialBackoff ? createExpBackOffGenerator(timeoutDelayMs, null) : null,
- initialDelayMs, timeoutDelayMs);
- }
-
- /**
- * Constructs an instance from {@code marshalledState} that does not use exponential backoff.
- * @param name name of the recurring task
- */
- private TiclRecurringTask(String name, RecurringTaskState marshalledState) {
- super(name, internalScheduler, logger, smearer, null, marshalledState);
- }
-
- /**
- * Constructs an instance from {@code marshalledState} that uses exponential backoff with an
- * initial backoff of {@code timeoutMs}.
- *
- * @param name name of the recurring task
- */
- private TiclRecurringTask(String name, int timeoutMs, RecurringTaskState marshalledState) {
- super(name, internalScheduler, logger, smearer,
- createExpBackOffGenerator(timeoutMs, marshalledState.getBackoffState()), marshalledState);
- }
- }
-
- /** A task for acquiring tokens from the server. */
- private class AcquireTokenTask extends TiclRecurringTask {
- private static final String TASK_NAME = "AcquireToken";
-
- AcquireTokenTask() {
- super(TASK_NAME, NO_DELAY, config.getNetworkTimeoutDelayMs(), true);
- }
-
- AcquireTokenTask(RecurringTaskState marshalledState) {
- super(TASK_NAME, config.getNetworkTimeoutDelayMs(), marshalledState);
- }
-
- @Override
- public boolean runTask() {
- // If token is still not assigned (as expected), sends a request. Otherwise, ignore.
- if (clientToken == null) {
- // Allocate a nonce and send a message requesting a new token.
- setNonce(generateNonce(random));
- protocolHandler.sendInitializeMessage(applicationClientId, nonce, batchingTask, TASK_NAME);
- return true; // Reschedule to check state, retry if necessary after timeout.
- } else {
- return false; // Don't reschedule.
- }
- }
- }
-
- /**
- * A task that schedules heartbeats when the registration summary at the client is not
- * in sync with the registration summary from the server.
- */
- private class RegSyncHeartbeatTask extends TiclRecurringTask {
- private static final String TASK_NAME = "RegSyncHeartbeat";
-
- RegSyncHeartbeatTask() {
- super(TASK_NAME, config.getNetworkTimeoutDelayMs(), config.getNetworkTimeoutDelayMs(), true);
- }
-
- RegSyncHeartbeatTask(RecurringTaskState marshalledState) {
- super(TASK_NAME, config.getNetworkTimeoutDelayMs(), marshalledState);
- }
-
- @Override
- public boolean runTask() {
- if (!registrationManager.isStateInSyncWithServer()) {
- // Simply send an info message to ensure syncing happens.
- logger.info("Registration state not in sync with server: %s", registrationManager);
- sendInfoMessageToServer(false, true /* request server summary */);
- return true;
- } else {
- logger.info("Not sending message since state is now in sync");
- return false;
- }
- }
- }
-
- /** A task that writes the token to persistent storage. */
- private class PersistentWriteTask extends TiclRecurringTask {
- /*
- * This class implements a "train" of events that attempt to reliably write state to
- * storage. The train continues until runTask encounters a termination condition, in
- * which the state currently in memory and the state currently in storage match.
- */
-
- private static final String TASK_NAME = "PersistentWrite";
-
- /** The last client token that was written to to persistent state successfully. */
- private final Box<ProtoWrapper<PersistentTiclState>> lastWrittenState =
- Box.of(ProtoWrapper.of(PersistentTiclState.getDefaultInstance()));
-
- PersistentWriteTask() {
- super(TASK_NAME, NO_DELAY, config.getWriteRetryDelayMs(), true);
- }
-
- PersistentWriteTask(RecurringTaskState marshalledState) {
- super(TASK_NAME, config.getWriteRetryDelayMs(), marshalledState);
- }
-
- @Override
- public boolean runTask() {
- if (clientToken == null) {
- // We cannot write without a token. We must do this check before creating the
- // PersistentTiclState because newPersistentTiclState cannot handle null tokens.
- return false;
- }
-
- // Compute the state that we will write if we decide to go ahead with the write.
- final ProtoWrapper<PersistentTiclState> state =
- ProtoWrapper.of(CommonProtos2.newPersistentTiclState(clientToken, lastMessageSendTimeMs));
- byte[] serializedState = PersistenceUtils.serializeState(state.getProto(), digestFn);
-
- // Decide whether or not to do the write. The decision varies depending on whether or
- // not the channel supports offline delivery. If we decide not to do the write, then
- // that means the in-memory and stored state match semantically, and the train stops.
- if (config.getChannelSupportsOfflineDelivery()) {
- // For offline delivery, we want the entire state to match, since we write the last
- // send time for every message.
- if (state.equals(lastWrittenState.get())) {
- return false;
- }
- } else {
- // If we do not support offline delivery, we avoid writing the state on each message, and
- // we avoid checking the last-sent time (we check only the client token).
- if (state.getProto().getClientToken().equals(
- lastWrittenState.get().getProto().getClientToken())) {
- return false;
- }
- }
-
- // We decided to do the write.
- storage.writeKey(CLIENT_TOKEN_KEY, serializedState, new Callback<Status>() {
- @Override
- public void accept(Status status) {
- logger.info("Write state completed: %s for %s", status, state.getProto());
- Preconditions.checkState(resources.getInternalScheduler().isRunningOnThread());
- if (status.isSuccess()) {
- // Set lastWrittenToken to be the token that was written (NOT clientToken - which
- // could have changed while the write was happening).
- lastWrittenState.set(state);
- } else {
- statistics.recordError(ClientErrorType.PERSISTENT_WRITE_FAILURE);
- }
- }
- });
- return true; // Reschedule after timeout to make sure that write does happen.
- }
- }
-
- /** A task for sending heartbeats to the server. */
- private class HeartbeatTask extends TiclRecurringTask {
- private static final String TASK_NAME = "Heartbeat";
-
- /** Next time that the performance counters are sent to the server. */
- private long nextPerformanceSendTimeMs;
-
- HeartbeatTask() {
- super(TASK_NAME, config.getHeartbeatIntervalMs(), NO_DELAY, false);
- }
-
- HeartbeatTask(RecurringTaskState marshalledState) {
- super(TASK_NAME, marshalledState);
- }
-
- @Override
- public boolean runTask() {
- // Send info message. If needed, send performance counters and reset the next performance
- // counter send time.
- logger.info("Sending heartbeat to server: %s", this);
- boolean mustSendPerfCounters =
- nextPerformanceSendTimeMs > internalScheduler.getCurrentTimeMs();
- if (mustSendPerfCounters) {
- this.nextPerformanceSendTimeMs = internalScheduler.getCurrentTimeMs() +
- getSmearer().getSmearedDelay(config.getPerfCounterDelayMs());
- }
- sendInfoMessageToServer(mustSendPerfCounters, !registrationManager.isStateInSyncWithServer());
- return true; // Reschedule.
- }
- }
-
- /** The task that is scheduled to send batched messages to the server (when needed). **/
-
- static class BatchingTask extends RecurringTask {
- /*
- * This class is static and extends RecurringTask directly so that it can be instantiated
- * independently in ProtocolHandlerTest.
- */
- private static final String TASK_NAME = "Batching";
-
- /** {@link ProtocolHandler} instance from which messages will be pulled. */
- private final ProtocolHandler protocolHandler;
-
- /** Creates a new instance with default state. */
- BatchingTask(ProtocolHandler protocolHandler, SystemResources resources, Smearer smearer,
- int batchingDelayMs) {
- super(TASK_NAME, resources.getInternalScheduler(), resources.getLogger(), smearer, null,
- batchingDelayMs, NO_DELAY);
- this.protocolHandler = protocolHandler;
- }
-
- /** Creates a new instance with state from {@code marshalledState}. */
- BatchingTask(ProtocolHandler protocolHandler, SystemResources resources, Smearer smearer,
- RecurringTaskState marshalledState) {
- super(TASK_NAME, resources.getInternalScheduler(), resources.getLogger(), smearer, null,
- marshalledState);
- this.protocolHandler = protocolHandler;
- }
-
- @Override
- public boolean runTask() {
- protocolHandler.sendMessageToServer();
- return false; // Don't reschedule.
- }
- }
-
- /**
- * A (slightly strange) recurring task that executes exactly once for the first heartbeat
- * performed by a Ticl restarting from persistent state. The Android Ticl implementation
- * requires that all work to be scheduled in the future occur in the form of a recurring task,
- * hence this class.
- */
- private class InitialPersistentHeartbeatTask extends TiclRecurringTask {
- private static final String TASK_NAME = "InitialPersistentHeartbeat";
-
- InitialPersistentHeartbeatTask(int delayMs) {
- super(TASK_NAME, delayMs, NO_DELAY, false);
- }
-
- @Override
- public boolean runTask() {
- sendInfoMessageToServer(false, true);
- return false; // Don't reschedule.
- }
- }
-
- //
- // End of nested classes.
- //
-
- /** The single key used to write all the Ticl state. */
-
- public static final String CLIENT_TOKEN_KEY = "ClientToken";
-
- /** Resources for the Ticl. */
- private final SystemResources resources;
-
- /**
- * Reference into the resources object for cleaner code. All Ticl code must execute on this
- * scheduler.
- */
- private final Scheduler internalScheduler;
-
- /** Logger reference into the resources object for cleaner code. */
- private final Logger logger;
-
- /** Storage for the Ticl persistent state. */
- Storage storage;
-
- /** Application callback interface. */
- final InvalidationListener listener;
-
- /** Configuration for this instance. */
- private ClientConfigP config;
-
- /** Application identifier for this client. */
- private final ApplicationClientIdP applicationClientId;
-
- /** Object maintaining the registration state for this client. */
- private final RegistrationManager registrationManager;
-
- /** Object handling low-level wire format interactions. */
- private final ProtocolHandler protocolHandler;
-
- /** Used to validate messages */
- private final TiclMessageValidator2 msgValidator;
-
- /** The function for computing the registration and persistence state digests. */
- private final DigestFunction digestFn = new ObjectIdDigestUtils.Sha1DigestFunction();
-
- /** The state of the Ticl whether it has started or not. */
- private final RunState ticlState;
-
- /** Statistics objects to track number of sent messages, etc. */
- final Statistics statistics;
-
- /** A smearer to make sure that delays are randomized a little bit. */
- private final Smearer smearer;
-
- /** Current client token known from the server. */
- private ByteString clientToken = null;
-
- // After the client starts, exactly one of nonce and clientToken is non-null.
-
- /** If not {@code null}, nonce for pending identifier request. */
- private ByteString nonce = null;
-
- /** Whether we should send registrations to the server or not. */
- private boolean shouldSendRegistrations;
-
- /** Whether the network is online. Assume so when we start. */
- private boolean isOnline = true;
-
- /** A random number generator. */
- private final Random random;
-
- /** Last time a message was sent to the server. */
- private long lastMessageSendTimeMs = 0;
-
- /** A task for acquiring the token (if the client has no token). */
- private AcquireTokenTask acquireTokenTask;
-
- /** Task for checking if reg summary is out of sync and then sending a heartbeat to the server. */
- private RegSyncHeartbeatTask regSyncHeartbeatTask;
-
- /** Task for writing the state blob to persistent storage. */
- private PersistentWriteTask persistentWriteTask;
-
- /** A task for periodic heartbeats. */
- private HeartbeatTask heartbeatTask;
-
- /** Task to send all batched messages to the server. */
- private BatchingTask batchingTask;
-
- /** Task to do the first heartbeat after a persistent restart. */
- private InitialPersistentHeartbeatTask initialPersistentHeartbeatTask;
-
- /**
- * Constructs a client.
- *
- * @param resources resources to use during execution
- * @param random a random number generator
- * @param clientType client type code
- * @param clientName application identifier for the client
- * @param config configuration for the client
- * @param applicationName name of the application using the library (for debugging/monitoring)
- * @param regManagerState marshalled registration manager state, if any
- * @param protocolHandlerState marshalled protocol handler state, if any
- * @param listener application callback
- */
- private InvalidationClientCore(final SystemResources resources, Random random, int clientType,
- final byte[] clientName, ClientConfigP config, String applicationName,
- RunStateP ticlRunState,
- RegistrationManagerStateP regManagerState,
- ProtocolHandlerState protocolHandlerState,
- StatisticsState statisticsState,
- InvalidationListener listener) {
- this.resources = Preconditions.checkNotNull(resources);
- this.random = random;
- this.logger = Preconditions.checkNotNull(resources.getLogger());
- this.internalScheduler = resources.getInternalScheduler();
- this.storage = resources.getStorage();
- this.config = config;
- this.ticlState = (ticlRunState == null) ? new RunState() : new RunState(ticlRunState);
- this.smearer = new Smearer(random, this.config.getSmearPercent());
- this.applicationClientId =
- CommonProtos2.newApplicationClientIdP(clientType, ByteString.copyFrom(clientName));
- this.listener = listener;
- this.msgValidator = new TiclMessageValidator2(resources.getLogger());
- this.statistics = (statisticsState != null) ?
- Statistics.deserializeStatistics(resources.getLogger(), statisticsState.getCounterList()) :
- new Statistics();
- this.registrationManager = new RegistrationManager(logger, statistics, digestFn,
- regManagerState);
- this.protocolHandler = new ProtocolHandler(config.getProtocolHandlerConfig(), resources,
- smearer, statistics, clientType, applicationName, this, msgValidator, protocolHandlerState);
- }
-
- /**
- * Constructs a client with default state.
- *
- * @param resources resources to use during execution
- * @param random a random number generator
- * @param clientType client type code
- * @param clientName application identifier for the client
- * @param config configuration for the client
- * @param applicationName name of the application using the library (for debugging/monitoring)
- * @param listener application callback
- */
- public InvalidationClientCore(final SystemResources resources, Random random, int clientType,
- final byte[] clientName, ClientConfigP config, String applicationName,
- InvalidationListener listener) {
- this(resources, random, clientType, clientName, config, applicationName, null, null, null, null,
- listener);
- createSchedulingTasks(null);
- registerWithNetwork(resources);
- logger.info("Created client: %s", this);
- }
-
- /**
- * Constructs a client with state initialized from {@code marshalledState}.
- *
- * @param resources resources to use during execution
- * @param random a random number generator
- * @param clientType client type code
- * @param clientName application identifier for the client
- * @param config configuration for the client
- * @param applicationName name of the application using the library (for debugging/monitoring)
- * @param listener application callback
- */
- public InvalidationClientCore(final SystemResources resources, Random random, int clientType,
- final byte[] clientName, ClientConfigP config, String applicationName,
- InvalidationClientState marshalledState, InvalidationListener listener) {
- this(resources, random, clientType, clientName, config, applicationName,
- marshalledState.getRunState(), marshalledState.getRegistrationManagerState(),
- marshalledState.getProtocolHandlerState(), marshalledState.getStatisticsState(), listener);
- // Unmarshall.
- if (marshalledState.hasClientToken()) {
- clientToken = marshalledState.getClientToken();
- }
- if (marshalledState.hasNonce()) {
- nonce = marshalledState.getNonce();
- }
- this.shouldSendRegistrations = marshalledState.getShouldSendRegistrations();
- this.lastMessageSendTimeMs = marshalledState.getLastMessageSendTimeMs();
- this.isOnline = marshalledState.getIsOnline();
- createSchedulingTasks(marshalledState);
-
- // We register with the network after unmarshalling our isOnline value. This is because when
- // we register with the network, it may give us a new value for isOnline. If we unmarshalled
- // after registering, then we would clobber the new value with the old marshalled value, which
- // is wrong.
- registerWithNetwork(resources);
- logger.info("Created client: %s", this);
- }
-
- /**
- * Registers handlers for received messages and network status changes with the network of
- * {@code resources}.
- */
- private void registerWithNetwork(final SystemResources resources) {
- resources.getNetwork().setListener(new NetworkChannel.NetworkListener() {
- @Override
- public void onMessageReceived(byte[] incomingMessage) {
- final String name = "handleIncomingMessage";
- InvalidationClientCore.this.handleIncomingMessage(incomingMessage);
- }
- @Override
- public void onOnlineStatusChange(boolean isOnline) {
- InvalidationClientCore.this.handleNetworkStatusChange(isOnline);
- }
- @Override
- public void onAddressChange() {
- // Send a message to the server. The header will include the new network address.
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- sendInfoMessageToServer(false, false);
- }
- });
- }
-
- /** Returns a default config builder for the client. */
- public static ClientConfigP.Builder createConfig() {
- return ClientConfigP.newBuilder()
- .setVersion(CommonProtos2.newVersion(CommonInvalidationConstants2.CONFIG_MAJOR_VERSION,
- CommonInvalidationConstants2.CONFIG_MINOR_VERSION))
- .setProtocolHandlerConfig(ProtocolHandler.createConfig());
- }
-
- /** Returns a configuration builder with parameters set for unit tests. */
- public static ClientConfigP.Builder createConfigForTest() {
- return ClientConfigP.newBuilder()
- .setVersion(CommonProtos2.newVersion(CommonInvalidationConstants2.CONFIG_MAJOR_VERSION,
- CommonInvalidationConstants2.CONFIG_MINOR_VERSION))
- .setProtocolHandlerConfig(ProtocolHandler.createConfigForTest())
- .setNetworkTimeoutDelayMs(2 * 1000)
- .setHeartbeatIntervalMs(5 * 1000)
- .setWriteRetryDelayMs(500);
- }
-
- /**
- * Creates the tasks used by the Ticl for token acquisition, heartbeats, persistent writes and
- * registration sync.
- *
- * @param marshalledState saved state of recurring tasks
- */
- private void createSchedulingTasks(InvalidationClientState marshalledState) {
- if (marshalledState == null) {
- this.acquireTokenTask = new AcquireTokenTask();
- this.heartbeatTask = new HeartbeatTask();
- this.regSyncHeartbeatTask = new RegSyncHeartbeatTask();
- this.persistentWriteTask = new PersistentWriteTask();
- this.batchingTask = new BatchingTask(protocolHandler, resources, smearer,
- config.getProtocolHandlerConfig().getBatchingDelayMs());
- } else {
- this.acquireTokenTask = new AcquireTokenTask(marshalledState.getAcquireTokenTaskState());
- this.heartbeatTask = new HeartbeatTask(marshalledState.getHeartbeatTaskState());
- this.regSyncHeartbeatTask =
- new RegSyncHeartbeatTask(marshalledState.getRegSyncHeartbeatTaskState());
- this.persistentWriteTask =
- new PersistentWriteTask(marshalledState.getPersistentWriteTaskState());
- this.batchingTask = new BatchingTask(protocolHandler, resources, smearer,
- marshalledState.getBatchingTaskState());
- if (marshalledState.hasLastWrittenState()) {
- persistentWriteTask.lastWrittenState.set(
- ProtoWrapper.of(marshalledState.getLastWrittenState()));
- }
- }
- // The handling of new InitialPersistentHeartbeatTask is a little strange. We create one when
- // the Ticl is first created so that it can be called by the scheduler if it had been scheduled
- // in the past. Otherwise, when we are ready to schedule one ourselves, we create a new instance
- // with the proper delay, then schedule it. We have to do this because we don't know what delay
- // to use here, since we don't compute it until start().
- this.initialPersistentHeartbeatTask = new InitialPersistentHeartbeatTask(0);
- }
-
- /** Returns the configuration used by the client. */
- protected ClientConfigP getConfig() {
- return config;
- }
-
- // Methods for TestableInvalidationClient.
-
- @Override
-
- public ClientConfigP getConfigForTest() {
- return getConfig();
- }
-
- @Override
-
- public byte[] getApplicationClientIdForTest() {
- return applicationClientId.toByteArray();
- }
-
- /** Returns the application client id of this client. */
- protected ApplicationClientIdP getApplicationClientIdP() {
- return applicationClientId;
- }
-
- @Override
-
- public InvalidationListener getInvalidationListenerForTest() {
- return (listener instanceof CheckingInvalidationListener) ?
- ((CheckingInvalidationListener) this.listener).getDelegate() : this.listener;
- }
-
-
- public SystemResources getResourcesForTest() {
- return resources;
- }
-
- public SystemResources getResources() {
- return resources;
- }
-
- @Override
-
- public Statistics getStatisticsForTest() {
- return statistics;
- }
-
- Statistics getStatistics() {
- return statistics;
- }
-
- @Override
-
- public DigestFunction getDigestFunctionForTest() {
- return this.digestFn;
- }
-
- @Override
-
- public long getNextMessageSendTimeMsForTest() {
- Preconditions.checkState(resources.getInternalScheduler().isRunningOnThread());
- return protocolHandler.getNextMessageSendTimeMsForTest();
- }
-
- @Override
-
- public RegistrationManagerState getRegistrationManagerStateCopyForTest() {
- Preconditions.checkState(resources.getInternalScheduler().isRunningOnThread());
- return registrationManager.getRegistrationManagerStateCopyForTest(
- new ObjectIdDigestUtils.Sha1DigestFunction());
- }
-
- @Override
-
- public void changeNetworkTimeoutDelayForTest(int networkTimeoutDelayMs) {
- config = ClientConfigP.newBuilder(config).setNetworkTimeoutDelayMs(networkTimeoutDelayMs)
- .build();
- createSchedulingTasks(null);
- }
-
- @Override
-
- public void changeHeartbeatDelayForTest(int heartbeatDelayMs) {
- config = ClientConfigP.newBuilder(config).setHeartbeatIntervalMs(heartbeatDelayMs).build();
- createSchedulingTasks(null);
- }
-
- @Override
-
- public void setDigestStoreForTest(DigestStore<ObjectIdP> digestStore) {
- Preconditions.checkState(!resources.isStarted());
- registrationManager.setDigestStoreForTest(digestStore);
- }
-
- @Override
-
- public ByteString getClientTokenForTest() {
- return getClientToken();
- }
-
- @Override
-
- public String getClientTokenKeyForTest() {
- return CLIENT_TOKEN_KEY;
- }
-
- @Override
- public boolean isStartedForTest() {
- return isStarted();
- }
-
- /**
- * Returns whether the Ticl is started, i.e., whether it at some point had a session with the
- * data center after being constructed.
- */
- protected boolean isStarted() {
- return ticlState.isStarted();
- }
-
- @Override
- public void stopResources() {
- resources.stop();
- }
-
- @Override
- public long getResourcesTimeMs() {
- return resources.getInternalScheduler().getCurrentTimeMs();
- }
-
- @Override
- public Scheduler getInternalSchedulerForTest() {
- return resources.getInternalScheduler();
- }
-
- @Override
- public Storage getStorage() {
- return storage;
- }
-
- @Override
- public NetworkEndpointId getNetworkIdForTest() {
- NetworkChannel network = resources.getNetwork();
- if (!(network instanceof TestableNetworkChannel)) {
- throw new UnsupportedOperationException(
- "getNetworkIdForTest requires a TestableNetworkChannel, not: " + network.getClass());
- }
- return ((TestableNetworkChannel) network).getNetworkIdForTest();
- }
-
- // End of methods for TestableInvalidationClient
-
- @Override // InvalidationClient
- public void start() {
- Preconditions.checkState(resources.isStarted(), "Resources must be started before starting " +
- "the Ticl");
- if (ticlState.isStarted()) {
- logger.severe("Ignoring start call since already started: client = %s", this);
- return;
- }
-
- // Initialize the nonce so that we can maintain the invariant that exactly one of
- // "nonce" and "clientToken" is non-null.
- setNonce(generateNonce(random));
-
- logger.info("Starting with Java config: %s", config);
- // Read the state blob and then schedule startInternal once the value is there.
- scheduleStartAfterReadingStateBlob();
- }
-
- /**
- * Implementation of {@link #start} on the internal thread with the persistent
- * {@code serializedState} if any. Starts the TICL protocol and makes the TICL ready to receive
- * registrations, invalidations, etc.
- */
- private void startInternal(byte[] serializedState) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
-
- // Initialize the session manager using the persisted client token.
- PersistentTiclState persistentState =
- (serializedState == null) ? null : PersistenceUtils.deserializeState(logger,
- serializedState, digestFn);
-
- if ((serializedState != null) && (persistentState == null)) {
- // In this case, we'll proceed as if we had no persistent state -- i.e., obtain a new client
- // id from the server.
- statistics.recordError(ClientErrorType.PERSISTENT_DESERIALIZATION_FAILURE);
- logger.severe("Failed deserializing persistent state: %s",
- CommonProtoStrings2.toLazyCompactString(serializedState));
- }
- if (persistentState != null) {
- // If we have persistent state, use the previously-stored token and send a heartbeat to
- // let the server know that we've restarted, since we may have been marked offline.
-
- // In the common case, the server will already have all of our
- // registrations, but we won't know for sure until we've gotten its summary.
- // We'll ask the application for all of its registrations, but to avoid
- // making the registrar redo the work of performing registrations that
- // probably already exist, we'll suppress sending them to the registrar.
- logger.info("Restarting from persistent state: %s",
- CommonProtoStrings2.toLazyCompactString(persistentState.getClientToken()));
- setNonce(null);
- setClientToken(persistentState.getClientToken());
- shouldSendRegistrations = false;
-
- // Schedule an info message for the near future.
- int initialHeartbeatDelayMs = computeInitialPersistentHeartbeatDelayMs(
- config, resources, persistentState.getLastMessageSendTimeMs());
- initialPersistentHeartbeatTask = new InitialPersistentHeartbeatTask(initialHeartbeatDelayMs);
- initialPersistentHeartbeatTask.ensureScheduled("");
-
- // We need to ensure that heartbeats are sent, regardless of whether we start fresh or from
- // persistent state. The line below ensures that they are scheduled in the persistent startup
- // case. For the other case, the task is scheduled when we acquire a token.
- heartbeatTask.ensureScheduled("Startup-after-persistence");
- } else {
- // If we had no persistent state or couldn't deserialize the state that we had, start fresh.
- // Request a new client identifier.
-
- // The server can't possibly have our registrations, so whatever we get
- // from the application we should send to the registrar.
- logger.info("Starting with no previous state");
- shouldSendRegistrations = true;
- acquireToken("Startup");
- }
-
- // listener.ready() is called when ticl has acquired a new token.
- }
-
- /**
- * Returns the delay for the initial heartbeat, given that the last message to the server was
- * sent at {@code lastSendTimeMs}.
- * @param config configuration object used by the client
- * @param resources resources used by the client
- */
-
- static int computeInitialPersistentHeartbeatDelayMs(ClientConfigP config,
- SystemResources resources, long lastSendTimeMs) {
- // There are five cases:
- // 1. Channel does not support offline delivery. We delay a little bit to allow the
- // application to reissue its registrations locally and avoid triggering registration
- // sync with the data center due to a hash mismatch. This is the "minimum delay," and we
- // never use a delay less than it.
- //
- // All other cases are for channels supporting offline delivery.
- //
- // 2. Last send time is in the future (something weird happened). Use the minimum delay.
- // 3. We have been asleep for more than one heartbeat interval. Use the minimum delay.
- // 4. We have been asleep for less than one heartbeat interval.
- // (a). The time remaining to the end of the interval is less than the minimum delay.
- // Use the minimum delay.
- // (b). The time remaining to the end of the interval is more than the minimum delay.
- // Use the remaining delay.
- final long nowMs = resources.getInternalScheduler().getCurrentTimeMs();
- final int initialHeartbeatDelayMs;
- if (!config.getChannelSupportsOfflineDelivery()) {
- // Case 1.
- initialHeartbeatDelayMs = config.getInitialPersistentHeartbeatDelayMs();
- } else {
- // Offline delivery cases (2, 3, 4).
- // The default of the last send time is zero, so even if it wasn't written in the persistent
- // state, this logic is still correct.
- if ((lastSendTimeMs > nowMs) || // Case 2.
- ((lastSendTimeMs + config.getHeartbeatIntervalMs()) < nowMs)) { // Case 3.
- // Either something strange happened and the last send time is in the future, or we
- // have been asleep for more than one heartbeat interval. Send immediately.
- initialHeartbeatDelayMs = config.getInitialPersistentHeartbeatDelayMs();
- } else {
- // Case 4.
- // We have been asleep for less than one heartbeat interval. Send after it expires,
- // but ensure we let the initial heartbeat interval elapse.
- final long timeSinceLastMessageMs = nowMs - lastSendTimeMs;
- final int remainingHeartbeatIntervalMs =
- (int) (config.getHeartbeatIntervalMs() - timeSinceLastMessageMs);
- initialHeartbeatDelayMs = Math.max(remainingHeartbeatIntervalMs,
- config.getInitialPersistentHeartbeatDelayMs());
- }
- }
- resources.getLogger().info("Computed heartbeat delay %s from: offline-delivery = %s, "
- + "initial-persistent-delay = %s, heartbeat-interval = %s, nowMs = %s",
- initialHeartbeatDelayMs, config.getChannelSupportsOfflineDelivery(),
- config.getInitialPersistentHeartbeatDelayMs(), config.getHeartbeatIntervalMs(),
- nowMs);
- return initialHeartbeatDelayMs;
- }
-
- @Override // InvalidationClient
- public void stop() {
- logger.warning("Ticl being stopped: %s", InvalidationClientCore.this);
- if (ticlState.isStarted()) { // RunState is thread-safe.
- ticlState.stop();
- }
- }
-
- @Override // InvalidationClient
- public void register(ObjectId objectId) {
- List<ObjectId> objectIds = new ArrayList<ObjectId>();
- objectIds.add(objectId);
- performRegisterOperations(objectIds, RegistrationP.OpType.REGISTER);
- }
-
- @Override // InvalidationClient
- public void unregister(ObjectId objectId) {
- List<ObjectId> objectIds = new ArrayList<ObjectId>();
- objectIds.add(objectId);
- performRegisterOperations(objectIds, RegistrationP.OpType.UNREGISTER);
- }
-
- @Override // InvalidationClient
- public void register(Collection<ObjectId> objectIds) {
- performRegisterOperations(objectIds, RegistrationP.OpType.REGISTER);
- }
-
- @Override // InvalidationClient
- public void unregister(Collection<ObjectId> objectIds) {
- performRegisterOperations(objectIds, RegistrationP.OpType.UNREGISTER);
- }
-
- /**
- * Implementation of (un)registration.
- *
- * @param objectIds object ids on which to operate
- * @param regOpType whether to register or unregister
- */
- private void performRegisterOperations(final Collection<ObjectId> objectIds,
- final RegistrationP.OpType regOpType) {
- Preconditions.checkState(!objectIds.isEmpty(), "Must specify some object id");
- Preconditions.checkNotNull(regOpType, "Must specify (un)registration");
- Preconditions.checkState(internalScheduler.isRunningOnThread(),
- "Not running on internal thread");
-
- if (ticlState.isStopped()) {
- // The Ticl has been stopped. This might be some old registration op coming in. Just ignore
- // instead of crashing.
- logger.severe("Ticl stopped: register (%s) of %s ignored.", regOpType, objectIds);
- return;
- }
- if (!ticlState.isStarted()) {
- // We must be in the NOT_STARTED state, since we can't be in STOPPED or STARTED (since the
- // previous if-check didn't succeeded, and isStarted uses a != STARTED test).
- logger.severe(
- "Ticl is not yet started; failing registration call; client = %s, objects = %s, op = %s",
- this, objectIds, regOpType);
- for (ObjectId objectId : objectIds) {
- listener.informRegistrationFailure(this, objectId, true, "Client not yet ready");
- }
- return;
- }
-
- List<ObjectIdP> objectIdProtos = new ArrayList<ObjectIdP>(objectIds.size());
- for (ObjectId objectId : objectIds) {
- Preconditions.checkNotNull(objectId, "Must specify object id");
- ObjectIdP objectIdProto = ProtoConverter.convertToObjectIdProto(objectId);
- IncomingOperationType opType = (regOpType == RegistrationP.OpType.REGISTER) ?
- IncomingOperationType.REGISTRATION : IncomingOperationType.UNREGISTRATION;
- statistics.recordIncomingOperation(opType);
- logger.info("Register %s, %s", CommonProtoStrings2.toLazyCompactString(objectIdProto),
- regOpType);
- objectIdProtos.add(objectIdProto);
- }
-
- // Update the registration manager state, then have the protocol client send a message.
- // performOperations returns only those elements of objectIdProtos that caused a state
- // change (i.e., elements not present if regOpType == REGISTER or elements that were present
- // if regOpType == UNREGISTER).
- Collection<ObjectIdP> objectProtosToSend = registrationManager.performOperations(
- objectIdProtos, regOpType);
-
- // Check whether we should suppress sending registrations because we don't
- // yet know the server's summary.
- if (shouldSendRegistrations && (!objectProtosToSend.isEmpty())) {
- protocolHandler.sendRegistrations(objectProtosToSend, regOpType, batchingTask);
- }
- InvalidationClientCore.this.regSyncHeartbeatTask.ensureScheduled("performRegister");
- }
-
- @Override // InvalidationClient
- public void acknowledge(final AckHandle acknowledgeHandle) {
- Preconditions.checkNotNull(acknowledgeHandle);
- Preconditions.checkState(internalScheduler.isRunningOnThread(),
- "Not running on internal thread");
-
- // 1. Parse the ack handle first.
- AckHandleP ackHandle;
- try {
- ackHandle = AckHandleP.parseFrom(acknowledgeHandle.getHandleData());
- } catch (InvalidProtocolBufferException exception) {
- logger.warning("Bad ack handle : %s",
- CommonProtoStrings2.toLazyCompactString(acknowledgeHandle.getHandleData()));
- statistics.recordError(ClientErrorType.ACKNOWLEDGE_HANDLE_FAILURE);
- return;
- }
-
- // 2. Validate ack handle - it should have a valid invalidation.
- if (!ackHandle.hasInvalidation() ||
- !msgValidator.isValid(ackHandle.getInvalidation())) {
- logger.warning("Incorrect ack handle data: %s", acknowledgeHandle);
- statistics.recordError(ClientErrorType.ACKNOWLEDGE_HANDLE_FAILURE);
- return;
- }
-
- // Currently, only invalidations have non-trivial ack handle.
- InvalidationP invalidation = ackHandle.getInvalidation();
- if (invalidation.hasPayload()) {
- // Don't send the payload back.
- invalidation = invalidation.toBuilder().clearPayload().build();
- }
- statistics.recordIncomingOperation(IncomingOperationType.ACKNOWLEDGE);
- protocolHandler.sendInvalidationAck(invalidation, batchingTask);
- }
-
- //
- // Protocol listener methods
- //
-
- @Override
- public ByteString getClientToken() {
- Preconditions.checkState((clientToken == null) || (nonce == null));
- return clientToken;
- }
-
- @Override
- public void handleMessageSent() {
- // The ProtocolHandler just sent a message to the server. If the channel supports offline
- // delivery (see the comment in the ClientConfigP), store this time to stable storage. This
- // only needs to be a best-effort write; if it fails, then we will "forget" that we sent the
- // message and heartbeat needlessly when next restarted. That is a performance/battery bug,
- // not a correctness bug.
- lastMessageSendTimeMs = getResourcesTimeMs();
- if (config.getChannelSupportsOfflineDelivery()) {
- // Write whether or not we have a token. The persistent write task is a no-op if there is
- // no token. We only write if the channel supports offline delivery. We could do the write
- // regardless, and may want to do so in the future, since it might simplify some of the
- // Ticl implementation.
- persistentWriteTask.ensureScheduled("sent-message");
- }
- }
-
- @Override
- public RegistrationSummary getRegistrationSummary() {
- return registrationManager.getRegistrationSummary();
- }
-
- //
- // Private methods and toString.
- //
-
- void handleNetworkStatusChange(final boolean isOnline) {
- // If we're back online and haven't sent a message to the server in a while, send a heartbeat to
- // make sure the server knows we're online.
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- boolean wasOnline = this.isOnline;
- this.isOnline = isOnline;
- if (isOnline && !wasOnline && (internalScheduler.getCurrentTimeMs() >
- lastMessageSendTimeMs + config.getOfflineHeartbeatThresholdMs())) {
- logger.log(Level.INFO,
- "Sending heartbeat after reconnection, previous send was %s ms ago",
- internalScheduler.getCurrentTimeMs() - lastMessageSendTimeMs);
- sendInfoMessageToServer(false, !registrationManager.isStateInSyncWithServer());
- }
- }
-
- /**
- * Handles an {@code incomingMessage} from the data center. If it is valid and addressed to
- * this client, dispatches to methods to handle sub-parts of the message; if not, drops the
- * message.
- */
- void handleIncomingMessage(byte[] incomingMessage) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- statistics.recordReceivedMessage(ReceivedMessageType.TOTAL);
- ParsedMessage parsedMessage = protocolHandler.handleIncomingMessage(incomingMessage);
- if (parsedMessage == null) {
- // Invalid message.
- return;
- }
-
- // Ensure we have either a matching token or a matching nonce.
- if (!validateToken(parsedMessage)) {
- return;
- }
-
- // Handle a token-control message, if present.
- if (parsedMessage.tokenControlMessage != null) {
- statistics.recordReceivedMessage(ReceivedMessageType.TOKEN_CONTROL);
- handleTokenChanged(parsedMessage.header.token,
- parsedMessage.tokenControlMessage.hasNewToken() ?
- parsedMessage.tokenControlMessage.getNewToken() : null);
- }
-
- // We might have lost our token or failed to acquire one. Ensure that we do not proceed in
- // either case.
- if (clientToken == null) {
- return;
- }
-
- // First, handle the message header.
- handleIncomingHeader(parsedMessage.header);
-
- // Then, handle any work remaining in the message.
- if (parsedMessage.invalidationMessage != null) {
- statistics.recordReceivedMessage(ReceivedMessageType.INVALIDATION);
- handleInvalidations(parsedMessage.invalidationMessage.getInvalidationList());
- }
- if (parsedMessage.registrationStatusMessage != null) {
- statistics.recordReceivedMessage(ReceivedMessageType.REGISTRATION_STATUS);
- handleRegistrationStatus(parsedMessage.registrationStatusMessage.getRegistrationStatusList());
- }
- if (parsedMessage.registrationSyncRequestMessage != null) {
- statistics.recordReceivedMessage(ReceivedMessageType.REGISTRATION_SYNC_REQUEST);
- handleRegistrationSyncRequest();
- }
- if (parsedMessage.infoRequestMessage != null) {
- statistics.recordReceivedMessage(ReceivedMessageType.INFO_REQUEST);
- handleInfoMessage(parsedMessage.infoRequestMessage.getInfoTypeList());
- }
- if (parsedMessage.errorMessage != null) {
- statistics.recordReceivedMessage(ReceivedMessageType.ERROR);
- handleErrorMessage(parsedMessage.header, parsedMessage.errorMessage.getCode(),
- parsedMessage.errorMessage.getDescription());
- }
- }
-
- /**
- * Handles a token-control message.
- * @param headerToken token in the server message
- * @param newToken the new token provided, or {@code null} if this is a destroy message.
- */
- private void handleTokenChanged(ByteString headerToken, final ByteString newToken) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
-
- // The server is either supplying a new token in response to an InitializeMessage, spontaneously
- // destroying a token we hold, or spontaneously upgrading a token we hold.
-
- if (newToken != null) {
- // Note: headerToken cannot be null, so a null nonce or clientToken will always be non-equal.
- boolean headerTokenMatchesNonce = TypedUtil.<ByteString>equals(headerToken, nonce);
- boolean headerTokenMatchesExistingToken =
- TypedUtil.<ByteString>equals(headerToken, clientToken);
- boolean shouldAcceptToken = headerTokenMatchesNonce || headerTokenMatchesExistingToken;
- if (!shouldAcceptToken) {
- logger.info("Ignoring new token; %s does not match nonce = %s or existing token = %s",
- newToken, nonce, clientToken);
- return;
- }
- logger.info("New token being assigned at client: %s, Old = %s",
- CommonProtoStrings2.toLazyCompactString(newToken),
- CommonProtoStrings2.toLazyCompactString(clientToken));
-
- // Start the regular heartbeats now.
- heartbeatTask.ensureScheduled("Heartbeat-after-new-token");
- setNonce(null);
- setClientToken(newToken);
- persistentWriteTask.ensureScheduled("Write-after-new-token");
- } else {
- logger.info("Destroying existing token: %s",
- CommonProtoStrings2.toLazyCompactString(clientToken));
- acquireToken("Destroy");
- }
- }
-
- /** Handles a server {@code header}. */
- private void handleIncomingHeader(ServerMessageHeader header) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- Preconditions.checkState(nonce == null,
- "Cannot process server header with non-null nonce (have %s): %s", nonce, header);
- if (header.registrationSummary != null) {
- // We've received a summary from the server, so if we were suppressing
- // registrations, we should now allow them to go to the registrar.
- shouldSendRegistrations = true;
-
- // Pass the registration summary to the registration manager. If we are now in agreement
- // with the server and we had any pending operations, we can tell the listener that those
- // operations have succeeded.
- Set<ProtoWrapper<RegistrationP>> upcalls =
- registrationManager.informServerRegistrationSummary(header.registrationSummary);
- logger.fine("Receivced new server registration summary (%s); will make %s upcalls",
- header.registrationSummary, upcalls.size());
- for (ProtoWrapper<RegistrationP> upcall : upcalls) {
- RegistrationP registration = upcall.getProto();
- ObjectId objectId = ProtoConverter.convertFromObjectIdProto(registration.getObjectId());
- RegistrationState regState = convertOpTypeToRegState(registration.getOpType());
- listener.informRegistrationStatus(this, objectId, regState);
- }
- }
- }
-
- /** Handles incoming {@code invalidations}. */
- private void handleInvalidations(Collection<InvalidationP> invalidations) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
-
- for (InvalidationP invalidation : invalidations) {
- AckHandle ackHandle = AckHandle.newInstance(
- CommonProtos2.newAckHandleP(invalidation).toByteArray());
- if (CommonProtos2.isAllObjectId(invalidation.getObjectId())) {
- logger.info("Issuing invalidate all");
- listener.invalidateAll(InvalidationClientCore.this, ackHandle);
- } else {
- // Regular object. Could be unknown version or not.
- Invalidation inv = ProtoConverter.convertFromInvalidationProto(invalidation);
-
- boolean isSuppressed = invalidation.getIsTrickleRestart();
- logger.info("Issuing invalidate (known-version = %s, is-trickle-restart = %s): %s",
- invalidation.getIsKnownVersion(), isSuppressed, inv);
-
- // Issue invalidate if the invalidation had a known version AND either no suppression has
- // occurred or the client allows suppression.
- if (invalidation.getIsKnownVersion() &&
- (!isSuppressed || InvalidationClientCore.this.config.getAllowSuppression())) {
- listener.invalidate(InvalidationClientCore.this, inv, ackHandle);
- } else {
- // Otherwise issue invalidateUnknownVersion.
- listener.invalidateUnknownVersion(InvalidationClientCore.this, inv.getObjectId(),
- ackHandle);
- }
- }
- }
- }
-
- /** Handles incoming registration statuses. */
- private void handleRegistrationStatus(List<RegistrationStatus> regStatusList) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- List<Boolean> localProcessingStatuses =
- registrationManager.handleRegistrationStatus(regStatusList);
- Preconditions.checkState(localProcessingStatuses.size() == regStatusList.size(),
- "Not all registration statuses were processed");
-
- // Inform app about the success or failure of each registration based
- // on what the registration manager has indicated.
- for (int i = 0; i < regStatusList.size(); ++i) {
- RegistrationStatus regStatus = regStatusList.get(i);
- boolean wasSuccess = localProcessingStatuses.get(i);
- logger.fine("Process reg status: %s", regStatus);
-
- ObjectId objectId = ProtoConverter.convertFromObjectIdProto(
- regStatus.getRegistration().getObjectId());
- if (wasSuccess) {
- // Server operation was both successful and agreed with what the client wanted.
- OpType regOpType = regStatus.getRegistration().getOpType();
- InvalidationListener.RegistrationState regState = convertOpTypeToRegState(regOpType);
- listener.informRegistrationStatus(InvalidationClientCore.this, objectId, regState);
- } else {
- // Server operation either failed or disagreed with client's intent (e.g., successful
- // unregister, but the client wanted a registration).
- String description = CommonProtos2.isSuccess(regStatus.getStatus()) ?
- "Registration discrepancy detected" : regStatus.getStatus().getDescription();
- boolean isPermanent = CommonProtos2.isPermanentFailure(regStatus.getStatus());
- listener.informRegistrationFailure(InvalidationClientCore.this, objectId, !isPermanent,
- description);
- }
- }
- }
-
- /** Handles a registration sync request. */
- private void handleRegistrationSyncRequest() {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- // Send all the registrations in the reg sync message.
- // Generate a single subtree for all the registrations.
- RegistrationSubtree subtree =
- registrationManager.getRegistrations(Bytes.EMPTY_BYTES.getByteArray(), 0);
- protocolHandler.sendRegistrationSyncSubtree(subtree, batchingTask);
- }
-
- /** Handles an info message request. */
- private void handleInfoMessage(Collection<InfoType> infoTypes) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- boolean mustSendPerformanceCounters = false;
- for (InfoType infoType : infoTypes) {
- mustSendPerformanceCounters = (infoType == InfoType.GET_PERFORMANCE_COUNTERS);
- if (mustSendPerformanceCounters) {
- break;
- }
- }
- sendInfoMessageToServer(mustSendPerformanceCounters,
- !registrationManager.isStateInSyncWithServer());
- }
-
- /** Handles an error message. */
- private void handleErrorMessage(ServerMessageHeader header,
- ErrorMessage.Code code, String description) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
-
- // If it is an auth failure, we shut down the ticl.
- logger.severe("Received error message: %s, %s, %s", header, code, description);
-
- // Translate the code to error reason.
- int reason;
- switch (code) {
- case AUTH_FAILURE:
- reason = ErrorInfo.ErrorReason.AUTH_FAILURE;
- break;
- case UNKNOWN_FAILURE:
- reason = ErrorInfo.ErrorReason.UNKNOWN_FAILURE;
- break;
- default:
- reason = ErrorInfo.ErrorReason.UNKNOWN_FAILURE;
- break;
- }
-
- // Issue an informError to the application.
- ErrorInfo errorInfo = ErrorInfo.newInstance(reason, false, description, null);
- listener.informError(this, errorInfo);
-
- // If this is an auth failure, remove registrations and stop the Ticl. Otherwise do nothing.
- if (code != ErrorMessage.Code.AUTH_FAILURE) {
- return;
- }
-
- // If there are any registrations, remove them and issue registration failure.
- Collection<ProtoWrapper<ObjectIdP>> desiredRegistrations =
- registrationManager.removeRegisteredObjects();
- logger.warning("Issuing failure for %s objects", desiredRegistrations.size());
- for (ProtoWrapper<ObjectIdP> objectIdWrapper : desiredRegistrations) {
- ObjectIdP objectId = objectIdWrapper.getProto();
- listener.informRegistrationFailure(this,
- ProtoConverter.convertFromObjectIdProto(objectId), false, "Auth error: " + description);
- }
- }
-
- /**
- * Returns whether the token in the header of {@code parsedMessage} matches either the
- * client token or nonce of this Ticl (depending on which is non-{@code null}).
- */
- private boolean validateToken(ParsedMessage parsedMessage) {
- if (clientToken != null) {
- // Client token case.
- if (!TypedUtil.<ByteString>equals(clientToken, parsedMessage.header.token)) {
- logger.info("Incoming message has bad token: server = %s, client = %s",
- CommonProtoStrings2.toLazyCompactString(parsedMessage.header.token),
- CommonProtoStrings2.toLazyCompactString(clientToken));
- statistics.recordError(ClientErrorType.TOKEN_MISMATCH);
- return false;
- }
- return true;
- } else if (nonce != null) {
- // Nonce case.
- if (!TypedUtil.<ByteString>equals(nonce, parsedMessage.header.token)) {
- statistics.recordError(ClientErrorType.NONCE_MISMATCH);
- logger.info("Rejecting server message with mismatched nonce: Client = %s, Server = %s",
- CommonProtoStrings2.toLazyCompactString(nonce),
- CommonProtoStrings2.toLazyCompactString(parsedMessage.header.token));
- return false;
- } else {
- logger.info("Accepting server message with matching nonce: %s",
- CommonProtoStrings2.toLazyCompactString(nonce));
- return true;
- }
- }
- // Neither token nor nonce; ignore message.
- logger.warning("Neither token nor nonce was set in validateToken: %s, %s", clientToken, nonce);
- return false;
- }
-
- /**
- * Requests a new client identifier from the server.
- * <p>
- * REQUIRES: no token currently be held.
- *
- * @param debugString information to identify the caller
- */
- private void acquireToken(final String debugString) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
-
- // Clear the current token and schedule the token acquisition.
- setClientToken(null);
- acquireTokenTask.ensureScheduled(debugString);
- }
-
- /**
- * Sends an info message to the server. If {@code mustSendPerformanceCounters} is true,
- * the performance counters are sent regardless of when they were sent earlier.
- */
- private void sendInfoMessageToServer(boolean mustSendPerformanceCounters,
- boolean requestServerSummary) {
- logger.info("Sending info message to server; request server summary = %s",
- requestServerSummary);
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
-
- List<SimplePair<String, Integer>> performanceCounters =
- new ArrayList<SimplePair<String, Integer>>();
- List<SimplePair<String, Integer>> configParams =
- new ArrayList<SimplePair<String, Integer>>();
- ClientConfigP configToSend = null;
- if (mustSendPerformanceCounters) {
- statistics.getNonZeroStatistics(performanceCounters);
- configToSend = config;
- }
- protocolHandler.sendInfoMessage(performanceCounters, configToSend, requestServerSummary,
- batchingTask);
- }
-
- /** Reads the Ticl state from persistent storage (if any) and calls {@code startInternal}. */
- private void scheduleStartAfterReadingStateBlob() {
- storage.readKey(CLIENT_TOKEN_KEY, new Callback<SimplePair<Status, byte[]>>() {
- @Override
- public void accept(final SimplePair<Status, byte[]> readResult) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- final byte[] serializedState = readResult.getFirst().isSuccess() ?
- readResult.getSecond() : null;
- // Call start now.
- if (!readResult.getFirst().isSuccess()) {
- statistics.recordError(ClientErrorType.PERSISTENT_READ_FAILURE);
- logger.warning("Could not read state blob: %s", readResult.getFirst().getMessage());
- }
- startInternal(serializedState);
- }
- });
- }
-
- /**
- * Converts an operation type {@code regOpType} to a
- * {@code InvalidationListener.RegistrationState}.
- */
- private static InvalidationListener.RegistrationState convertOpTypeToRegState(
- RegistrationP.OpType regOpType) {
- InvalidationListener.RegistrationState regState =
- regOpType == RegistrationP.OpType.REGISTER ?
- InvalidationListener.RegistrationState.REGISTERED :
- InvalidationListener.RegistrationState.UNREGISTERED;
- return regState;
- }
-
- /**
- * Sets the nonce to {@code newNonce}.
- * <p>
- * REQUIRES: {@code newNonce} be null or {@link #clientToken} be null.
- * The goal is to ensure that a nonce is never set unless there is no
- * client token, unless the nonce is being cleared.
- */
- private void setNonce(ByteString newNonce) {
- Preconditions.checkState((newNonce == null) || (clientToken == null),
- "Tried to set nonce with existing token %s", clientToken);
- this.nonce = newNonce;
- }
-
- /**
- * Returns a randomly generated nonce. Visible for testing only.
- */
-
- public static ByteString generateNonce(Random random) {
- // Generate 8 random bytes.
- byte[] randomBytes = new byte[8];
- random.nextBytes(randomBytes);
-
- // Return the bytes as a ByteString.
- return ByteString.copyFrom(randomBytes);
- }
-
- /**
- * Sets the clientToken to {@code newClientToken}.
- * <p>
- * REQUIRES: {@code newClientToken} be null or {@link #nonce} be null.
- * The goal is to ensure that a token is never set unless there is no
- * nonce, unless the token is being cleared.
- */
- private void setClientToken(ByteString newClientToken) {
- Preconditions.checkState((newClientToken == null) || (nonce == null),
- "Tried to set token with existing nonce %s", nonce);
-
- // If the ticl is in the process of being started and we are getting a new token (either from
- // persistence or from the server, start the ticl and inform the application.
- boolean finishStartingTicl = !ticlState.isStarted() &&
- (clientToken == null) && (newClientToken != null);
- this.clientToken = newClientToken;
-
- if (finishStartingTicl) {
- finishStartingTiclAndInformListener();
- }
- }
-
- /** Start the ticl and inform the listener that it is ready. */
- private void finishStartingTiclAndInformListener() {
- Preconditions.checkState(!ticlState.isStarted());
- ticlState.start();
- listener.ready(this);
-
- // We are not currently persisting our registration digest, so regardless of whether or not
- // we are restarting from persistent state, we need to query the application for all of
- // its registrations.
- listener.reissueRegistrations(InvalidationClientCore.this, RegistrationManager.EMPTY_PREFIX, 0);
- logger.info("Ticl started: %s", this);
- }
-
- /**
- * Returns an exponential backoff generator with {@code initialDelayMs} and other state as
- * given in {@code marshalledState}.
- */
- private TiclExponentialBackoffDelayGenerator createExpBackOffGenerator(int initialDelayMs,
- ExponentialBackoffState marshalledState) {
- if (marshalledState != null) {
- return new TiclExponentialBackoffDelayGenerator(random, initialDelayMs,
- config.getMaxExponentialBackoffFactor(), marshalledState);
- } else {
- return new TiclExponentialBackoffDelayGenerator(random, initialDelayMs,
- config.getMaxExponentialBackoffFactor());
- }
- }
-
- /** Returns a map from recurring task name to the runnable for that recurring task. */
- protected Map<String, Runnable> getRecurringTasks() {
- final int numPersistentTasks = 6;
- HashMap<String, Runnable> tasks = new HashMap<String, Runnable>(numPersistentTasks);
- tasks.put(AcquireTokenTask.TASK_NAME, acquireTokenTask.getRunnable());
- tasks.put(RegSyncHeartbeatTask.TASK_NAME, regSyncHeartbeatTask.getRunnable());
- tasks.put(PersistentWriteTask.TASK_NAME, persistentWriteTask.getRunnable());
- tasks.put(HeartbeatTask.TASK_NAME, heartbeatTask.getRunnable());
- tasks.put(BatchingTask.TASK_NAME, batchingTask.getRunnable());
- tasks.put(InitialPersistentHeartbeatTask.TASK_NAME,
- initialPersistentHeartbeatTask.getRunnable());
- return tasks;
- }
-
- @Override
- public void toCompactString(TextBuilder builder) {
- builder.appendFormat("Client: %s, %s, %s", applicationClientId,
- CommonProtoStrings2.toLazyCompactString(clientToken), ticlState);
- }
-
- @Override
- public InvalidationClientState marshal() {
- Preconditions.checkState(internalScheduler.isRunningOnThread(),
- "Not running on internal thread");
- InvalidationClientState.Builder builder = InvalidationClientState.newBuilder();
- if (clientToken != null) {
- builder.setClientToken(clientToken);
- }
- builder.setLastMessageSendTimeMs(lastMessageSendTimeMs);
- if (nonce != null) {
- builder.setNonce(nonce);
- }
- builder.setProtocolHandlerState(protocolHandler.marshal())
- .setRegistrationManagerState(registrationManager.marshal())
- .setShouldSendRegistrations(shouldSendRegistrations)
- .setRunState(ticlState.marshal())
- .setIsOnline(isOnline)
- .setAcquireTokenTaskState(acquireTokenTask.marshal())
- .setPersistentWriteTaskState(persistentWriteTask.marshal())
- .setRegSyncHeartbeatTaskState(regSyncHeartbeatTask.marshal())
- .setHeartbeatTaskState(heartbeatTask.marshal())
- .setBatchingTaskState(batchingTask.marshal())
- .setStatisticsState(statistics.marshal());
- if (clientToken != null) {
- builder.setClientToken(clientToken);
- }
- if (persistentWriteTask.lastWrittenState.get() != null) {
- builder.setLastWrittenState(persistentWriteTask.lastWrittenState.get().getProto());
- }
- return builder.build();
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/InvalidationClientImpl.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/InvalidationClientImpl.java
deleted file mode 100644
index c30176c446a..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/InvalidationClientImpl.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import static com.google.ipc.invalidation.external.client.SystemResources.Scheduler.NO_DELAY;
-
-import com.google.ipc.invalidation.external.client.InvalidationListener;
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.ipc.invalidation.external.client.types.AckHandle;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientConfigP;
-
-import java.util.Collection;
-import java.util.Random;
-
-/**
- * Implementation of the standard Java Ticl. This class extends {@link InvalidationClientCore}
- * with additional thread-safety related constructs. Specifically, it ensures that:
- * <p>
- * 1. All application calls into the Ticl execute on the internal scheduler.
- * <p>
- * 2. The storage layer always executes callbacks on the internal scheduler thread.
- * <p>
- * 3. All calls into the listener are made on the listener scheduler thread.
- */
-public class InvalidationClientImpl extends InvalidationClientCore {
- public InvalidationClientImpl(final SystemResources resources, Random random, int clientType,
- final byte[] clientName, ClientConfigP config, String applicationName,
- InvalidationListener listener) {
- super(
- // We will make Storage a SafeStorage after the constructor call. It's not possible to
- // construct a new resources around the existing components and pass that to super(...)
- // because then subsequent calls on the first resources object (e.g., start) would not
- // affect the new resources object that the Ticl would be using.
- resources,
-
- // Pass basic parameters through unmodified.
- random, clientType, clientName, config, applicationName,
-
- // Wrap the listener in a CheckingInvalidationListener to enforce appropriate threading.
- new CheckingInvalidationListener(listener,
- resources.getInternalScheduler(), resources.getListenerScheduler(),
- resources.getLogger())
- ); // End super.
-
- // Make Storage safe.
- this.storage = new SafeStorage(resources.getStorage());
- this.storage.setSystemResources(resources);
-
- // CheckingInvalidationListener needs the statistics object created by our super() call, so
- // we can't provide it at construction-time (since it hasn't been created yet).
- ((CheckingInvalidationListener) this.listener).setStatistics(statistics);
-
- }
-
- // Methods below are public methods from InvalidationClient that must first enqueue onto the
- // internal thread.
-
- @Override
- public void start() {
- getResources().getInternalScheduler().schedule(NO_DELAY, new Runnable() {
- @Override
- public void run() {
- InvalidationClientImpl.super.start();
- }
- });
- }
-
- @Override
- public void stop() {
- getResources().getInternalScheduler().schedule(NO_DELAY, new Runnable() {
- @Override
- public void run() {
- InvalidationClientImpl.super.stop();
- }
- });
- }
-
- @Override
- public void register(final ObjectId objectId) {
- getResources().getInternalScheduler().schedule(NO_DELAY, new Runnable() {
- @Override
- public void run() {
- InvalidationClientImpl.super.register(objectId);
- }
- });
- }
-
- @Override
- public void register(final Collection<ObjectId> objectIds) {
- getResources().getInternalScheduler().schedule(NO_DELAY, new Runnable() {
- @Override
- public void run() {
- InvalidationClientImpl.super.register(objectIds);
- }
- });
- }
-
- @Override
- public void unregister(final ObjectId objectId) {
- getResources().getInternalScheduler().schedule(NO_DELAY, new Runnable() {
- @Override
- public void run() {
- InvalidationClientImpl.super.unregister(objectId);
- }
- });
- }
-
- @Override
- public void unregister(final Collection<ObjectId> objectIds) {
- getResources().getInternalScheduler().schedule(NO_DELAY, new Runnable() {
- @Override
- public void run() {
- InvalidationClientImpl.super.unregister(objectIds);
- }
- });
- }
-
- @Override
- public void acknowledge(final AckHandle ackHandle) {
- getResources().getInternalScheduler().schedule(NO_DELAY, new Runnable() {
- @Override
- public void run() {
- InvalidationClientImpl.super.acknowledge(ackHandle);
- }
- });
- }
-
- // End InvalidationClient methods.
-
- @Override // InvalidationClientCore; overriding to add concurrency control.
- void handleIncomingMessage(final byte[] message) {
- getResources().getInternalScheduler().schedule(NO_DELAY, new Runnable() {
- @Override
- public void run() {
- InvalidationClientImpl.super.handleIncomingMessage(message);
- }
- });
- }
-
- @Override // InvalidationClientCore; overriding to add concurrency control.
- public void handleNetworkStatusChange(final boolean isOnline) {
- getResources().getInternalScheduler().schedule(NO_DELAY, new Runnable() {
- @Override
- public void run() {
- InvalidationClientImpl.super.handleNetworkStatusChange(isOnline);
- }
- });
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/MemoryStorageImpl.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/MemoryStorageImpl.java
deleted file mode 100644
index 1b2a93aa3f7..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/MemoryStorageImpl.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.ipc.invalidation.external.client.SystemResources.Scheduler;
-import com.google.ipc.invalidation.external.client.SystemResources.Storage;
-import com.google.ipc.invalidation.external.client.types.Callback;
-import com.google.ipc.invalidation.external.client.types.SimplePair;
-import com.google.ipc.invalidation.external.client.types.Status;
-import com.google.ipc.invalidation.util.Bytes;
-import com.google.ipc.invalidation.util.InternalBase;
-import com.google.ipc.invalidation.util.NamedRunnable;
-import com.google.ipc.invalidation.util.TextBuilder;
-import com.google.ipc.invalidation.util.TypedUtil;
-
-import java.util.HashMap;
-import java.util.Map;
-
-
-/**
- * Map-based in-memory implementation of {@link Storage}.
- *
- */
-public class MemoryStorageImpl extends InternalBase implements Storage {
- private Scheduler scheduler;
- private Map<String, byte[]> ticlPersistentState = new HashMap<String, byte[]>();
-
- @Override
- public void writeKey(final String key, final byte[] value, final Callback<Status> callback) {
- // Need to schedule immediately because C++ locks aren't reentrant, and
- // C++ locking code assumes that this call will not return directly.
-
- // Schedule the write even if the resources are started since the
- // scheduler will prevent it from running in case the resources have been
- // stopped.
- scheduler.schedule(Scheduler.NO_DELAY,
- new NamedRunnable("MemoryStorage.writeKey") {
- @Override
- public void run() {
- ticlPersistentState.put(key, value);
- callback.accept(Status.newInstance(Status.Code.SUCCESS, ""));
- }
- });
- }
-
- int numKeysForTest() {
- return ticlPersistentState.size();
- }
-
- @Override
- public void setSystemResources(SystemResources resources) {
- this.scheduler = resources.getInternalScheduler();
- }
-
- @Override
- public void readKey(final String key, final Callback<SimplePair<Status, byte[]>> done) {
- scheduler.schedule(Scheduler.NO_DELAY,
- new NamedRunnable("MemoryStorage.readKey") {
- @Override
- public void run() {
- byte[] value = TypedUtil.mapGet(ticlPersistentState, key);
- final SimplePair<Status, byte[]> result;
- if (value != null) {
- result = SimplePair.of(Status.newInstance(Status.Code.SUCCESS, ""), value);
- } else {
- String error = "No value present in map for " + key;
- result = SimplePair.of(Status.newInstance(Status.Code.PERMANENT_FAILURE, error), null);
- }
- done.accept(result);
- }
- });
- }
-
- @Override
- public void deleteKey(final String key, final Callback<Boolean> done) {
- scheduler.schedule(Scheduler.NO_DELAY,
- new NamedRunnable("MemoryStorage.deleteKey") {
- @Override
- public void run() {
- TypedUtil.remove(ticlPersistentState, key);
- done.accept(true);
- }
- });
- }
-
- @Override
- public void readAllKeys(final Callback<SimplePair<Status, String>> done) {
- scheduler.schedule(Scheduler.NO_DELAY,
- new NamedRunnable("MemoryStorage.readAllKeys") {
- @Override
- public void run() {
- Status successStatus = Status.newInstance(Status.Code.SUCCESS, "");
- for (String key : ticlPersistentState.keySet()) {
- done.accept(SimplePair.of(successStatus, key));
- }
- done.accept(null);
- }
- });
- }
-
- /**
- * Same as write except without any callbacks and is NOT done on the internal thread.
- * Test code should typically call this before starting the client.
- */
- void writeForTest(final String key, final byte[] value) {
- ticlPersistentState.put(key, value);
- }
-
- /**
- * Sets the scheduler, for tests. The Android tests use this to supply a scheduler that executes
- * no-delay items in-line.
- */
- public void setSchedulerForTest(Scheduler newScheduler) {
- scheduler = newScheduler;
- }
-
- /**
- * Same as read except without any callbacks and is NOT done on the internal thread.
- */
- public byte[] readForTest(final String key) {
- return ticlPersistentState.get(key);
- }
-
- @Override
- public void toCompactString(TextBuilder builder) {
- builder.append("Storage state: ");
- for (Map.Entry<String, byte[]> entry : ticlPersistentState.entrySet()) {
- builder.appendFormat("<%s, %s>, ", entry.getKey(), Bytes.toString(entry.getValue()));
- }
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/PersistenceUtils.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/PersistenceUtils.java
deleted file mode 100644
index 817c57122db..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/PersistenceUtils.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import com.google.ipc.invalidation.common.CommonProtos2;
-import com.google.ipc.invalidation.common.DigestFunction;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.util.TypedUtil;
-import com.google.protobuf.ByteString;
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protos.ipc.invalidation.Client.PersistentStateBlob;
-import com.google.protos.ipc.invalidation.Client.PersistentTiclState;
-
-/**
- * Utility methods for handling the Ticl persistent state.
- *
- */
-
-public class PersistenceUtils {
-
- /** Serializes a Ticl state blob. */
-
- public static byte[] serializeState(PersistentTiclState state, DigestFunction digestFn) {
- ByteString mac = generateMac(state, digestFn);
- return CommonProtos2.newPersistentStateBlob(state, mac).toByteArray();
- }
-
- /**
- * Deserializes a Ticl state blob. Returns either the parsed state or {@code null}
- * if it could not be parsed.
- */
- public static PersistentTiclState deserializeState(Logger logger, byte[] stateBlobBytes,
- DigestFunction digestFn) {
- PersistentStateBlob stateBlob;
- try {
- // Try parsing the envelope protocol buffer.
- stateBlob = PersistentStateBlob.parseFrom(stateBlobBytes);
- } catch (InvalidProtocolBufferException exception) {
- logger.severe("Failed deserializing Ticl state: %s", exception.getMessage());
- return null;
- }
-
- // Check the mac in the envelope against the recomputed mac from the state.
- PersistentTiclState ticlState = stateBlob.getTiclState();
- ByteString mac = generateMac(ticlState, digestFn);
- if (!TypedUtil.<ByteString>equals(mac, stateBlob.getAuthenticationCode())) {
- logger.warning("Ticl state failed MAC check: computed %s vs %s", mac,
- stateBlob.getAuthenticationCode());
- return null;
- }
- return ticlState;
- }
-
- /** Returns a message authentication code over {@code state}. */
- private static ByteString generateMac(PersistentTiclState state, DigestFunction digestFn) {
- digestFn.reset();
- digestFn.update(state.toByteArray());
- return ByteString.copyFrom(digestFn.getDigest());
- }
-
- private PersistenceUtils() {
- // Prevent instantiation.
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/ProtoConverter.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/ProtoConverter.java
deleted file mode 100644
index dfa2035a300..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/ProtoConverter.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.common.CommonProtos2;
-import com.google.ipc.invalidation.common.TrickleState;
-import com.google.ipc.invalidation.external.client.types.Invalidation;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-import com.google.protobuf.ByteString;
-import com.google.protos.ipc.invalidation.ClientProtocol.InvalidationP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ObjectIdP;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-/**
- * Utilities to convert between protobufs and externally-exposed types in the Ticl.
- *
- */
-
-public class ProtoConverter {
-
- /**
- * Converts an object id protocol buffer {@code objectId} to the
- * corresponding external type and returns it.
- */
- public static ObjectId convertFromObjectIdProto(ObjectIdP objectIdProto) {
- Preconditions.checkNotNull(objectIdProto);
- return ObjectId.newInstance(objectIdProto.getSource(), objectIdProto.getName().toByteArray());
- }
-
- /**
- * Converts an object id {@code objectId} to the corresponding protocol buffer
- * and returns it.
- */
-
- public static ObjectIdP convertToObjectIdProto(ObjectId objectId) {
- Preconditions.checkNotNull(objectId);
- return CommonProtos2.newObjectIdP(objectId.getSource(),
- ByteString.copyFrom(objectId.getName()));
- }
-
- /**
- * Returns a list of {@link ObjectIdP} by converting each element of {@code objectIds} to
- * an {@code ObjectIdP}.
- */
- public static List<ObjectIdP> convertToObjectIdProtoList(Collection<ObjectId> objectIds) {
- List<ObjectIdP> objectIdPs = new ArrayList<ObjectIdP>(objectIds.size());
- for (ObjectId objectId : objectIds) {
- objectIdPs.add(ProtoConverter.convertToObjectIdProto(objectId));
- }
- return objectIdPs;
- }
-
- /**
- * Returns a list of {@link ObjectId} by converting each element of {@code oidPs} to
- * an {@code ObjectId}.
- */
- public static List<ObjectId> convertToObjectIdList(List<ObjectIdP> oidPs) {
- List<ObjectId> objects = new ArrayList<ObjectId>(oidPs.size());
- for (ObjectIdP oidP : oidPs) {
- objects.add(ObjectId.newInstance(oidP.getSource(), oidP.getName().toByteArray()));
- }
- return objects;
- }
-
- /**
- * Converts an invalidation protocol buffer {@code invalidation} to the
- * corresponding external object and returns it
- */
- public static Invalidation convertFromInvalidationProto(InvalidationP invalidation) {
- Preconditions.checkNotNull(invalidation);
- ObjectId objectId = convertFromObjectIdProto(invalidation.getObjectId());
-
- // No bridge arrival time in invalidation.
- return Invalidation.newInstance(objectId, invalidation.getVersion(),
- invalidation.hasPayload() ? invalidation.getPayload().toByteArray() : null,
- invalidation.getIsTrickleRestart());
- }
-
- /**
- * Converts an invalidation {@code invalidation} to the corresponding protocol
- * buffer and returns it.
- */
- public static InvalidationP convertToInvalidationProto(Invalidation invalidation) {
- Preconditions.checkNotNull(invalidation);
- ObjectIdP objectId = convertToObjectIdProto(invalidation.getObjectId());
-
- // Invalidations clients do not know about trickle restarts. Every invalidation is allowed
- // to suppress earlier invalidations and acks implicitly acknowledge all previous
- // invalidations. Therefore the correct semanantics are provided by setting isTrickleRestart to
- // true.
- return CommonProtos2.newInvalidationP(objectId, invalidation.getVersion(),
- TrickleState.fromBoolean(invalidation.getIsTrickleRestartForInternalUse()),
- invalidation.getPayload() == null ? null : ByteString.copyFrom(invalidation.getPayload()));
- }
-
- private ProtoConverter() { // To prevent instantiation.
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/ProtoWrapper.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/ProtoWrapper.java
deleted file mode 100644
index 94a2fe07365..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/ProtoWrapper.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import com.google.common.base.Preconditions;
-import com.google.protobuf.AbstractMessageLite;
-
-import java.util.Arrays;
-
-/**
- * Wraps a Lite protobuf type and provides appropriate {@link #equals} and {@link #hashCode}
- * implementations so the wrapped object can be stored in a Java collection and/or compared to other
- * wrapped proto instances of the same type for equality. This is necessary because protobuf classes
- * generated with the {@code LITE_RUNTIME} optimization do not have custom implementations of these
- * methods (so only support simple object equivalence).
- *
- * @param <P> the protobuf message lite type that is being wrapped.
- */
-public class ProtoWrapper<P extends AbstractMessageLite> {
-
- /** The wrapped proto object */
- private final P proto;
-
- /** The serialized byte representation of the wrapped object */
- private final byte [] protoBytes;
-
- /** The hash code of the serialized representation */
- private final int hashCode;
-
- /** Returns a ProtoWrapper that wraps the provided object */
- public static <M extends AbstractMessageLite> ProtoWrapper<M> of(M proto) {
- return new ProtoWrapper<M>(proto);
- }
-
- // Internal constructor that savees the object and computes serialized state and hash code.
- private ProtoWrapper(P proto) {
- this.proto = Preconditions.checkNotNull(proto);
- this.protoBytes = proto.toByteArray();
- this.hashCode = Arrays.hashCode(protoBytes);
- }
-
- /** Returns the wrapped proto object */
- public P getProto() {
- return proto;
- }
-
- /** Returns the hash code of the serialized state representation of the protobuf object */
- @Override
- public int hashCode() {
- return hashCode;
- }
-
- /**
- * Returns {@code true} if the provided object is a proto wrapper of an object of the same
- * protobuf type that has the same serialized state representation.
- */
- @Override
- public boolean equals(Object o) {
- Class<?> msgClass = proto.getClass();
- if (!(o instanceof ProtoWrapper)) {
- return false;
- }
- @SuppressWarnings("rawtypes")
- ProtoWrapper<?> wrapper = (ProtoWrapper) o;
- if (proto.getClass() != wrapper.proto.getClass()) {
- return false;
- }
- if (hashCode != wrapper.hashCode) {
- return false;
- }
- return Arrays.equals(protoBytes, wrapper.protoBytes);
- }
-
- @Override
- public String toString() {
- // Don't print exactly the protocol buffer because that could be extremely confusing when
- // debugging, since this object isn't actually a protocol buffer.
- return "PW-" + proto.toString();
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/ProtocolHandler.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/ProtocolHandler.java
deleted file mode 100644
index 3c9e06ebba2..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/ProtocolHandler.java
+++ /dev/null
@@ -1,712 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.common.CommonInvalidationConstants2;
-import com.google.ipc.invalidation.common.CommonProtoStrings2;
-import com.google.ipc.invalidation.common.CommonProtos2;
-import com.google.ipc.invalidation.common.TiclMessageValidator2;
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.SystemResources.NetworkChannel;
-import com.google.ipc.invalidation.external.client.SystemResources.Scheduler;
-import com.google.ipc.invalidation.external.client.types.SimplePair;
-import com.google.ipc.invalidation.ticl.InvalidationClientCore.BatchingTask;
-import com.google.ipc.invalidation.ticl.Statistics.ClientErrorType;
-import com.google.ipc.invalidation.ticl.Statistics.ReceivedMessageType;
-import com.google.ipc.invalidation.ticl.Statistics.SentMessageType;
-import com.google.ipc.invalidation.util.InternalBase;
-import com.google.ipc.invalidation.util.Marshallable;
-import com.google.ipc.invalidation.util.Smearer;
-import com.google.ipc.invalidation.util.TextBuilder;
-import com.google.protobuf.ByteString;
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protos.ipc.invalidation.ClientProtocol.ApplicationClientIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientConfigP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientHeader;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientToServerMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientVersion;
-import com.google.protos.ipc.invalidation.ClientProtocol.ConfigChangeMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.ErrorMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InfoMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InfoRequestMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InitializeMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InitializeMessage.DigestSerializationType;
-import com.google.protos.ipc.invalidation.ClientProtocol.InvalidationMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.InvalidationP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ObjectIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.PropertyRecord;
-import com.google.protos.ipc.invalidation.ClientProtocol.ProtocolHandlerConfigP;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationP;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationP.OpType;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationStatusMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSubtree;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSummary;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSyncMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSyncRequestMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.ServerHeader;
-import com.google.protos.ipc.invalidation.ClientProtocol.ServerToClientMessage;
-import com.google.protos.ipc.invalidation.ClientProtocol.TokenControlMessage;
-import com.google.protos.ipc.invalidation.JavaClient.BatcherState;
-import com.google.protos.ipc.invalidation.JavaClient.ProtocolHandlerState;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-
-/**
- * A layer for interacting with low-level protocol messages. Parses messages from the server and
- * calls appropriate functions on the {@code ProtocolListener} to handle various types of message
- * content. Also buffers message data from the client and constructs and sends messages to the
- * server.
- * <p>
- * This class implements {@link Marshallable}, so its state can be written to a protocol buffer,
- * and instances can be restored from such protocol buffers. Additionally, the nested class
- * {@link Batcher} also implements {@code Marshallable} for the same reason.
- * <p>
- * Note that while we talk about "marshalling," in this context we mean marshalling to protocol
- * buffers, not raw bytes.
- *
- */
-class ProtocolHandler implements Marshallable<ProtocolHandlerState> {
- /** Class that batches messages to the server. */
- private static class Batcher implements Marshallable<BatcherState> {
- /** Statistics to be updated when messages are created. */
- private final Statistics statistics;
-
- /** Resources used for logging and thread assertions. */
- private final SystemResources resources;
-
- /** Set of pending registrations stored as a map for overriding later operations. */
- private final Map<ProtoWrapper<ObjectIdP>, RegistrationP.OpType> pendingRegistrations =
- new HashMap<ProtoWrapper<ObjectIdP>, RegistrationP.OpType>();
-
- /** Set of pending invalidation acks. */
- private final Set<ProtoWrapper<InvalidationP>> pendingAckedInvalidations =
- new HashSet<ProtoWrapper<InvalidationP>>();
-
- /** Set of pending registration sub trees for registration sync. */
- private final Set<ProtoWrapper<RegistrationSubtree>> pendingRegSubtrees =
- new HashSet<ProtoWrapper<RegistrationSubtree>>();
-
- /** Pending initialization message to send to the server, if any. */
- private InitializeMessage pendingInitializeMessage = null;
-
- /** Pending info message to send to the server, if any. */
- private InfoMessage pendingInfoMessage = null;
-
- /** Creates a batcher. */
- Batcher(SystemResources resources, Statistics statistics) {
- this.resources = resources;
- this.statistics = statistics;
- }
-
- /** Creates a batcher from {@code marshalledState}. */
- Batcher(SystemResources resources, Statistics statistics, BatcherState marshalledState) {
- this(resources, statistics);
- for (ObjectIdP registration : marshalledState.getRegistrationList()) {
- pendingRegistrations.put(ProtoWrapper.of(registration), RegistrationP.OpType.REGISTER);
- }
- for (ObjectIdP unregistration : marshalledState.getUnregistrationList()) {
- pendingRegistrations.put(ProtoWrapper.of(unregistration), RegistrationP.OpType.UNREGISTER);
- }
- for (InvalidationP ack : marshalledState.getAcknowledgementList()) {
- pendingAckedInvalidations.add(ProtoWrapper.of(ack));
- }
- for (RegistrationSubtree subtree : marshalledState.getRegistrationSubtreeList()) {
- pendingRegSubtrees.add(ProtoWrapper.of(subtree));
- }
- if (marshalledState.hasInitializeMessage()) {
- pendingInitializeMessage = marshalledState.getInitializeMessage();
- }
- if (marshalledState.hasInfoMessage()) {
- pendingInfoMessage = marshalledState.getInfoMessage();
- }
- }
-
- /** Sets the initialize message to be sent. */
- void setInitializeMessage(InitializeMessage msg) {
- pendingInitializeMessage = msg;
- }
-
- /** Sets the info message to be sent. */
- void setInfoMessage(InfoMessage msg) {
- pendingInfoMessage = msg;
- }
-
- /** Adds a registration on {@code oid} of {@code opType} to the registrations to be sent. */
- void addRegistration(ObjectIdP oid, RegistrationP.OpType opType) {
- pendingRegistrations.put(ProtoWrapper.of(oid), opType);
- }
-
- /** Adds {@code ack} to the set of acknowledgements to be sent. */
- void addAck(InvalidationP ack) {
- pendingAckedInvalidations.add(ProtoWrapper.of(ack));
- }
-
- /** Adds {@code subtree} to the set of registration subtrees to be sent. */
- void addRegSubtree(RegistrationSubtree subtree) {
- pendingRegSubtrees.add(ProtoWrapper.of(subtree));
- }
-
- /**
- * Returns a builder for a {@link ClientToServerMessage} to be sent to the server. Crucially,
- * the builder does <b>NOT</b> include the message header.
- * @param hasClientToken whether the client currently holds a token
- */
- ClientToServerMessage.Builder toBuilder(boolean hasClientToken) {
- ClientToServerMessage.Builder builder = ClientToServerMessage.newBuilder();
- if (pendingInitializeMessage != null) {
- statistics.recordSentMessage(SentMessageType.INITIALIZE);
- builder.setInitializeMessage(pendingInitializeMessage);
- pendingInitializeMessage = null;
- }
-
- // Note: Even if an initialize message is being sent, we can send additional
- // messages such as regisration messages, etc to the server. But if there is no token
- // and an initialize message is not being sent, we cannot send any other message.
-
- if (!hasClientToken && !builder.hasInitializeMessage()) {
- // Cannot send any message
- resources.getLogger().warning(
- "Cannot send message since no token and no initialize msg: %s", builder);
- statistics.recordError(ClientErrorType.TOKEN_MISSING_FAILURE);
- return null;
- }
-
- // Check for pending batched operations and add to message builder if needed.
-
- // Add reg, acks, reg subtrees - clear them after adding.
- if (!pendingAckedInvalidations.isEmpty()) {
- builder.setInvalidationAckMessage(createInvalidationAckMessage());
- statistics.recordSentMessage(SentMessageType.INVALIDATION_ACK);
- }
-
- // Check regs.
- if (!pendingRegistrations.isEmpty()) {
- builder.setRegistrationMessage(createRegistrationMessage());
- statistics.recordSentMessage(SentMessageType.REGISTRATION);
- }
-
- // Check reg substrees.
- if (!pendingRegSubtrees.isEmpty()) {
- for (ProtoWrapper<RegistrationSubtree> subtree : pendingRegSubtrees) {
- builder.setRegistrationSyncMessage(RegistrationSyncMessage.newBuilder()
- .addSubtree(subtree.getProto()));
- }
- pendingRegSubtrees.clear();
- statistics.recordSentMessage(SentMessageType.REGISTRATION_SYNC);
- }
-
- // Check if an info message has to be sent.
- if (pendingInfoMessage != null) {
- statistics.recordSentMessage(SentMessageType.INFO);
- builder.setInfoMessage(pendingInfoMessage);
- pendingInfoMessage = null;
- }
- return builder;
- }
-
- /**
- * Creates a registration message based on registrations from {@code pendingRegistrations}
- * and returns it.
- * <p>
- * REQUIRES: pendingRegistrations.size() > 0
- */
- private RegistrationMessage createRegistrationMessage() {
- Preconditions.checkState(!pendingRegistrations.isEmpty());
- RegistrationMessage.Builder regMessage = RegistrationMessage.newBuilder();
-
- // Run through the pendingRegistrations map.
- for (Map.Entry<ProtoWrapper<ObjectIdP>, RegistrationP.OpType> entry :
- pendingRegistrations.entrySet()) {
- RegistrationP reg = CommonProtos2.newRegistrationP(entry.getKey().getProto(),
- entry.getValue() == RegistrationP.OpType.REGISTER);
- regMessage.addRegistration(reg);
- }
- pendingRegistrations.clear();
- return regMessage.build();
- }
-
- /**
- * Creates an invalidation ack message based on acks from {@code pendingAckedInvalidations} and
- * returns it.
- * <p>
- * REQUIRES: pendingAckedInvalidations.size() > 0
- */
- private InvalidationMessage createInvalidationAckMessage() {
- Preconditions.checkState(!pendingAckedInvalidations.isEmpty());
- InvalidationMessage.Builder ackMessage = InvalidationMessage.newBuilder();
- for (ProtoWrapper<InvalidationP> wrapper : pendingAckedInvalidations) {
- ackMessage.addInvalidation(wrapper.getProto());
- }
- pendingAckedInvalidations.clear();
- return ackMessage.build();
- }
-
- @Override
- public BatcherState marshal() {
- BatcherState.Builder builder = BatcherState.newBuilder();
-
- // Marshall (un)registrations.
- for (Map.Entry<ProtoWrapper<ObjectIdP>, RegistrationP.OpType> entry :
- pendingRegistrations.entrySet()) {
- OpType opType = entry.getValue();
- ObjectIdP oid = entry.getKey().getProto();
- switch (opType) {
- case REGISTER:
- builder.addRegistration(oid);
- break;
- case UNREGISTER:
- builder.addUnregistration(oid);
- break;
- default:
- throw new IllegalArgumentException(opType.toString());
- }
- }
-
- // Marshall acks.
- for (ProtoWrapper<InvalidationP> ack : pendingAckedInvalidations) {
- builder.addAcknowledgement(ack.getProto());
- }
-
- // Marshall registration subtrees.
- for (ProtoWrapper<RegistrationSubtree> subtree : pendingRegSubtrees) {
- builder.addRegistrationSubtree(subtree.getProto());
- }
-
- // Marshall initialize and info messages if present.
- if (pendingInitializeMessage != null) {
- builder.setInitializeMessage(pendingInitializeMessage);
- }
- if (pendingInfoMessage != null) {
- builder.setInfoMessage(pendingInfoMessage);
- }
- return builder.build();
- }
- }
-
- /** Representation of a message header for use in a server message. */
- static class ServerMessageHeader extends InternalBase {
- /**
- * Constructs an instance.
- *
- * @param token server-sent token
- * @param registrationSummary summary over server registration state
- */
- ServerMessageHeader(ByteString token, RegistrationSummary registrationSummary) {
- this.token = token;
- this.registrationSummary = registrationSummary;
- }
-
- /** Server-sent token. */
- ByteString token;
-
- /** Summary of the client's registration state at the server. */
- RegistrationSummary registrationSummary;
-
- @Override
- public void toCompactString(TextBuilder builder) {
- builder.appendFormat("Token: %s, Summary: %s", CommonProtoStrings2.toLazyCompactString(token),
- registrationSummary);
- }
- }
-
- /**
- * Representation of a message receiver for the server. Such a message is guaranteed to be
- * valid (i.e. checked by {@link TiclMessageValidator2}, but the session token is <b>not</b>
- * checked.
- */
- static class ParsedMessage {
- /*
- * Each of these fields corresponds directly to a field in the ServerToClientMessage protobuf.
- * It is non-null iff the correspondig hasYYY method in the protobuf would return true.
- */
- final ServerMessageHeader header;
- final TokenControlMessage tokenControlMessage;
- final InvalidationMessage invalidationMessage;
- final RegistrationStatusMessage registrationStatusMessage;
- final RegistrationSyncRequestMessage registrationSyncRequestMessage;
- final ConfigChangeMessage configChangeMessage;
- final InfoRequestMessage infoRequestMessage;
- final ErrorMessage errorMessage;
-
- /** Constructs an instance from a {@code rawMessage}. */
- ParsedMessage(ServerToClientMessage rawMessage) {
- // For each field, assign it to the corresponding protobuf field if present, else null.
- ServerHeader messageHeader = rawMessage.getHeader();
- header = new ServerMessageHeader(messageHeader.getClientToken(),
- messageHeader.hasRegistrationSummary() ? messageHeader.getRegistrationSummary() : null);
- tokenControlMessage = rawMessage.hasTokenControlMessage() ?
- rawMessage.getTokenControlMessage() : null;
- invalidationMessage = rawMessage.hasInvalidationMessage() ?
- rawMessage.getInvalidationMessage() : null;
- registrationStatusMessage = rawMessage.hasRegistrationStatusMessage() ?
- rawMessage.getRegistrationStatusMessage() : null;
- registrationSyncRequestMessage = rawMessage.hasRegistrationSyncRequestMessage() ?
- rawMessage.getRegistrationSyncRequestMessage() : null;
- configChangeMessage = rawMessage.hasConfigChangeMessage() ?
- rawMessage.getConfigChangeMessage() : null;
- infoRequestMessage = rawMessage.hasInfoRequestMessage() ?
- rawMessage.getInfoRequestMessage() : null;
- errorMessage = rawMessage.hasErrorMessage() ? rawMessage.getErrorMessage() : null;
- }
- }
-
- /**
- * Listener for protocol events. The handler guarantees that the call will be made on the internal
- * thread that the SystemResources provides.
- */
- interface ProtocolListener {
- /** Records that a message was sent to the server at the current time. */
- void handleMessageSent();
-
- /** Returns a summary of the current desired registrations. */
- RegistrationSummary getRegistrationSummary();
-
- /** Returns the current server-assigned client token, if any. */
- ByteString getClientToken();
- }
-
- /** Information about the client, e.g., application name, OS, etc. */
- private final ClientVersion clientVersion;
-
- /** A logger. */
- private final Logger logger;
-
- /** Scheduler for the client's internal processing. */
- private final Scheduler internalScheduler;
-
- /** Network channel for sending and receiving messages to and from the server. */
- private final NetworkChannel network;
-
- /** The protocol listener. */
- private final ProtocolListener listener;
-
- /** Checks that messages (inbound and outbound) conform to basic validity constraints. */
- private final TiclMessageValidator2 msgValidator;
-
- /** Batches messages to the server. */
- private final Batcher batcher;
-
- /** A debug message id that is added to every message to the server. */
- private int messageId = 1;
-
- // State specific to a client. If we want to support multiple clients, this could
- // be in a map or could be eliminated (e.g., no batching).
-
- /** The last known time from the server. */
- private long lastKnownServerTimeMs = 0;
-
- /**
- * The next time before which a message cannot be sent to the server. If this is less than current
- * time, a message can be sent at any time.
- */
- private long nextMessageSendTimeMs = 0;
-
- /** Statistics objects to track number of sent messages, etc. */
- private final Statistics statistics;
-
- /** Client type for inclusion in headers. */
- private final int clientType;
-
- /**
- * Creates an instance.
- *
- * @param config configuration for the client
- * @param resources resources to use
- * @param smearer a smearer to randomize delays
- * @param statistics track information about messages sent/received, etc
- * @param applicationName name of the application using the library (for debugging/monitoring)
- * @param listener callback for protocol events
- */
- ProtocolHandler(ProtocolHandlerConfigP config, final SystemResources resources,
- Smearer smearer, Statistics statistics, int clientType, String applicationName,
- ProtocolListener listener, TiclMessageValidator2 msgValidator,
- ProtocolHandlerState marshalledState) {
- this.logger = resources.getLogger();
- this.statistics = statistics;
- this.internalScheduler = resources.getInternalScheduler();
- this.network = resources.getNetwork();
- this.listener = listener;
- this.msgValidator = msgValidator;
- this.clientVersion = CommonProtos2.newClientVersion(resources.getPlatform(), "Java",
- applicationName);
- this.clientType = clientType;
- if (marshalledState == null) {
- // If there is no marshalled state, construct a clean batcher.
- this.batcher = new Batcher(resources, statistics);
- } else {
- // Otherwise, restore the batcher from the marshalled state.
- this.batcher = new Batcher(resources, statistics, marshalledState.getBatcherState());
- this.messageId = marshalledState.getMessageId();
- this.lastKnownServerTimeMs = marshalledState.getLastKnownServerTimeMs();
- this.nextMessageSendTimeMs = marshalledState.getNextMessageSendTimeMs();
- }
- logger.info("Created protocol handler for application %s, platform %s", applicationName,
- resources.getPlatform());
- }
-
- /** Returns a default config for the protocol handler. */
- static ProtocolHandlerConfigP.Builder createConfig() {
- // Allow at most 3 messages every 5 seconds.
- int windowMs = 5 * 1000;
- int numMessagesPerWindow = 3;
-
- return ProtocolHandlerConfigP.newBuilder()
- .addRateLimit(CommonProtos2.newRateLimitP(windowMs, numMessagesPerWindow));
- }
-
- /** Returns a configuration object with parameters set for unit tests. */
- static ProtocolHandlerConfigP.Builder createConfigForTest() {
- // No rate limits
- int smallBatchDelayForTest = 200;
- return ProtocolHandlerConfigP.newBuilder().setBatchingDelayMs(smallBatchDelayForTest);
- }
-
- /**
- * Returns the next time a message is allowed to be sent to the server. Typically, this will be
- * in the past, meaning that the client is free to send a message at any time.
- */
- public long getNextMessageSendTimeMsForTest() {
- return nextMessageSendTimeMs;
- }
-
- /**
- * Handles a message from the server. If the message can be processed (i.e., is valid, is
- * of the right version, and is not a silence message), returns a {@link ParsedMessage}
- * representing it. Otherwise, returns {@code null}.
- * <p>
- * This class intercepts and processes silence messages. In this case, it will discard any other
- * data in the message.
- * <p>
- * Note that this method does <b>not</b> check the session token of any message.
- */
- ParsedMessage handleIncomingMessage(byte[] incomingMessage) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- ServerToClientMessage message;
- try {
- message = ServerToClientMessage.parseFrom(incomingMessage);
- } catch (InvalidProtocolBufferException exception) {
- logger.warning("Incoming message is unparseable: %s",
- CommonProtoStrings2.toLazyCompactString(incomingMessage));
- return null;
- }
-
- // Validate the message. If this passes, we can blindly assume valid messages from here on.
- logger.fine("Incoming message: %s", message);
- if (!msgValidator.isValid(message)) {
- statistics.recordError(ClientErrorType.INCOMING_MESSAGE_FAILURE);
- logger.severe("Received invalid message: %s", message);
- return null;
- }
-
- // Check the version of the message.
- if (message.getHeader().getProtocolVersion().getVersion().getMajorVersion() !=
- CommonInvalidationConstants2.PROTOCOL_MAJOR_VERSION) {
- statistics.recordError(ClientErrorType.PROTOCOL_VERSION_FAILURE);
- logger.severe("Dropping message with incompatible version: %s", message);
- return null;
- }
-
- // Check if it is a ConfigChangeMessage which indicates that messages should no longer be
- // sent for a certain duration. Perform this check before the token is even checked.
- if (message.hasConfigChangeMessage()) {
- ConfigChangeMessage configChangeMsg = message.getConfigChangeMessage();
- statistics.recordReceivedMessage(ReceivedMessageType.CONFIG_CHANGE);
- if (configChangeMsg.hasNextMessageDelayMs()) { // Validator has ensured that it is positive.
- nextMessageSendTimeMs =
- internalScheduler.getCurrentTimeMs() + configChangeMsg.getNextMessageDelayMs();
- }
- return null; // Ignore all other messages in the envelope.
- }
-
- lastKnownServerTimeMs = Math.max(lastKnownServerTimeMs, message.getHeader().getServerTimeMs());
- return new ParsedMessage(message);
- }
-
- /**
- * Sends a message to the server to request a client token.
- *
- * @param applicationClientId application-specific client id
- * @param nonce nonce for the request
- * @param debugString information to identify the caller
- */
- void sendInitializeMessage(ApplicationClientIdP applicationClientId, ByteString nonce,
- BatchingTask batchingTask, String debugString) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- if (applicationClientId.getClientType() != clientType) {
- // This condition is not fatal, but it probably represents a bug somewhere if it occurs.
- logger.warning(
- "Client type in application id does not match constructor-provided type: %s vs %s",
- applicationClientId, clientType);
- }
-
- // Simply store the message in pendingInitializeMessage and send it when the batching task runs.
- InitializeMessage initializeMsg = CommonProtos2.newInitializeMessage(clientType,
- applicationClientId, nonce, DigestSerializationType.BYTE_BASED);
- batcher.setInitializeMessage(initializeMsg);
- logger.info("Batching initialize message for client: %s, %s", debugString, initializeMsg);
- batchingTask.ensureScheduled(debugString);
- }
-
- /**
- * Sends an info message to the server with the performance counters supplied
- * in {@code performanceCounters} and the config supplies in
- * {@code configParams}.
- *
- * @param requestServerRegistrationSummary indicates whether to request the
- * server's registration summary
- */
- void sendInfoMessage(List<SimplePair<String, Integer>> performanceCounters,
- ClientConfigP clientConfig, boolean requestServerRegistrationSummary,
- BatchingTask batchingTask) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- InfoMessage.Builder infoMessage = InfoMessage.newBuilder()
- .setClientVersion(clientVersion);
-
- // Add configuration parameters.
- if (clientConfig != null) {
- infoMessage.setClientConfig(clientConfig);
- }
-
- // Add performance counters.
- for (SimplePair<String, Integer> performanceCounter : performanceCounters) {
- PropertyRecord counter =
- CommonProtos2.newPropertyRecord(performanceCounter.first, performanceCounter.second);
- infoMessage.addPerformanceCounter(counter);
- }
-
- // Indicate whether we want the server's registration summary sent back.
- infoMessage.setServerRegistrationSummaryRequested(requestServerRegistrationSummary);
-
- // Simply store the message in pendingInfoMessage and send it when the batching task runs.
- batcher.setInfoMessage(infoMessage.build());
- batchingTask.ensureScheduled("Send-info");
- }
-
- /**
- * Sends a registration request to the server.
- *
- * @param objectIds object ids on which to (un)register
- * @param regOpType whether to register or unregister
- */
- void sendRegistrations(Collection<ObjectIdP> objectIds, RegistrationP.OpType regOpType,
- BatchingTask batchingTask) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- for (ObjectIdP objectId : objectIds) {
- batcher.addRegistration(objectId, regOpType);
- }
- batchingTask.ensureScheduled("Send-registrations");
- }
-
- /** Sends an acknowledgement for {@code invalidation} to the server. */
- void sendInvalidationAck(InvalidationP invalidation, BatchingTask batchingTask) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- // We could do squelching - we don't since it is unlikely to be too beneficial here.
- logger.fine("Sending ack for invalidation %s", invalidation);
- batcher.addAck(invalidation);
- batchingTask.ensureScheduled("Send-Ack");
- }
-
- /**
- * Sends a single registration subtree to the server.
- *
- * @param regSubtree subtree to send
- */
- void sendRegistrationSyncSubtree(RegistrationSubtree regSubtree, BatchingTask batchingTask) {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- batcher.addRegSubtree(regSubtree);
- logger.info("Adding subtree: %s", regSubtree);
- batchingTask.ensureScheduled("Send-reg-sync");
- }
-
- /** Sends pending data to the server (e.g., registrations, acks, registration sync messages). */
- void sendMessageToServer() {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- if (nextMessageSendTimeMs > internalScheduler.getCurrentTimeMs()) {
- logger.warning("In quiet period: not sending message to server: %s > %s",
- nextMessageSendTimeMs, internalScheduler.getCurrentTimeMs());
- return;
- }
-
- // Create the message from the batcher.
- ClientToServerMessage.Builder msgBuilder =
- batcher.toBuilder(listener.getClientToken() != null);
- if (msgBuilder == null) {
- // Happens when we don't have a token and are not sending an initialize message. Logged
- // in batcher.toBuilder().
- return;
- }
- msgBuilder.setHeader(createClientHeader());
- ++messageId;
-
- // Validate the message and send it.
- ClientToServerMessage message = msgBuilder.build();
- if (!msgValidator.isValid(message)) {
- logger.severe("Tried to send invalid message: %s", message);
- statistics.recordError(ClientErrorType.OUTGOING_MESSAGE_FAILURE);
- return;
- }
-
- statistics.recordSentMessage(SentMessageType.TOTAL);
- logger.fine("Sending message to server: {0}",
- CommonProtoStrings2.toLazyCompactString(message, true));
- network.sendMessage(message.toByteArray());
-
- // Record that the message was sent. We're invoking the listener directly, rather than
- // scheduling a new work unit to do it. It would be safer to do a schedule, but that's hard to
- // do in Android, we wrote this listener (it's InvalidationClientCore, so we know what it does),
- // and it's the last line of this function.
- listener.handleMessageSent();
- }
-
- /** Returns the header to include on a message to the server. */
- private ClientHeader.Builder createClientHeader() {
- Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");
- ClientHeader.Builder builder = ClientHeader.newBuilder()
- .setProtocolVersion(CommonInvalidationConstants2.PROTOCOL_VERSION)
- .setClientTimeMs(internalScheduler.getCurrentTimeMs())
- .setMessageId(Integer.toString(messageId))
- .setMaxKnownServerTimeMs(lastKnownServerTimeMs)
- .setRegistrationSummary(listener.getRegistrationSummary())
- .setClientType(clientType);
- ByteString clientToken = listener.getClientToken();
- if (clientToken != null) {
- logger.fine("Sending token on client->server message: %s",
- CommonProtoStrings2.toLazyCompactString(clientToken));
- builder.setClientToken(clientToken);
- }
- return builder;
- }
-
- @Override
- public ProtocolHandlerState marshal() {
- ProtocolHandlerState.Builder builder = ProtocolHandlerState.newBuilder();
- builder.setLastKnownServerTimeMs(lastKnownServerTimeMs);
- builder.setMessageId(messageId);
- builder.setNextMessageSendTimeMs(nextMessageSendTimeMs);
- builder.setBatcherState(batcher.marshal());
- return builder.build();
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/RecurringTask.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/RecurringTask.java
deleted file mode 100644
index 303bea59876..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/RecurringTask.java
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.SystemResources.Scheduler;
-import com.google.ipc.invalidation.util.ExponentialBackoffDelayGenerator;
-import com.google.ipc.invalidation.util.InternalBase;
-import com.google.ipc.invalidation.util.Marshallable;
-import com.google.ipc.invalidation.util.NamedRunnable;
-import com.google.ipc.invalidation.util.Smearer;
-import com.google.protos.ipc.invalidation.JavaClient.RecurringTaskState;
-
-
-/**
- * An abstraction for scheduling recurring tasks. Combines idempotent scheduling and smearing with
- * conditional retries and exponential backoff. Does not implement throttling. Designed to support a
- * variety of use cases, including:
- *
- * <ul>
- * <li>Idempotent scheduling, e.g., ensuring that a batching task is scheduled exactly once.
- * <li>Recurring tasks, e.g., periodic heartbeats.
- * <li>Retriable actions aimed at state change, e.g., sending initialization messages.
- * </ul>
- * Each instance of this class manages the state for a single task. Examples:
- *
- * <pre>
- * batchingTask = new RecurringTask("Batching", scheduler, logger, smearer, null,
- * batchingDelayMs, NO_DELAY) {
- * @Override
- * public boolean runTask() {
- * throttle.fire();
- * return false; // don't reschedule.
- * }
- * };
- * heartbeatTask = new RecurringTask("Heartbeat", scheduler, logger, smearer, null,
- * heartbeatDelayMs, NO_DELAY) {
- * @Override
- * public boolean runTask() {
- * sendInfoMessageToServer(false, !registrationManager.isStateInSyncWithServer());
- * return true; // reschedule
- * }
- * };
- * initializeTask = new RecurringTask("Token", scheduler, logger, smearer, expDelayGen, NO_DELAY,
- * networkTimeoutMs) {
- * @Override
- * public boolean runTask() {
- * // If token is still not assigned (as expected), sends a request. Otherwise, ignore.
- * if (clientToken == null) {
- * // Allocate a nonce and send a message requesting a new token.
- * setNonce(ByteString.copyFromUtf8(Long.toString(internalScheduler.getCurrentTimeMs())));
- * protocolHandler.sendInitializeMessage(applicationClientId, nonce, debugString);
- * return true; // reschedule to check state, retry if necessary after timeout
- * } else {
- * return false; // don't reschedule
- * }
- * }
- * };
- *</pre>
- *
- */
-public abstract class RecurringTask extends InternalBase
- implements Marshallable<RecurringTaskState> {
-
- /** Name of the task (for debugging purposes mostly). */
- private final String name;
-
- /** A logger */
- private final Logger logger;
-
- /** Scheduler for the scheduling the task as needed. */
- private final Scheduler scheduler;
-
- /**
- * The time after which the task is scheduled first. If no delayGenerator is specified, this is
- * also the delay used for retries.
- */
- private final int initialDelayMs;
-
- /** For a task that is retried, add this time to the delay. */
- private final int timeoutDelayMs;
-
- /** A smearer for spreading the delays. */
- private final Smearer smearer;
-
- /** A delay generator for exponential backoff. */
- private final TiclExponentialBackoffDelayGenerator delayGenerator;
-
- /** The runnable that is scheduled for the task. */
- private final NamedRunnable runnable;
-
- /** If the task has been currently scheduled. */
- private boolean isScheduled;
-
- /**
- * Creates a recurring task with the given parameters. The specs of the parameters are given in
- * the instance variables.
- * <p>
- * The created task is first scheduled with a smeared delay of {@code initialDelayMs}. If the
- * {@code this.run()} returns true on its execution, the task is rescheduled after a
- * {@code timeoutDelayMs} + smeared delay of {@code initialDelayMs} or {@code timeoutDelayMs} +
- * {@code delayGenerator.getNextDelay()} depending on whether the {@code delayGenerator} is null
- * or not.
- */
-
- public RecurringTask(String name, Scheduler scheduler, Logger logger, Smearer smearer,
- TiclExponentialBackoffDelayGenerator delayGenerator,
- final int initialDelayMs, final int timeoutDelayMs) {
- this.delayGenerator = delayGenerator;
- this.name = Preconditions.checkNotNull(name);
- this.logger = Preconditions.checkNotNull(logger);
- this.scheduler = Preconditions.checkNotNull(scheduler);
- this.smearer = Preconditions.checkNotNull(smearer);
- this.initialDelayMs = initialDelayMs;
- this.isScheduled = false;
- this.timeoutDelayMs = timeoutDelayMs;
-
- // Create a runnable that runs the task. If the task asks for a retry, reschedule it after
- // at a timeout delay. Otherwise, resets the delayGenerator.
- this.runnable = createRunnable();
- }
-
- /**
- * Creates a recurring task from {@code marshalledState}. Other parameters are as in the
- * constructor above.
- */
- RecurringTask(String name, Scheduler scheduler, Logger logger, Smearer smearer,
- TiclExponentialBackoffDelayGenerator delayGenerator,
- RecurringTaskState marshalledState) {
- this(name, scheduler, logger, smearer, delayGenerator, marshalledState.getInitialDelayMs(),
- marshalledState.getTimeoutDelayMs());
- this.isScheduled = marshalledState.getScheduled();
- }
-
- private NamedRunnable createRunnable() {
- return new NamedRunnable(name) {
- @Override
- public void run() {
- Preconditions.checkState(scheduler.isRunningOnThread(), "Not on scheduler thread");
- isScheduled = false;
- if (runTask()) {
- // The task asked to be rescheduled, so reschedule it after a timeout has occured.
- Preconditions.checkState((delayGenerator != null) || (initialDelayMs != 0),
- "Spinning: No exp back off and initialdelay is zero");
- ensureScheduled(true, "Retry");
- } else if (delayGenerator != null) {
- // The task asked not to be rescheduled. Treat it as having "succeeded" and reset the
- // delay generator.
- delayGenerator.reset();
- }
- }
- };
- }
-
- /**
- * Run the task and return true if the task should be rescheduled after a timeout. If false is
- * returned, the task is not scheduled again until {@code ensureScheduled} is called again.
- */
- public abstract boolean runTask();
-
- /** Returns the smearer used for randomizing delays. */
- Smearer getSmearer() {
- return smearer;
- }
-
- /** Returns the delay generator, if any. */
- ExponentialBackoffDelayGenerator getDelayGenerator() {
- return delayGenerator;
- }
-
- /**
- * Ensures that the task is scheduled (with {@code debugReason} as the reason to be printed
- * for debugging purposes). If the task has been scheduled, it is not scheduled again.
- * <p>
- * REQUIRES: Must be called from the scheduler thread.
- */
-
- public void ensureScheduled(String debugReason) {
- ensureScheduled(false, debugReason);
- }
-
- /**
- * Ensures that the task is scheduled if it is already not scheduled. If already scheduled, this
- * method is a no-op.
- *
- * @param isRetry If this is {@code false}, smears the {@code initialDelayMs} and uses that delay
- * for scheduling. If {@code isRetry} is true, it determines the new delay to be
- * {@code timeoutDelayMs} + {@ocde delayGenerator.getNextDelay()} if
- * {@code delayGenerator} is non-null. If {@code delayGenerator} is null, schedules the
- * task after a delay of {@code timeoutDelayMs} + smeared value of {@code initialDelayMs}
- * <p>
- * REQUIRES: Must be called from the scheduler thread.
- */
- private void ensureScheduled(boolean isRetry, String debugReason) {
- Preconditions.checkState(scheduler.isRunningOnThread());
- if (isScheduled) {
- return;
- }
- final int delayMs;
-
- if (isRetry) {
- // For a retried task, determine the delay to be timeout + extra delay (depending on whether
- // a delay generator was provided or not).
- if (delayGenerator != null) {
- delayMs = timeoutDelayMs + delayGenerator.getNextDelay();
- } else {
- delayMs = timeoutDelayMs + smearer.getSmearedDelay(initialDelayMs);
- }
- } else {
- delayMs = smearer.getSmearedDelay(initialDelayMs);
- }
-
- logger.fine("[%s] Scheduling %s with a delay %s, Now = %s", debugReason, name, delayMs,
- scheduler.getCurrentTimeMs());
- scheduler.schedule(delayMs, runnable);
- isScheduled = true;
- }
-
- /** For use only in the Android scheduler. */
- public NamedRunnable getRunnable() {
- return runnable;
- }
-
- @Override
- public RecurringTaskState marshal() {
- RecurringTaskState.Builder builder = RecurringTaskState.newBuilder()
- .setInitialDelayMs(initialDelayMs)
- .setScheduled(isScheduled)
- .setTimeoutDelayMs(timeoutDelayMs);
- if (delayGenerator != null) {
- builder.setBackoffState(delayGenerator.marshal());
- }
- return builder.build();
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/RegistrationManager.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/RegistrationManager.java
deleted file mode 100644
index 534322a221c..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/RegistrationManager.java
+++ /dev/null
@@ -1,303 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import com.google.ipc.invalidation.common.CommonProtoStrings2;
-import com.google.ipc.invalidation.common.CommonProtos2;
-import com.google.ipc.invalidation.common.DigestFunction;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.ticl.Statistics.ClientErrorType;
-import com.google.ipc.invalidation.ticl.TestableInvalidationClient.RegistrationManagerState;
-import com.google.ipc.invalidation.util.InternalBase;
-import com.google.ipc.invalidation.util.Marshallable;
-import com.google.ipc.invalidation.util.TextBuilder;
-import com.google.ipc.invalidation.util.TypedUtil;
-import com.google.protos.ipc.invalidation.ClientProtocol.ObjectIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationP;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationP.OpType;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationStatus;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSubtree;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSummary;
-import com.google.protos.ipc.invalidation.JavaClient.RegistrationManagerStateP;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-
-/**
- * Object to track desired client registrations. This class belongs to caller (e.g.,
- * InvalidationClientImpl) and is not thread-safe - the caller has to use this class in a
- * thread-safe manner.
- *
- */
-class RegistrationManager extends InternalBase implements Marshallable<RegistrationManagerStateP> {
-
- /** Prefix used to request all registrations. */
- static final byte[] EMPTY_PREFIX = new byte[]{};
-
- /** The set of regisrations that the application has requested for. */
- private DigestStore<ObjectIdP> desiredRegistrations;
-
- /** Statistics objects to track number of sent messages, etc. */
- private final Statistics statistics;
-
- /** Latest known server registration state summary. */
- private ProtoWrapper<RegistrationSummary> lastKnownServerSummary;
-
- /**
- * Map of object ids and operation types for which we have not yet issued any registration-status
- * upcall to the listener. We need this so that we can synthesize success upcalls if registration
- * sync, rather than a server message, communicates to us that we have a successful
- * (un)registration.
- * <p>
- * This is a map from object id to type, rather than a set of {@code RegistrationP}, because
- * a set of {@code RegistrationP} would assume that we always get a response for every operation
- * we issue, which isn't necessarily true (i.e., the server might send back an unregistration
- * status in response to a registration request).
- */
- private final Map<ProtoWrapper<ObjectIdP>, RegistrationP.OpType> pendingOperations =
- new HashMap<ProtoWrapper<ObjectIdP>, RegistrationP.OpType>();
-
- private final Logger logger;
-
- public RegistrationManager(Logger logger, Statistics statistics, DigestFunction digestFn,
- RegistrationManagerStateP registrationManagerState) {
- this.logger = logger;
- this.statistics = statistics;
- this.desiredRegistrations = new SimpleRegistrationStore(digestFn);
-
- if (registrationManagerState == null) {
- // Initialize the server summary with a 0 size and the digest corresponding
- // to it. Using defaultInstance would wrong since the server digest will
- // not match unnecessarily and result in an info message being sent.
- this.lastKnownServerSummary = ProtoWrapper.of(getRegistrationSummary());
- } else {
- this.lastKnownServerSummary =
- ProtoWrapper.of(registrationManagerState.getLastKnownServerSummary());
- desiredRegistrations.add(registrationManagerState.getRegistrationsList());
- for (RegistrationP regOp : registrationManagerState.getPendingOperationsList()) {
- pendingOperations.put(ProtoWrapper.of(regOp.getObjectId()), regOp.getOpType());
- }
- }
- }
-
- /**
- * Returns a copy of the registration manager's state
- * <p>
- * Direct test code MUST not call this method on a random thread. It must be called on the
- * InvalidationClientImpl's internal thread.
- */
-
- RegistrationManagerState getRegistrationManagerStateCopyForTest(DigestFunction digestFunction) {
- List<ObjectIdP> registeredObjects = new ArrayList<ObjectIdP>();
- for (ObjectIdP oid : desiredRegistrations.getElements(EMPTY_PREFIX, 0)) {
- registeredObjects.add(oid);
- }
- return new RegistrationManagerState(
- RegistrationSummary.newBuilder(getRegistrationSummary()).build(),
- RegistrationSummary.newBuilder(lastKnownServerSummary.getProto()).build(),
- registeredObjects);
- }
-
- /**
- * Sets the digest store to be {@code digestStore} for testing purposes.
- * <p>
- * REQUIRES: This method is called before the Ticl has done any operations on this object.
- */
-
- void setDigestStoreForTest(DigestStore<ObjectIdP> digestStore) {
- this.desiredRegistrations = digestStore;
- this.lastKnownServerSummary = ProtoWrapper.of(getRegistrationSummary());
- }
-
-
- Collection<ObjectIdP> getRegisteredObjectsForTest() {
- return desiredRegistrations.getElements(EMPTY_PREFIX, 0);
- }
-
- /** Perform registration/unregistation for all objects in {@code objectIds}. */
- Collection<ObjectIdP> performOperations(Collection<ObjectIdP> objectIds,
- RegistrationP.OpType regOpType) {
- // Record that we have pending operations on the objects.
- for (ObjectIdP objectId : objectIds) {
- pendingOperations.put(ProtoWrapper.of(objectId), regOpType);
- }
- // Update the digest appropriately.
- if (regOpType == RegistrationP.OpType.REGISTER) {
- return desiredRegistrations.add(objectIds);
- } else {
- return desiredRegistrations.remove(objectIds);
- }
- }
-
- /**
- * Returns a registration subtree for registrations where the digest of the object id begins with
- * the prefix {@code digestPrefix} of {@code prefixLen} bits. This method may also return objects
- * whose digest prefix does not match {@code digestPrefix}.
- */
- RegistrationSubtree getRegistrations(byte[] digestPrefix, int prefixLen) {
- RegistrationSubtree.Builder builder = RegistrationSubtree.newBuilder();
- for (ObjectIdP objectId : desiredRegistrations.getElements(digestPrefix, prefixLen)) {
- builder.addRegisteredObject(objectId);
- }
- return builder.build();
- }
-
- /**
- * Handles registration operation statuses from the server. Returns a list of booleans, one per
- * registration status, that indicates whether the registration operation was both successful and
- * agreed with the desired client state (i.e., for each registration status,
- * (status.optype == register) == desiredRegistrations.contains(status.objectid)).
- * <p>
- * REQUIRES: the caller subsequently make an informRegistrationStatus or informRegistrationFailure
- * upcall on the listener for each registration in {@code registrationStatuses}.
- */
- List<Boolean> handleRegistrationStatus(List<RegistrationStatus> registrationStatuses) {
- // Local-processing result code for each element of registrationStatuses.
- List<Boolean> localStatuses = new ArrayList<Boolean>(registrationStatuses.size());
- for (RegistrationStatus registrationStatus : registrationStatuses) {
- ObjectIdP objectIdProto = registrationStatus.getRegistration().getObjectId();
-
- // The object is no longer pending, since we have received a server status for it, so
- // remove it from the pendingOperations map. (It may or may not have existed in the map,
- // since we can receive spontaneous status messages from the server.)
- TypedUtil.remove(pendingOperations, ProtoWrapper.of(objectIdProto));
-
- // We start off with the local-processing set as success, then potentially fail.
- boolean isSuccess = true;
-
- // if the server operation succeeded, then local processing fails on "incompatibility" as
- // defined above.
- if (CommonProtos2.isSuccess(registrationStatus.getStatus())) {
- boolean appWantsRegistration = desiredRegistrations.contains(objectIdProto);
- boolean isOpRegistration =
- registrationStatus.getRegistration().getOpType() == RegistrationP.OpType.REGISTER;
- boolean discrepancyExists = isOpRegistration ^ appWantsRegistration;
- if (discrepancyExists) {
- // Remove the registration and set isSuccess to false, which will cause the caller to
- // issue registration-failure to the application.
- desiredRegistrations.remove(objectIdProto);
- statistics.recordError(ClientErrorType.REGISTRATION_DISCREPANCY);
- logger.info("Ticl discrepancy detected: registered = %s, requested = %s. " +
- "Removing %s from requested",
- isOpRegistration, appWantsRegistration,
- CommonProtoStrings2.toLazyCompactString(objectIdProto));
- isSuccess = false;
- }
- } else {
- // If the server operation failed, then also local processing fails.
- desiredRegistrations.remove(objectIdProto);
- logger.fine("Removing %s from committed",
- CommonProtoStrings2.toLazyCompactString(objectIdProto));
- isSuccess = false;
- }
- localStatuses.add(isSuccess);
- }
- return localStatuses;
- }
-
- /**
- * Removes all desired registrations and pending operations. Returns all object ids
- * that were affected.
- * <p>
- * REQUIRES: the caller issue a permanent failure upcall to the listener for all returned object
- * ids.
- */
- Collection<ProtoWrapper<ObjectIdP>> removeRegisteredObjects() {
- int numObjects = desiredRegistrations.size() + pendingOperations.size();
- Set<ProtoWrapper<ObjectIdP>> failureCalls = new HashSet<ProtoWrapper<ObjectIdP>>(numObjects);
- for (ObjectIdP objectId : desiredRegistrations.removeAll()) {
- failureCalls.add(ProtoWrapper.of(objectId));
- }
- failureCalls.addAll(pendingOperations.keySet());
- pendingOperations.clear();
- return failureCalls;
- }
-
- //
- // Digest-related methods
- //
-
- /** Returns a summary of the desired registrations. */
- RegistrationSummary getRegistrationSummary() {
- return CommonProtos2.newRegistrationSummary(desiredRegistrations.size(),
- desiredRegistrations.getDigest());
- }
-
- /**
- * Informs the manager of a new registration state summary from the server.
- * Returns a possibly-empty map of <object-id, reg-op-type>. For each entry in the map,
- * the caller should make an inform-registration-status upcall on the listener.
- */
- Set<ProtoWrapper<RegistrationP>> informServerRegistrationSummary(
- RegistrationSummary regSummary) {
- if (regSummary != null) {
- this.lastKnownServerSummary = ProtoWrapper.of(regSummary);
- }
- if (isStateInSyncWithServer()) {
- // If we are now in sync with the server, then the caller should make inform-reg-status
- // upcalls for all operations that we had pending, if any; they are also no longer pending.
- Set<ProtoWrapper<RegistrationP>> upcallsToMake =
- new HashSet<ProtoWrapper<RegistrationP>>(pendingOperations.size());
- for (Map.Entry<ProtoWrapper<ObjectIdP>, RegistrationP.OpType> entry :
- pendingOperations.entrySet()) {
- ObjectIdP objectId = entry.getKey().getProto();
- boolean isReg = entry.getValue() == OpType.REGISTER;
- upcallsToMake.add(ProtoWrapper.of(CommonProtos2.newRegistrationP(objectId, isReg)));
- }
- pendingOperations.clear();
- return upcallsToMake;
- } else {
- // If we are not in sync with the server, then the caller should make no upcalls.
- return Collections.emptySet();
- }
- }
-
- /**
- * Returns whether the local registration state and server state agree, based on the last
- * received server summary (from {@link #informServerRegistrationSummary}).
- */
- boolean isStateInSyncWithServer() {
- return TypedUtil.equals(lastKnownServerSummary, ProtoWrapper.of(getRegistrationSummary()));
- }
-
- @Override
- public void toCompactString(TextBuilder builder) {
- builder.appendFormat("Last known digest: %s, Requested regs: %s", lastKnownServerSummary,
- desiredRegistrations);
- }
-
- @Override
- public RegistrationManagerStateP marshal() {
- RegistrationManagerStateP.Builder builder = RegistrationManagerStateP.newBuilder();
- builder.setLastKnownServerSummary(lastKnownServerSummary.getProto());
- builder.addAllRegistrations(desiredRegistrations.getElements(EMPTY_PREFIX, 0));
- for (Map.Entry<ProtoWrapper<ObjectIdP>, RegistrationP.OpType> pendingOp :
- pendingOperations.entrySet()) {
- ObjectIdP objectId = pendingOp.getKey().getProto();
- boolean isReg = pendingOp.getValue() == OpType.REGISTER;
- builder.addPendingOperations(CommonProtos2.newRegistrationP(objectId, isReg));
- }
- return builder.build();
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/RunState.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/RunState.java
deleted file mode 100644
index 62d243211e2..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/RunState.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.util.Marshallable;
-import com.google.protos.ipc.invalidation.Client.RunStateP;
-
-/**
- * An abstraction that keeps track of whether the caller is started or stopped and only allows
- * the following transitions NOT_STARTED -> STARTED -> STOPPED. This class is thread-safe.
- *
- *
- */
-public class RunState implements Marshallable<RunStateP> {
- /** Current run state. */
- private RunStateP.State currentState;
- private Object lock = new Object();
-
- /** Constructs a new instance in the {@code NOT_STARTED} state. */
- public RunState() {
- currentState = RunStateP.State.NOT_STARTED;
- }
-
- /** Constructs a new instance with the state given in {@code runState}. */
- RunState(RunStateP runState) {
- this.currentState = runState.getState();
- }
-
- /**
- * Marks the current state to be STARTED.
- * <p>
- * REQUIRES: Current state is NOT_STARTED.
- */
- public void start() {
- synchronized (lock) {
- Preconditions.checkState(currentState == RunStateP.State.NOT_STARTED,
- "Cannot start: %s", currentState);
- currentState = RunStateP.State.STARTED;
- }
- }
-
- /**
- * Marks the current state to be STOPPED.
- * <p>
- * REQUIRES: Current state is STARTED.
- */
- public void stop() {
- synchronized (lock) {
- Preconditions.checkState(currentState == RunStateP.State.STARTED,
- "Cannot stop: %s", currentState);
- currentState = RunStateP.State.STOPPED;
- }
- }
-
- /**
- * Returns true iff {@link #start} has been called on this but {@link #stop} has not been called.
- */
- public boolean isStarted() {
- synchronized (lock) {
- return currentState == RunStateP.State.STARTED;
- }
- }
-
- /** Returns true iff {@link #start} and {@link #stop} have been called on this object. */
- public boolean isStopped() {
- synchronized (lock) {
- return currentState == RunStateP.State.STOPPED;
- }
- }
-
- @Override
- public RunStateP marshal() {
- return RunStateP.newBuilder().setState(currentState).build();
- }
-
- @Override
- public String toString() {
- return "<RunState: " + currentState + ">";
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/SafeStorage.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/SafeStorage.java
deleted file mode 100644
index 6dac0009bfd..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/SafeStorage.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import static com.google.ipc.invalidation.external.client.SystemResources.Scheduler.NO_DELAY;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.ipc.invalidation.external.client.SystemResources.Scheduler;
-import com.google.ipc.invalidation.external.client.SystemResources.Storage;
-import com.google.ipc.invalidation.external.client.types.Callback;
-import com.google.ipc.invalidation.external.client.types.SimplePair;
-import com.google.ipc.invalidation.external.client.types.Status;
-import com.google.ipc.invalidation.util.NamedRunnable;
-
-/**
- * An implementation of the Storage resource that schedules the callbacks on the given scheduler
- * thread.
- *
- */
-public class SafeStorage implements Storage {
-
- /** The delegate to which the calls are forwarded. */
- private final Storage delegate;
-
- /** The scheduler on which the callbacks are scheduled. */
- private Scheduler scheduler;
-
- SafeStorage(Storage delegate) {
- this.delegate = Preconditions.checkNotNull(delegate);
- }
-
- @Override
- public void setSystemResources(SystemResources resources) {
- this.scheduler = resources.getInternalScheduler();
- }
-
- @Override
- public void writeKey(String key, byte[] value, final Callback<Status> done) {
- delegate.writeKey(key, value, new Callback<Status>() {
- @Override
- public void accept(final Status status) {
- scheduler.schedule(NO_DELAY, new NamedRunnable("SafeStorage.writeKey") {
- @Override
- public void run() {
- done.accept(status);
- }
- });
- }
- });
- }
-
- @Override
- public void readKey(String key, final Callback<SimplePair<Status, byte[]>> done) {
- delegate.readKey(key, new Callback<SimplePair<Status, byte[]>>() {
- @Override
- public void accept(final SimplePair<Status, byte[]> result) {
- scheduler.schedule(NO_DELAY, new NamedRunnable("SafeStorage.readKey") {
- @Override
- public void run() {
- done.accept(result);
- }
- });
- }
- });
- }
-
- @Override
- public void deleteKey(String key, final Callback<Boolean> done) {
- delegate.deleteKey(key, new Callback<Boolean>() {
- @Override
- public void accept(final Boolean success) {
- scheduler.schedule(NO_DELAY, new NamedRunnable("SafeStorage.deleteKey") {
- @Override
- public void run() {
- done.accept(success);
- }
- });
- }
- });
- }
-
- @Override
- public void readAllKeys(final Callback<SimplePair<Status, String>> keyCallback) {
- delegate.readAllKeys(new Callback<SimplePair<Status, String>>() {
- @Override
- public void accept(final SimplePair<Status, String> keyResult) {
- scheduler.schedule(NO_DELAY, new NamedRunnable("SafeStorage.readAllKeys") {
- @Override
- public void run() {
- keyCallback.accept(keyResult);
- }
- });
- }
- });
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/SimpleRegistrationStore.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/SimpleRegistrationStore.java
deleted file mode 100644
index 384290ee5d5..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/SimpleRegistrationStore.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import com.google.ipc.invalidation.common.DigestFunction;
-import com.google.ipc.invalidation.common.ObjectIdDigestUtils;
-import com.google.ipc.invalidation.util.Bytes;
-import com.google.ipc.invalidation.util.InternalBase;
-import com.google.protos.ipc.invalidation.ClientProtocol.ObjectIdP;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.SortedMap;
-import java.util.TreeMap;
-
-/**
- * Simple, map-based implementation of {@link DigestStore}.
- *
- */
-class SimpleRegistrationStore extends InternalBase implements DigestStore<ObjectIdP> {
-
- /** All the registrations in the store mapped from the digest to the Object Id. */
- private final SortedMap<Bytes, ObjectIdP> registrations = new TreeMap<Bytes, ObjectIdP>();
-
- /** The function used to compute digests of objects. */
- private final DigestFunction digestFunction;
-
- /** The memoized digest of all objects in registrations. */
- private Bytes digest;
-
- SimpleRegistrationStore(DigestFunction digestFunction) {
- this.digestFunction = digestFunction;
- recomputeDigest();
- }
-
- @Override
- public boolean add(ObjectIdP oid) {
- if (registrations.put(ObjectIdDigestUtils.getDigest(oid, digestFunction), oid) == null) {
- recomputeDigest();
- return true;
- }
- return false;
- }
-
- @Override
- public Collection<ObjectIdP> add(Collection<ObjectIdP> oids) {
- Collection<ObjectIdP> addedOids = new ArrayList<ObjectIdP>();
- for (ObjectIdP oid : oids) {
- if (registrations.put(ObjectIdDigestUtils.getDigest(oid, digestFunction), oid) == null) {
- // There was no previous value, so this is a new item.
- addedOids.add(oid);
- }
- }
- if (!addedOids.isEmpty()) {
- // Only recompute the digest if we made changes.
- recomputeDigest();
- }
- return addedOids;
- }
-
- @Override
- public boolean remove(ObjectIdP oid) {
- if (registrations.remove(ObjectIdDigestUtils.getDigest(oid, digestFunction)) != null) {
- recomputeDigest();
- return true;
- }
- return false;
- }
-
- @Override
- public Collection<ObjectIdP> remove(Collection<ObjectIdP> oids) {
- Collection<ObjectIdP> removedOids = new ArrayList<ObjectIdP>();
- for (ObjectIdP oid : oids) {
- if (registrations.remove(ObjectIdDigestUtils.getDigest(oid, digestFunction)) != null) {
- removedOids.add(oid);
- }
- }
- if (!removedOids.isEmpty()) {
- // Only recompute the digest if we made changes.
- recomputeDigest();
- }
- return removedOids;
- }
-
- @Override
- public Collection<ObjectIdP> removeAll() {
- Collection<ObjectIdP> result = new ArrayList<ObjectIdP>(registrations.values());
- registrations.clear();
- recomputeDigest();
- return result;
- }
-
- @Override
- public boolean contains(ObjectIdP oid) {
- return registrations.containsKey(ObjectIdDigestUtils.getDigest(oid, digestFunction));
- }
-
- @Override
- public int size() {
- return registrations.size();
- }
-
- @Override
- public byte[] getDigest() {
- return digest.getByteArray();
- }
-
- @Override
- public Collection<ObjectIdP> getElements(byte[] oidDigestPrefix, int prefixLen) {
- // We always return all the registrations and let the Ticl sort it out.
- return registrations.values();
- }
-
- /** Recomputes the digests over all objects and sets {@code this.digest}. */
- private void recomputeDigest() {
- this.digest = ObjectIdDigestUtils.getDigest(registrations.keySet(), digestFunction);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/Statistics.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/Statistics.java
deleted file mode 100644
index 288254c5830..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/Statistics.java
+++ /dev/null
@@ -1,353 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import com.google.ipc.invalidation.common.CommonProtos2;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.types.SimplePair;
-import com.google.ipc.invalidation.util.InternalBase;
-import com.google.ipc.invalidation.util.Marshallable;
-import com.google.ipc.invalidation.util.TextBuilder;
-import com.google.ipc.invalidation.util.TypedUtil;
-import com.google.protos.ipc.invalidation.ClientProtocol.PropertyRecord;
-import com.google.protos.ipc.invalidation.JavaClient.StatisticsState;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Statistics for the Ticl, e.g., number of registration calls, number of token mismatches, etc.
- *
- */
-public class Statistics extends InternalBase implements Marshallable<StatisticsState> {
-
- // Implementation: To classify the statistics a bit better, we have a few enums to track different
- // types of statistics, e.g., sent message types, errors, etc. For each statistic type, we create
- // a map and provide a method to record an event for each type of statistic.
-
- /** Types of messages sent to the server: {@code ClientToServerMessage} for their description. */
- public enum SentMessageType {
- INFO,
- INITIALIZE,
- INVALIDATION_ACK,
- REGISTRATION,
- REGISTRATION_SYNC,
- TOTAL, // Refers to the actual ClientToServerMessage message sent on the network.
- }
-
- /**
- * Types of messages received from the server: {@code ServerToClientMessage} for their
- * description.
- */
- public enum ReceivedMessageType {
- INFO_REQUEST,
- INVALIDATION,
- REGISTRATION_STATUS,
- REGISTRATION_SYNC_REQUEST,
- TOKEN_CONTROL,
- ERROR,
- CONFIG_CHANGE,
- TOTAL, // Refers to the actual ServerToClientMessage messages received from the network.
- }
-
- /** Interesting API calls coming from the application ({@code InvalidationClient}). */
- public enum IncomingOperationType {
- ACKNOWLEDGE,
- REGISTRATION,
- UNREGISTRATION,
- }
-
- /** Different types of events issued by the {@code InvalidationListener}). */
- public enum ListenerEventType {
- INFORM_ERROR,
- INFORM_REGISTRATION_FAILURE,
- INFORM_REGISTRATION_STATUS,
- INVALIDATE,
- INVALIDATE_ALL,
- INVALIDATE_UNKNOWN,
- REISSUE_REGISTRATIONS,
- }
-
- /** Different types of errors observed by the Ticl. */
- public enum ClientErrorType {
- /** Acknowledge call received from client with a bad handle. */
- ACKNOWLEDGE_HANDLE_FAILURE,
-
- /** Incoming message dropped due to parsing, validation problems. */
- INCOMING_MESSAGE_FAILURE,
-
- /** Tried to send an outgoing message that was invalid. */
- OUTGOING_MESSAGE_FAILURE,
-
- /** Persistent state failed to deserialize correctly. */
- PERSISTENT_DESERIALIZATION_FAILURE,
-
- /** Read of blob from persistent state failed. */
- PERSISTENT_READ_FAILURE,
-
- /** Write of blob from persistent state failed. */
- PERSISTENT_WRITE_FAILURE,
-
- /** Message received with incompatible protocol version. */
- PROTOCOL_VERSION_FAILURE,
-
- /**
- * Registration at client and server is different, e.g., client thinks it is registered while
- * the server says it is unregistered (of course, sync will fix it).
- */
- REGISTRATION_DISCREPANCY,
-
- /** The nonce from the server did not match the current nonce by the client. */
- NONCE_MISMATCH,
-
- /** The current token at the client is different from the token in the incoming message. */
- TOKEN_MISMATCH,
-
- /** No message sent due to token missing. */
- TOKEN_MISSING_FAILURE,
-
- /** Received a message with a token (transient) failure. */
- TOKEN_TRANSIENT_FAILURE,
- }
-
- // Names of statistics types. Do not rely on reflection to determine type names because Proguard
- // may change them for Android clients.
- private static final String SENT_MESSAGE_TYPE_NAME = "SentMessageType";
- private static final String INCOMING_OPERATION_TYPE_NAME = "IncomingOperationType";
- private static final String RECEIVED_MESSAGE_TYPE_NAME = "ReceivedMessageType";
- private static final String LISTENER_EVENT_TYPE_NAME = "ListenerEventType";
- private static final String CLIENT_ERROR_TYPE_NAME = "ClientErrorType";
-
- // Map from stats enum names to values. Used in place of Enum.valueOf() because this method
- // invokes Enum.values() via reflection, and that method may be renamed by Proguard.
- private static final Map<String, SentMessageType> SENT_MESSAGE_TYPE_NAME_TO_VALUE_MAP =
- createValueOfMap(SentMessageType.values());
- private static final Map<String, IncomingOperationType>
- INCOMING_OPERATION_TYPE_NAME_TO_VALUE_MAP = createValueOfMap(IncomingOperationType.values());
- private static final Map<String, ReceivedMessageType> RECEIVED_MESSAGE_TYPE_NAME_TO_VALUE_MAP =
- createValueOfMap(ReceivedMessageType.values());
- private static final Map<String, ListenerEventType> LISTENER_EVENT_TYPE_NAME_TO_VALUE_MAP =
- createValueOfMap(ListenerEventType.values());
- private static final Map<String, ClientErrorType> CLIENT_ERROR_TYPE_NAME_TO_VALUE_MAP =
- createValueOfMap(ClientErrorType.values());
-
- // Maps for each type of Statistic to keep track of how many times each event has occurred.
-
- private final Map<SentMessageType, Integer> sentMessageTypes =
- new HashMap<SentMessageType, Integer>();
- private final Map<ReceivedMessageType, Integer> receivedMessageTypes =
- new HashMap<ReceivedMessageType, Integer>();
- private final Map<IncomingOperationType, Integer> incomingOperationTypes =
- new HashMap<IncomingOperationType, Integer>();
- private final Map<ListenerEventType, Integer> listenerEventTypes =
- new HashMap<ListenerEventType, Integer>();
- private final Map<ClientErrorType, Integer> clientErrorTypes =
- new HashMap<ClientErrorType, Integer>();
-
- public Statistics() {
- initializeMap(sentMessageTypes, SentMessageType.values());
- initializeMap(receivedMessageTypes, ReceivedMessageType.values());
- initializeMap(incomingOperationTypes, IncomingOperationType.values());
- initializeMap(listenerEventTypes, ListenerEventType.values());
- initializeMap(clientErrorTypes, ClientErrorType.values());
- }
-
- /** Returns a copy of this. */
- public Statistics getCopyForTest() {
- Statistics statistics = new Statistics();
- statistics.sentMessageTypes.putAll(sentMessageTypes);
- statistics.receivedMessageTypes.putAll(receivedMessageTypes);
- statistics.incomingOperationTypes.putAll(incomingOperationTypes);
- statistics.listenerEventTypes.putAll(listenerEventTypes);
- statistics.clientErrorTypes.putAll(clientErrorTypes);
- return statistics;
- }
-
- /** Returns the counter value for {@code clientErrorType}. */
- int getClientErrorCounterForTest(ClientErrorType clientErrorType) {
- return TypedUtil.mapGet(clientErrorTypes, clientErrorType);
- }
-
- /** Returns the counter value for {@code sentMessageType}. */
- int getSentMessageCounterForTest(SentMessageType sentMessageType) {
- return TypedUtil.mapGet(sentMessageTypes, sentMessageType);
- }
-
- /** Returns the counter value for {@code receivedMessageType}. */
- int getReceivedMessageCounterForTest(ReceivedMessageType receivedMessageType) {
- return TypedUtil.mapGet(receivedMessageTypes, receivedMessageType);
- }
-
- /** Records the fact that a message of type {@code sentMessageType} has been sent. */
- public void recordSentMessage(SentMessageType sentMessageType) {
- incrementValue(sentMessageTypes, sentMessageType);
- }
-
- /** Records the fact that a message of type {@code receivedMessageType} has been received. */
- public void recordReceivedMessage(ReceivedMessageType receivedMessageType) {
- incrementValue(receivedMessageTypes, receivedMessageType);
- }
-
- /**
- * Records the fact that the application has made a call of type
- * {@code incomingOperationType}.
- */
- public void recordIncomingOperation(IncomingOperationType incomingOperationType) {
- incrementValue(incomingOperationTypes, incomingOperationType);
- }
-
- /** Records the fact that the listener has issued an event of type {@code listenerEventType}. */
- public void recordListenerEvent(ListenerEventType listenerEventType) {
- incrementValue(listenerEventTypes, listenerEventType);
- }
-
- /** Records the fact that the client has observed an error of type {@code clientErrorType}. */
- public void recordError(ClientErrorType clientErrorType) {
- incrementValue(clientErrorTypes, clientErrorType);
- }
-
- /**
- * Modifies {@code performanceCounters} to contain all the statistics that are non-zero. Each pair
- * has the name of the statistic event and the number of times that event has occurred since the
- * client started.
- */
- public void getNonZeroStatistics(List<SimplePair<String, Integer>> performanceCounters) {
- // Add the non-zero values from the different maps to performanceCounters.
- fillWithNonZeroStatistics(sentMessageTypes, performanceCounters, SENT_MESSAGE_TYPE_NAME);
- fillWithNonZeroStatistics(receivedMessageTypes, performanceCounters,
- RECEIVED_MESSAGE_TYPE_NAME);
- fillWithNonZeroStatistics(incomingOperationTypes, performanceCounters,
- INCOMING_OPERATION_TYPE_NAME);
- fillWithNonZeroStatistics(listenerEventTypes, performanceCounters, LISTENER_EVENT_TYPE_NAME);
- fillWithNonZeroStatistics(clientErrorTypes, performanceCounters, CLIENT_ERROR_TYPE_NAME);
- }
-
- /** Modifies {@code result} to contain those statistics from {@code map} whose value is > 0. */
- private static <Key extends Enum<Key>> void fillWithNonZeroStatistics(Map<Key, Integer> map,
- List<SimplePair<String, Integer>> destination, String typeName) {
- String prefix = typeName + ".";
- for (Map.Entry<Key, Integer> entry : map.entrySet()) {
- if (entry.getValue() > 0) {
- destination.add(SimplePair.of(prefix + entry.getKey().name(), entry.getValue()));
- }
- }
- }
-
- /** Initializes a map from enum names to values of the given {@code keys}. */
- private static <Key extends Enum<Key>> Map<String, Key> createValueOfMap(Key[] keys) {
- HashMap<String, Key> map = new HashMap<String, Key>();
- for (Key key : keys) {
- map.put(key.name(), key);
- }
- return map;
- }
-
- /** Increments the value of {@code map}[{@code key}] by 1. */
- private static <Key> void incrementValue(Map<Key, Integer> map, Key key) {
- map.put(key, TypedUtil.mapGet(map, key) + 1);
- }
-
- /** Initializes all values for {@code keys} in {@code map} to be 0. */
- private static <Key> void initializeMap(Map<Key, Integer> map, Key[] keys) {
- for (Key key : keys) {
- map.put(key, 0);
- }
- }
-
- @Override
- public void toCompactString(TextBuilder builder) {
- List<SimplePair<String, Integer>> nonZeroValues = new ArrayList<SimplePair<String, Integer>>();
- getNonZeroStatistics(nonZeroValues);
- builder.appendFormat("Client Statistics: %s\n", nonZeroValues);
- }
-
- @Override
- public StatisticsState marshal() {
- // Get all the non-zero counters, convert them to proto PropertyRecord messages, and return
- // a StatisticsState containing the records.
- StatisticsState.Builder builder = StatisticsState.newBuilder();
- List<SimplePair<String, Integer>> counters = new ArrayList<SimplePair<String, Integer>>();
- getNonZeroStatistics(counters);
- for (SimplePair<String, Integer> counter : counters) {
- builder.addCounter(CommonProtos2.newPropertyRecord(counter.getFirst(), counter.getSecond()));
- }
- return builder.build();
- }
-
- /**
- * Given the serialized {@code performanceCounters} of the client statistics, returns a Statistics
- * object with the performance counter values from {@code performanceCounters}.
- */
-
- public static Statistics deserializeStatistics(Logger logger,
- Collection<PropertyRecord> performanceCounters) {
- Statistics statistics = new Statistics();
-
- // For each counter, parse out the counter name and value.
- for (PropertyRecord performanceCounter : performanceCounters) {
- String counterName = performanceCounter.getName();
- String[] parts = counterName.split("\\.");
- if (parts.length != 2) {
- logger.warning("Perf counter name must of form: class.value, skipping: %s", counterName);
- continue;
- }
- String className = parts[0];
- String fieldName = parts[1];
- int counterValue = performanceCounter.getValue();
-
- // Call the relevant method in a loop (i.e., depending on the type of the class).
- if (TypedUtil.<String>equals(className, SENT_MESSAGE_TYPE_NAME)) {
- incrementPerformanceCounterValue(logger, SENT_MESSAGE_TYPE_NAME_TO_VALUE_MAP,
- statistics.sentMessageTypes, fieldName, counterValue);
- } else if (TypedUtil.<String>equals(className, INCOMING_OPERATION_TYPE_NAME)) {
- incrementPerformanceCounterValue(logger, INCOMING_OPERATION_TYPE_NAME_TO_VALUE_MAP,
- statistics.incomingOperationTypes, fieldName, counterValue);
- } else if (TypedUtil.<String>equals(className, RECEIVED_MESSAGE_TYPE_NAME)) {
- incrementPerformanceCounterValue(logger, RECEIVED_MESSAGE_TYPE_NAME_TO_VALUE_MAP,
- statistics.receivedMessageTypes, fieldName, counterValue);
- } else if (TypedUtil.<String>equals(className, LISTENER_EVENT_TYPE_NAME)) {
- incrementPerformanceCounterValue(logger, LISTENER_EVENT_TYPE_NAME_TO_VALUE_MAP,
- statistics.listenerEventTypes, fieldName, counterValue);
- } else if (TypedUtil.<String>equals(className, CLIENT_ERROR_TYPE_NAME)) {
- incrementPerformanceCounterValue(logger, CLIENT_ERROR_TYPE_NAME_TO_VALUE_MAP,
- statistics.clientErrorTypes, fieldName, counterValue);
- } else {
- logger.warning("Skipping unknown enum class name %s", className);
- }
- }
- return statistics;
- }
-
- /**
- * Looks for an enum value with the given {@code fieldName} in {@code valueOfMap} and increments
- * the corresponding entry in {@code counts} by {@code counterValue}. Call to update statistics
- * for a single performance counter.
- */
- private static <Key extends Enum<Key>> void incrementPerformanceCounterValue(Logger logger,
- Map<String, Key> valueOfMap, Map<Key, Integer> counts, String fieldName, int counterValue) {
- Key type = TypedUtil.mapGet(valueOfMap, fieldName);
- if (type != null) {
- int currentValue = TypedUtil.mapGet(counts, type);
- counts.put(type, currentValue + counterValue);
- } else {
- logger.warning("Skipping unknown enum value name %s", fieldName);
- }
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/TestableInvalidationClient.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/TestableInvalidationClient.java
deleted file mode 100644
index e1d712dd3eb..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/TestableInvalidationClient.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.common.DigestFunction;
-import com.google.ipc.invalidation.external.client.InvalidationClient;
-import com.google.ipc.invalidation.external.client.InvalidationListener;
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.ipc.invalidation.util.InternalBase;
-import com.google.protobuf.ByteString;
-import com.google.protos.ipc.invalidation.Channel.NetworkEndpointId;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientConfigP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ObjectIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.RegistrationSummary;
-
-import java.util.Collection;
-
-
-/**
- * An interface that exposes some extra methods for testing an invalidation client implementation.
- *
- */
-public interface TestableInvalidationClient extends InvalidationClient {
-
- /** The state of the registration manager exposed for testing. */
- public class RegistrationManagerState extends InternalBase {
-
- /** The registration summary of all objects registered by the client (known at the client). */
- private final RegistrationSummary clientSummary;
-
- /** The last known registration summary from the server. */
- private final RegistrationSummary serverSummary;
-
- /** The objects registered by the client (as known at the client). */
- private final Collection<ObjectIdP> registeredObjects;
-
- public RegistrationManagerState(RegistrationSummary clientSummary,
- RegistrationSummary serverSummary, Collection<ObjectIdP> registeredObjects) {
- this.clientSummary = Preconditions.checkNotNull(clientSummary);
- this.serverSummary = Preconditions.checkNotNull(serverSummary);
- this.registeredObjects = Preconditions.checkNotNull(registeredObjects);
- }
-
- public RegistrationSummary getClientSummary() {
- return clientSummary;
- }
-
- public RegistrationSummary getServerSummary() {
- return serverSummary;
- }
-
- public Collection<ObjectIdP> getRegisteredObjects() {
- return registeredObjects;
- }
- }
-
- /** Returns whether the Ticl is started. */
- boolean isStartedForTest();
-
- /** Stops the system resources. */
- void stopResources();
-
- /** Returns the current time on the client. */
- long getResourcesTimeMs();
-
- /** Returns the client internal scheduler */
- SystemResources.Scheduler getInternalSchedulerForTest();
-
- /** Returns the client storage. */
- SystemResources.Storage getStorage();
-
- /** Returns a snapshot of the performance counters/statistics . */
- Statistics getStatisticsForTest();
-
- /** Returns the digest function used for computing digests for object registrations. */
- DigestFunction getDigestFunctionForTest();
-
- /**
- * Returns a copy of the registration manager's state
- * <p>
- * REQUIRES: This method is called on the internal scheduler.
- */
- RegistrationManagerState getRegistrationManagerStateCopyForTest();
-
- /**
- * Changes the existing delay for the network timeout delay in the operation scheduler to be
- * {@code delayMs}.
- */
- void changeNetworkTimeoutDelayForTest(int delayMs);
-
- /**
- * Changes the existing delay for the heartbeat delay in the operation scheduler to be
- * {@code delayMs}.
- */
- void changeHeartbeatDelayForTest(int delayMs);
-
- /**
- * Sets the digest store to be {@code digestStore} for testing purposes.
- * <p>
- * REQUIRES: This method is called before the Ticl has been started.
- */
- void setDigestStoreForTest(DigestStore<ObjectIdP> digestStore);
-
- /** Returns the client id that is used for squelching invalidations on the server side. */
- byte[] getApplicationClientIdForTest();
-
- /** Returns the listener that was registered by the caller. */
- InvalidationListener getInvalidationListenerForTest();
-
- /** Returns the current client token. */
- ByteString getClientTokenForTest();
-
- /** Returns the single key used to write all the Ticl state. */
- String getClientTokenKeyForTest();
-
- /** Returns the next time a message is allowed to be sent to the server (could be in the past). */
- long getNextMessageSendTimeMsForTest();
-
- /** Returns the configuration used by the client. */
- ClientConfigP getConfigForTest();
-
- /**
- * Returns the network endpoint id of the client. May throw {@code UnsupportedOperationException}.
- */
- NetworkEndpointId getNetworkIdForTest();
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/TestableNetworkChannel.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/TestableNetworkChannel.java
deleted file mode 100644
index 7ce2e5111a5..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/TestableNetworkChannel.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.protos.ipc.invalidation.Channel.NetworkEndpointId;
-
-/**
- * Extension of {@link com.google.ipc.invalidation.external.client.SystemResources.NetworkChannel}
- * that adds a method to get the network endpoint id.
- *
- */
-public interface TestableNetworkChannel extends SystemResources.NetworkChannel {
- /**
- * Returns the network id for testing. May throw {@link UnsupportedOperationException}.
- */
- NetworkEndpointId getNetworkIdForTest();
-
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/TiclExponentialBackoffDelayGenerator.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/TiclExponentialBackoffDelayGenerator.java
deleted file mode 100644
index a75cfed7510..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/TiclExponentialBackoffDelayGenerator.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl;
-
-import com.google.ipc.invalidation.util.ExponentialBackoffDelayGenerator;
-import com.google.ipc.invalidation.util.Marshallable;
-import com.google.protos.ipc.invalidation.Client.ExponentialBackoffState;
-
-import java.util.Random;
-
-/**
- * A subclass of {@link ExponentialBackoffDelayGenerator} that supports (un)marshalling to and from
- * protocol buffers.
- *
- */
-public class TiclExponentialBackoffDelayGenerator
- extends ExponentialBackoffDelayGenerator implements Marshallable<ExponentialBackoffState> {
-
- /**
- * Creates an exponential backoff delay generator. Parameters are as in
- * {@link ExponentialBackoffDelayGenerator#ExponentialBackoffDelayGenerator(Random, int, int)}.
- */
- public TiclExponentialBackoffDelayGenerator(Random random, int initialMaxDelay,
- int maxExponentialFactor) {
- super(random, initialMaxDelay, maxExponentialFactor);
- }
-
- /**
- * Restores a generator from {@code marshalledState}. Other parameters are as in
- * {@link ExponentialBackoffDelayGenerator#ExponentialBackoffDelayGenerator(Random, int, int)}.
- *
- * @param marshalledState marshalled state from which to restore.
- */
- public TiclExponentialBackoffDelayGenerator(Random random, int initialMaxDelay,
- int maxExponentialFactor, ExponentialBackoffState marshalledState) {
- super(random, initialMaxDelay, maxExponentialFactor, marshalledState.getCurrentMaxDelay(),
- marshalledState.getInRetryMode());
- }
-
- @Override
- public ExponentialBackoffState marshal() {
- return ExponentialBackoffState.newBuilder()
- .setCurrentMaxDelay(getCurrentMaxDelay())
- .setInRetryMode(getInRetryMode())
- .build();
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AbstractInvalidationService.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AbstractInvalidationService.java
deleted file mode 100644
index 886617aee5b..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AbstractInvalidationService.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android;
-
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.external.client.android.service.Event;
-import com.google.ipc.invalidation.external.client.android.service.InvalidationService;
-import com.google.ipc.invalidation.external.client.android.service.ListenerService;
-import com.google.ipc.invalidation.external.client.android.service.Request;
-import com.google.ipc.invalidation.external.client.android.service.Request.Action;
-import com.google.ipc.invalidation.external.client.android.service.Response;
-import com.google.ipc.invalidation.external.client.android.service.Response.Status;
-
-import android.app.Service;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.IBinder;
-import android.os.RemoteException;
-
-/**
- * Abstract base class for implementing the Android invalidation service. The service implements the
- * set of actions defined in {@link Action}. For each supported action, the service will extract the
- * action parameters and invoke an abstract methods that will be implemented by subclasses to
- * provide the action-specific processing.
- * <p>
- * This class acquires a lock before calling into the subclass and releases it after the call.
- * It also ensures that no call into the subclass will be made after the service has been destroyed.
- * <p>
- * The class also provides {@code sendEvent} methods that can be used to generate events back to the
- * client.
- *
- */
-public abstract class AbstractInvalidationService extends Service {
-
- private static final Logger logger = AndroidLogger.forTag("InvService");
-
- /**
- * Simple service stub that delegates back to methods on the service.
- */
- private final InvalidationService.Stub serviceBinder = new InvalidationService.Stub() {
-
- @Override
- public void handleRequest(Bundle input, Bundle output) {
- AbstractInvalidationService.this.handleRequest(input, output);
- }
- };
-
- /** Lock over all state in this class. */
- final Object lock = new Object();
-
- /** Whether the service is in the created state. */
- private boolean isCreated = false;
-
- @Override
- public void onCreate() {
- synchronized (lock) {
- super.onCreate();
- logger.fine("onCreate: %s", this.getClass());
- this.isCreated = true;
- }
- }
-
- @Override
- public void onDestroy() {
- synchronized (lock) {
- logger.fine("onDestroy: %s", this.getClass());
- this.isCreated = false;
- super.onDestroy();
- }
- }
-
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- return START_NOT_STICKY;
- }
-
- @Override
- public IBinder onBind(Intent intent) {
- return serviceBinder;
- }
-
- /** Returns whether the service is started. */
- boolean isCreatedForTest() {
- synchronized (lock) {
- return isCreated;
- }
- }
-
- protected void handleRequest(Bundle input, Bundle output) {
- synchronized (lock) {
- if (!isCreated) {
- logger.warning("Dropping bundle since not created: %s", input);
- return;
- }
- Request request = new Request(input);
- Response.Builder response = Response.newBuilder(request.getActionOrdinal(), output);
- Action action = request.getAction();
- logger.fine("%s request from %s", action, request.getClientKey());
- try {
- switch(action) {
- case CREATE:
- create(request, response);
- break;
- case RESUME:
- resume(request, response);
- break;
- case START:
- start(request, response);
- break;
- case STOP:
- stop(request, response);
- break;
- case REGISTER:
- register(request, response);
- break;
- case UNREGISTER:
- unregister(request, response);
- break;
- case ACKNOWLEDGE:
- acknowledge(request, response);
- break;
- case DESTROY:
- destroy(request, response);
- break;
- default:
- throw new IllegalStateException("Unknown action:" + action);
- }
- } catch (Exception e) {
- logger.severe("Client request error", e);
- response.setStatus(Status.RUNTIME_ERROR); // Subclass might already have set status.
- response.setException(e);
- }
- }
- }
-
- protected abstract void create(Request request, Response.Builder response);
-
- protected abstract void resume(Request request, Response.Builder response);
-
- protected abstract void start(Request request, Response.Builder response);
-
- protected abstract void stop(Request request, Response.Builder response);
-
- protected abstract void register(Request request, Response.Builder response);
-
- protected abstract void unregister(Request request, Response.Builder response);
-
- protected abstract void acknowledge(Request request, Response.Builder response);
-
- protected abstract void destroy(Request request, Response.Builder response);
-
- /**
- * Send event messages to application clients and provides common processing
- * of the response.
- */
- protected void sendEvent(ListenerService listenerService, Event event) {
- try {
- logger.fine("Sending %s event", event.getAction());
- Bundle responseBundle = new Bundle();
- listenerService.handleEvent(event.getBundle(), responseBundle);
-
- // Wrap the response bundle and throw on any failure from the client
- Response response = new Response(responseBundle);
- response.warnOnFailure();
- } catch (RemoteException exception) {
- logger.severe("Unable to send event", exception);
- throw new RuntimeException("Unable to send event", exception);
- }
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidC2DMConstants.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidC2DMConstants.java
deleted file mode 100644
index 184ba9c5696..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidC2DMConstants.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android;
-
-/**
- * Defines constants related to Invalidation C2DM messages.
- *
- */
-public class AndroidC2DMConstants {
-
- /**
- * The default account name associated with delivered C2DM messages. Alternate sender IDs
- * may be used when sharing C2DM within an application.
- */
- public static final String SENDER_ID = "ipc.invalidation@gmail.com";
-
- /**
- * The prefix that is added to data items when C2DM messages are generated. This prefix
- * <b>does not</b> appear on the data items in the received C2DM intent extra bundle.
- */
- public static final String DATA_PREFIX = "data.";
-
- /** Name of C2DM parameter containing the client key. */
- public static final String CLIENT_KEY_PARAM = "tid";
-
- /**
- * Name of C2DM parameter containing message content. If not set, data is not present. (We drop
- * it if it is too big.)
- */
- public static final String CONTENT_PARAM = "content";
-
- /** Name of the C2DM parameter containing an opaque token to be echoed on HTTP requests. */
- public static final String ECHO_PARAM = "echo-token";
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidChannel.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidChannel.java
deleted file mode 100644
index 3ff32042e6c..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidChannel.java
+++ /dev/null
@@ -1,462 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android;
-
-import com.google.android.gcm.GCMRegistrar;
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.common.CommonProtos2;
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.SystemResources.NetworkChannel;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.ticl.TestableNetworkChannel;
-import com.google.ipc.invalidation.util.ExponentialBackoffDelayGenerator;
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protos.ipc.invalidation.AndroidChannel.AddressedAndroidMessage;
-import com.google.protos.ipc.invalidation.AndroidChannel.MajorVersion;
-import com.google.protos.ipc.invalidation.Channel.NetworkEndpointId;
-import com.google.protos.ipc.invalidation.ClientProtocol.Version;
-
-import android.accounts.AccountManager;
-import android.accounts.AccountManagerCallback;
-import android.accounts.AccountManagerFuture;
-import android.accounts.AuthenticatorException;
-import android.accounts.OperationCanceledException;
-import android.content.Context;
-import android.net.http.AndroidHttpClient;
-import android.os.Build;
-import android.os.Bundle;
-import android.util.Base64;
-
-import org.apache.http.client.HttpClient;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Random;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.atomic.AtomicInteger;
-
-
-/**
- * Provides a bidirectional channel for Android devices using GCM (data center to device) and the
- * Android HTTP frontend (device to data center). The android channel computes a network endpoint id
- * based upon the GCM registration ID for the containing application ID and the client key of the
- * client using the channel. If an attempt is made to send messages on the channel before a GCM
- * registration ID has been assigned, it will temporarily buffer the outbound messages and send them
- * when the registration ID is eventually assigned.
- *
- */
-class AndroidChannel extends AndroidChannelBase implements TestableNetworkChannel {
-
- private static final Logger logger = AndroidLogger.forTag("InvChannel");
-
- /**
- * The maximum number of outbound messages that will be buffered while waiting for async delivery
- * of the GCM registration ID and authentication token. The general flow for a new client is
- * that an 'initialize' message is sent (and resent on a timed interval) until a session token is
- * sent back and this just prevents accumulation a large number of initialize messages (and
- * consuming memory) in a long delay or failure scenario.
- */
- private static final int MAX_BUFFERED_MESSAGES = 10;
-
- /** The channel version expected by this channel implementation */
-
- static final Version CHANNEL_VERSION =
- CommonProtos2.newVersion(MajorVersion.INITIAL.getNumber(), 0);
-
- /** How to long to wait initially before retrying a failed auth token request. */
- private static final int INITIAL_AUTH_TOKEN_RETRY_DELAY_MS = 1 * 1000; // 1 second
-
- /** Largest exponential backoff factor to use for auth token retries. */
- private static final int MAX_AUTH_TOKEN_RETRY_FACTOR = 60 * 60 * 12; // 12 hours
-
- /** Number of C2DM messages for unknown clients. */
-
- static final AtomicInteger numGcmInvalidClients = new AtomicInteger();
-
- /** Invalidation client proxy using the channel. */
- private final AndroidClientProxy proxy;
-
- /** Android context used to retrieve registration IDs. */
- private final Context context;
-
- /** System resources for this channel */
- private SystemResources resources;
-
- /**
- * When set, this registration ID is used rather than checking
- * {@link GCMRegistrar#getRegistrationId}. It should not be read directly: call
- * {@link #getRegistrationId} instead.
- */
- private String registrationIdForTest;
-
- /** The authentication token that can be used in channel requests to the server */
- private String authToken;
-
- /** Listener for network events. */
- private NetworkChannel.NetworkListener listener;
-
- // TODO: Add code to track time of last network activity (in either direction)
- // so inactive clients can be detected and periodically flushed from memory.
-
- /**
- * List that holds outbound messages while waiting for a registration ID. Allocated on
- * demand since it is only needed when there is no registration id.
- */
- private List<byte[]> pendingMessages = null;
-
- /**
- * Testing only flag that disables interactions with the AcccountManager for mock tests.
- */
- static boolean disableAccountManager = false;
-
- /**
- * Returns the default HTTP client to use for requests from the channel based upon its execution
- * context. The format of the User-Agent string is "<application-pkg>(<android-release>)".
- */
- static AndroidHttpClient getDefaultHttpClient(Context context) {
- return AndroidHttpClient.newInstance(
- context.getApplicationInfo().className + "(" + Build.VERSION.RELEASE + ")");
- }
-
- /** Executor used for HTTP calls to send messages to . */
-
- final ExecutorService scheduler = Executors.newSingleThreadExecutor();
-
- /**
- * Creates a new AndroidChannel.
- *
- * @param proxy the client proxy associated with the channel
- * @param httpClient the HTTP client to use to communicate with the Android invalidation frontend
- * @param context Android context
- */
- AndroidChannel(AndroidClientProxy proxy, HttpClient httpClient, Context context) {
- super(httpClient, proxy.getAuthType(), proxy.getService().getChannelUrl());
- this.proxy = Preconditions.checkNotNull(proxy);
- this.context = Preconditions.checkNotNull(context);
- }
-
- /**
- * Returns the GCM registration ID associated with the channel. Checks the {@link GCMRegistrar}
- * unless {@link #setRegistrationIdForTest} has been called.
- */
- String getRegistrationId() {
- String registrationId = (registrationIdForTest != null) ? registrationIdForTest :
- GCMRegistrar.getRegistrationId(context);
-
- // Callers check for null registration ID rather than "null or empty", so replace empty strings
- // with null here.
- if ("".equals(registrationId)) {
- registrationId = null;
- }
- return registrationId;
- }
-
- /** Returns the client proxy that is using the channel */
- AndroidClientProxy getClientProxy() {
- return proxy;
- }
-
- /**
- * Retrieves the list of pending messages in the channel (or {@code null} if there are none).
- */
- List<byte[]> getPendingMessages() {
- return pendingMessages;
- }
-
- @Override
-
- protected String getAuthToken() {
- return authToken;
- }
-
- /** A completion callback for an asynchronous operation. */
- interface CompletionCallback {
- void success();
- void failure();
- }
-
- /** An asynchronous runnable that calls a completion callback. */
- interface AsyncRunnable {
- void run(CompletionCallback callback);
- }
-
- /**
- * A utility function to run an async runnable with exponential backoff after failures.
- * @param runnable the asynchronous runnable.
- * @param scheduler used to schedule retries.
- * @param backOffGenerator a backoff generator that returns how to long to wait between retries.
- * The client must pass a new instance or reset the backoff generator before calling this
- * method.
- */
-
- static void retryUntilSuccessWithBackoff(final SystemResources.Scheduler scheduler,
- final ExponentialBackoffDelayGenerator backOffGenerator, final AsyncRunnable runnable) {
- logger.fine("Running %s", runnable);
- runnable.run(new CompletionCallback() {
- @Override
- public void success() {
- logger.fine("%s succeeded", runnable);
- }
-
- @Override
- public void failure() {
- int nextDelay = backOffGenerator.getNextDelay();
- logger.fine("%s failed, retrying after %s ms", nextDelay);
- scheduler.schedule(nextDelay, new Runnable() {
- @Override
- public void run() {
- retryUntilSuccessWithBackoff(scheduler, backOffGenerator, runnable);
- }
- });
- }
- });
- }
-
- /**
- * Initiates acquisition of an authentication token that can be used with channel HTTP requests.
- * Android token acquisition is asynchronous since it may require HTTP interactions with the
- * ClientLogin servers to obtain the token.
- */
- @SuppressWarnings("deprecation")
-
- synchronized void requestAuthToken(final CompletionCallback callback) {
- // If there is currently no token and no pending request, initiate one.
- if (disableAccountManager) {
- logger.fine("Not requesting auth token since account manager disabled");
- return;
- }
- if (authToken == null) {
- // Ask the AccountManager for the token, with a pending future to store it on the channel
- // once available.
- final AndroidChannel theChannel = this;
- AccountManager accountManager = AccountManager.get(proxy.getService());
- accountManager.getAuthToken(proxy.getAccount(), proxy.getAuthType(), true,
- new AccountManagerCallback<Bundle>() {
- @Override
- public void run(AccountManagerFuture<Bundle> future) {
- try {
- Bundle result = future.getResult();
- if (result.containsKey(AccountManager.KEY_INTENT)) {
- // TODO: Handle case where there are no authentication
- // credentials associated with the client account
- logger.severe("Token acquisition requires user login");
- callback.success(); // No further retries.
- }
- setAuthToken(result.getString(AccountManager.KEY_AUTHTOKEN));
- } catch (OperationCanceledException exception) {
- logger.warning("Auth cancelled", exception);
- // TODO: Send error to client
- } catch (AuthenticatorException exception) {
- logger.warning("Auth error acquiring token", exception);
- callback.failure();
- } catch (IOException exception) {
- logger.warning("IO Exception acquiring token", exception);
- callback.failure();
- }
- }
- }, null);
- } else {
- logger.fine("Auth token request already pending");
- callback.success();
- }
- }
-
- /*
- * Updates the registration ID for this channel, flushing any pending outbound messages that
- * were waiting for an id.
- */
- synchronized void setRegistrationIdForTest(String updatedRegistrationId) {
- // Synchronized to avoid concurrent access to pendingMessages
- if (registrationIdForTest != updatedRegistrationId) {
- logger.fine("Setting registration ID for test for client key %s", proxy.getClientKey());
- registrationIdForTest = updatedRegistrationId;
- informRegistrationIdChanged();
- }
- }
-
- /**
- * Call to inform the Android channel that the registration ID has changed. May kick loose some
- * pending outbound messages.
- */
- synchronized void informRegistrationIdChanged() {
- checkReady();
- }
-
- /**
- * Sets the authentication token to use for HTTP requests to the invalidation frontend and
- * flushes any pending messages (if appropriate).
- *
- * @param authToken the authentication token
- */
- synchronized void setAuthToken(String authToken) {
- logger.fine("Auth token received fo %s", proxy.getClientKey());
- this.authToken = authToken;
- checkReady();
- }
-
- @Override
- public void setListener(NetworkChannel.NetworkListener listener) {
- this.listener = Preconditions.checkNotNull(listener);
- }
-
- @Override
- public synchronized void sendMessage(final byte[] outgoingMessage) {
- // synchronized to avoid concurrent access to pendingMessages
-
- // If there is no registration id, we cannot compute a network endpoint id. If there is no
- // auth token, then we cannot authenticate the send request. Defer sending messages until both
- // are received.
- String registrationId = getRegistrationId();
- if ((registrationId == null) || (authToken == null)) {
- if (pendingMessages == null) {
- pendingMessages = new ArrayList<byte[]>();
- }
- logger.fine("Buffering outbound message: hasRegId: %s, hasAuthToken: %s",
- registrationId != null, authToken != null);
- if (pendingMessages.size() < MAX_BUFFERED_MESSAGES) {
- pendingMessages.add(outgoingMessage);
- } else {
- logger.warning("Exceeded maximum number of buffered messages, dropping outbound message");
- }
- return;
- }
-
- // Do the actual HTTP I/O on a separate thread, since we may be called on the main
- // thread for the application.
- scheduler.execute(new Runnable() {
- @Override
- public void run() {
- if (resources.isStarted()) {
- deliverOutboundMessage(outgoingMessage);
- } else {
- logger.warning("Dropping outbound messages because resources are stopped");
- }
- }
- });
- }
-
- /**
- * Called when either the registration or authentication token has been received to check to
- * see if channel is ready for network activity. If so, the status receiver is notified and
- * any pending messages are flushed.
- */
- private synchronized void checkReady() {
- String registrationId = getRegistrationId();
- if ((registrationId != null) && (authToken != null)) {
-
- logger.fine("Enabling network endpoint: %s", getWebEncodedEndpointId());
-
- // Notify the network listener that we are now network enabled
- if (listener != null) {
- listener.onOnlineStatusChange(true);
- }
-
- // Flush any pending messages
- if (pendingMessages != null) {
- for (byte [] message : pendingMessages) {
- sendMessage(message);
- }
- pendingMessages = null;
- }
- }
- }
-
- void receiveMessage(byte[] inboundMessage) {
- try {
- AddressedAndroidMessage addrMessage = AddressedAndroidMessage.parseFrom(inboundMessage);
- tryDeliverMessage(addrMessage);
- } catch (InvalidProtocolBufferException exception) {
- logger.severe("Failed decoding AddressedAndroidMessage as C2DM payload", exception);
- }
- }
-
- /**
- * Delivers the payload of {@code addrMessage} to the {@code callbackReceiver} if the client key
- * of the addressed message matches that of the {@link #proxy}.
- */
- @Override
- protected void tryDeliverMessage(AddressedAndroidMessage addrMessage) {
- String clientKey = proxy.getClientKey();
- if (addrMessage.getClientKey().equals(clientKey)) {
- logger.fine("Deliver to %s message %s", clientKey, addrMessage);
- listener.onMessageReceived(addrMessage.getMessage().toByteArray());
- } else {
- logger.severe("Not delivering message due to key mismatch: %s vs %s",
- addrMessage.getClientKey(), clientKey);
- numGcmInvalidClients.incrementAndGet();
- }
- }
-
- /** Returns the web encoded version of the channel network endpoint ID for HTTP requests. */
- @Override
- protected String getWebEncodedEndpointId() {
- NetworkEndpointId networkEndpointId = getNetworkId();
- return Base64.encodeToString(networkEndpointId.toByteArray(),
- Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING);
- }
-
- @Override
- public void setSystemResources(SystemResources resources) {
- this.resources = resources;
-
- // Prefetch the auth sub token. Since this might require an HTTP round trip, we do this
- // as soon as the resources are available.
- // TODO: Find a better place to fetch the auth token; this method
- // doesn't sound like one that should be doing work.
- retryUntilSuccessWithBackoff(resources.getInternalScheduler(),
- new ExponentialBackoffDelayGenerator(
- new Random(), INITIAL_AUTH_TOKEN_RETRY_DELAY_MS, MAX_AUTH_TOKEN_RETRY_FACTOR),
- new AsyncRunnable() {
- @Override
- public void run(CompletionCallback callback) {
- requestAuthToken(callback);
- }
- });
- }
-
- @Override
- public NetworkEndpointId getNetworkIdForTest() {
- return getNetworkId();
- }
-
- @Override
- protected Logger getLogger() {
- return resources.getLogger();
- }
-
- private NetworkEndpointId getNetworkId() {
- String registrationId = getRegistrationId();
- return CommonProtos2.newAndroidEndpointId(registrationId, proxy.getClientKey(),
- proxy.getService().getPackageName(), CHANNEL_VERSION);
- }
-
- ExecutorService getExecutorServiceForTest() {
- return scheduler;
- }
-
- @Override
- void setHttpClientForTest(HttpClient client) {
- if (this.httpClient instanceof AndroidHttpClient) {
- // Release the previous client if any.
- ((AndroidHttpClient) this.httpClient).close();
- }
- super.setHttpClientForTest(client);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidChannelBase.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidChannelBase.java
deleted file mode 100644
index 6dd106bc018..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidChannelBase.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.protos.ipc.invalidation.AndroidChannel.AddressedAndroidMessage;
-
-import org.apache.http.client.ClientProtocolException;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.entity.ByteArrayEntity;
-import org.apache.http.impl.client.BasicResponseHandler;
-
-import java.io.IOException;
-
-
-/**
- * Implementation of the HTTP communication used by {@code AndroidChannel}. Factored into
- * a separate class that can be run outside the Android environment to improve testing.
- *
- */
-
-public abstract class AndroidChannelBase {
- /** Http client to use when making requests to . */
- HttpClient httpClient;
-
- /** Authentication type for frontends. */
- private final String authType;
-
- /** URL of the frontends. */
- private final String channelUrl;
-
- /** The token that will be echoed to the data center in the headers of all HTTP requests. */
- private String echoToken = null;
-
- /**
- * Creates an instance that uses {@code httpClient} to send requests to {@code channelUrl}
- * using an auth type of {@code authType}.
- */
- protected AndroidChannelBase(HttpClient httpClient, String authType, String channelUrl) {
- this.httpClient = httpClient;
- this.authType = authType;
- this.channelUrl = channelUrl;
- }
-
- /** Sends {@code outgoingMessage} to . */
- void deliverOutboundMessage(final byte[] outgoingMessage) {
- getLogger().fine("Delivering outbound message: %s bytes", outgoingMessage.length);
- StringBuilder target = new StringBuilder();
-
- // Build base URL that targets the inbound request service with the encoded network endpoint id
- target.append(channelUrl);
- target.append(AndroidHttpConstants.REQUEST_URL);
- target.append(getWebEncodedEndpointId());
-
- // Add query parameter indicating the service to authenticate against
- target.append('?');
- target.append(AndroidHttpConstants.SERVICE_PARAMETER);
- target.append('=');
- target.append(authType);
-
- // Construct entity containing the outbound protobuf msg
- ByteArrayEntity contentEntity = new ByteArrayEntity(outgoingMessage);
- contentEntity.setContentType(AndroidHttpConstants.PROTO_CONTENT_TYPE);
-
- // Construct POST request with the entity content and appropriate authorization
- HttpPost httpPost = new HttpPost(target.toString());
- httpPost.setEntity(contentEntity);
- setPostHeaders(httpPost);
- try {
- String response = httpClient.execute(httpPost, new BasicResponseHandler());
- } catch (ClientProtocolException exception) {
- // TODO: Distinguish between key HTTP error codes and handle more specifically
- // where appropriate.
- getLogger().warning("Error from server on request: %s", exception);
- } catch (IOException exception) {
- getLogger().warning("Error writing request: %s", exception);
- } catch (RuntimeException exception) {
- getLogger().warning("Runtime exception writing request: %s", exception);
- }
- }
-
- /** Sets the Authorization and echo headers on {@code httpPost}. */
- private void setPostHeaders(HttpPost httpPost) {
- httpPost.setHeader("Authorization", "GoogleLogin auth=" + getAuthToken());
- if (echoToken != null) {
- // If we have a token to echo to the server, echo it.
- httpPost.setHeader(AndroidHttpConstants.ECHO_HEADER, echoToken);
- }
- }
-
- /**
- * If {@code echoToken} is not {@code null}, updates the token that will be sent in the header
- * of all HTTP requests.
- */
- void updateEchoToken(String echoToken) {
- if (echoToken != null) {
- this.echoToken = echoToken;
- }
- }
-
- /** Returns the token that will be sent in the header of all HTTP requests. */
- String getEchoTokenForTest() {
- return this.echoToken;
- }
-
- /** Sets the HTTP client to {@code client}. */
- void setHttpClientForTest(HttpClient client) {
- this.httpClient = Preconditions.checkNotNull(client);
- }
-
- /** Returns the base-64-encoded network endpoint id for the client. */
- protected abstract String getWebEncodedEndpointId();
-
- /** Returns the current authentication token for the client for web requests to . */
- protected abstract String getAuthToken();
-
- /** Returns the logger to use. */
- protected abstract Logger getLogger();
-
- /** Attempts to deliver a {@code message} from to the local client. */
- protected abstract void tryDeliverMessage(AddressedAndroidMessage message);
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidClientManager.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidClientManager.java
deleted file mode 100644
index c2dd46e80b0..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidClientManager.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android;
-
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.service.AndroidClientException;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.external.client.android.service.Response.Status;
-import com.google.ipc.invalidation.ticl.InvalidationClientCore;
-import com.google.ipc.invalidation.util.TypedUtil;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientConfigP;
-
-import android.accounts.Account;
-import android.content.Context;
-import android.content.Intent;
-
-import java.util.HashMap;
-import java.util.Map;
-
-
-/**
- * Manages active client instances for the Android invalidation service. The client manager contains
- * the code to create, persist, load, and lookup client instances, as well as handling the
- * propagation of any C2DM registration notifications to active clients.
- *
- */
-public class AndroidClientManager {
-
- /** Logger */
- private static final Logger logger = AndroidLogger.forTag("InvClientManager");
-
- /**
- * The client configuration used creating new invalidation client instances. This is normally
- * a constant but may be varied for testing.
- */
- private static ClientConfigP clientConfig = InvalidationClientCore.createConfig().build();
-
- /** The invalidation service associated with this manager */
- private final AndroidInvalidationService service;
-
- /**
- * When set, this registration ID is used rather than the ID returned by
- * {@code GCMRegistrar.getRegistrationId()}.
- */
- private static String registrationIdForTest;
-
- /** A map from client key to client proxy instances for in-memory client instances */
- private final Map<String, AndroidClientProxy> clientMap =
- new HashMap<String, AndroidClientProxy>();
-
- /** All client manager operations are synchronized on this lock */
- private final Object lock = new Object();
-
- /** Creates a new client manager instance associated with the provided service */
- AndroidClientManager(AndroidInvalidationService service) {
- this.service = service;
- }
-
- /**
- * Returns the number of managed clients.
- */
- int getClientCount() {
- synchronized (lock) {
- return clientMap.size();
- }
- }
-
- /**
- * Creates a new Android client proxy with the provided attributes. Before creating, will check to
- * see if there is an existing client with attributes that match and return it if found. If there
- * is an existing client with the same key but attributes that do not match, an exception will be
- * thrown. If no client with a matching key exists, a new client proxy will be created and
- * returned.
- *
- * @param clientKey key that uniquely identifies the client on the device.
- * @param clientType client type.
- * @param account user account associated with the client.
- * @param authType authentication type for the client.
- * @param eventIntent intent that can be used to bind to an event listener for the client.
- * @return an android invalidation client instance representing the client.
- */
- AndroidClientProxy create(String clientKey, int clientType, Account account, String authType,
- Intent eventIntent) {
- synchronized (lock) {
-
- // First check to see if an existing client is found
- AndroidClientProxy proxy = lookup(clientKey);
- if (proxy != null) {
- if (!proxy.getAccount().equals(account) || !proxy.getAuthType().equals(authType)) {
- throw new AndroidClientException(
- Status.INVALID_CLIENT, "Account does not match existing client");
- }
- return proxy;
- }
-
- // If not found, create a new client proxy instance to represent the client.
- AndroidStorage store = createAndroidStorage(service, clientKey);
- store.create(clientType, account, authType, eventIntent);
- proxy = new AndroidClientProxy(service, store, clientConfig);
- if (registrationIdForTest != null) {
- proxy.getChannel().setRegistrationIdForTest(registrationIdForTest);
- }
- clientMap.put(clientKey, proxy);
- logger.fine("Client %s created", clientKey);
- return proxy;
- }
- }
-
- /**
- * Retrieves an existing client that matches the provided key, loading it if necessary. If no
- * matching client can be found, an exception is thrown.
- *
- * @param clientKey the client key for the client to retrieve.
- * @return the matching client instance
- */
- AndroidClientProxy get(String clientKey) {
- synchronized (lock) {
- return lookup(clientKey);
- }
- }
-
- /**
- * Removes any client proxy instance associated with the provided key from memory but leaves the
- * instance persisted. The client may subsequently be loaded again by calling {@code #get}.
- *
- * @param clientKey the client key of the instance to remove from memory.
- */
- void remove(String clientKey) {
- synchronized (lock) {
- // Remove the proxy from the managed set and release any associated resources
- AndroidClientProxy proxy = clientMap.remove(clientKey);
- if (proxy != null) {
- proxy.release();
- }
- }
- }
-
- /**
- * Looks up the client proxy instance associated with the provided key and returns it (or {@code
- * null} if not found).
- *
- * @param clientKey the client key to look up
- * @return the client instance or {@code null}.
- */
-
- AndroidClientProxy lookup(String clientKey) {
- synchronized (lock) {
- // See if the client is already resident in memory
- AndroidClientProxy client = clientMap.get(clientKey);
- if (client == null) {
- // Attempt to load the client from the store
- AndroidStorage storage = createAndroidStorage(service, clientKey);
- if (storage.load()) {
- logger.fine("Client %s loaded from disk", clientKey);
- client = new AndroidClientProxy(service, storage, clientConfig);
- clientMap.put(clientKey, client);
- }
- }
- return client;
- }
- }
-
- /**
- * Sets the GCM registration ID that should be used for all managed clients (new and existing).
- */
- void informRegistrationIdChanged() {
- synchronized (lock) {
- // Propagate the value to all existing clients
- for (AndroidClientProxy proxy : clientMap.values()) {
- proxy.getChannel().informRegistrationIdChanged();
- }
- }
- }
-
- /**
- * Releases all managed clients and drops them from the managed set.
- */
- void releaseAll() {
- synchronized (lock) {
- for (AndroidClientProxy clientProxy : clientMap.values()) {
- clientProxy.release();
- }
- clientMap.clear();
- }
- }
-
- /**
- * Returns an android storage instance for managing client state.
- */
-
- protected AndroidStorage createAndroidStorage(Context context, String clientKey) {
- synchronized (lock) {
- return new AndroidStorage(context, clientKey);
- }
- }
-
-
- static ClientConfigP setConfigForTest(ClientConfigP newConfig) {
- logger.info("Setting client configuration: %s", newConfig);
- ClientConfigP currentConfig = clientConfig;
- clientConfig = newConfig;
- return clientConfig;
- }
-
-
- public static void setRegistrationIdForTest(String registrationIdForTest) {
- AndroidClientManager.registrationIdForTest = registrationIdForTest;
- }
-
- /** Returns whether all loaded clients are stopped. */
- public boolean areAllClientsStopped() {
- synchronized (lock) {
- for (AndroidClientProxy proxy : clientMap.values()) {
- if (proxy.isStarted()) {
- return false;
- }
- }
- return true;
- }
- }
-
- /** Returns whether the client with key {@code clientKey} is in memory. */
- public boolean isLoadedForTest(String clientKey) {
- synchronized (lock) {
- return TypedUtil.containsKey(clientMap, clientKey);
- }
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidClientProxy.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidClientProxy.java
deleted file mode 100644
index 927e71b89a1..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidClientProxy.java
+++ /dev/null
@@ -1,387 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.InvalidationClient;
-import com.google.ipc.invalidation.external.client.InvalidationListener;
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.AndroidInvalidationClient;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.external.client.android.service.Event;
-import com.google.ipc.invalidation.external.client.android.service.ListenerBinder;
-import com.google.ipc.invalidation.external.client.android.service.ListenerService;
-import com.google.ipc.invalidation.external.client.android.service.ServiceBinder.BoundWork;
-import com.google.ipc.invalidation.external.client.types.AckHandle;
-import com.google.ipc.invalidation.external.client.types.ErrorInfo;
-import com.google.ipc.invalidation.external.client.types.Invalidation;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-import com.google.ipc.invalidation.ticl.InvalidationClientCore;
-import com.google.ipc.invalidation.ticl.InvalidationClientImpl;
-import com.google.protos.ipc.invalidation.AndroidState.ClientMetadata;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientConfigP;
-
-import android.accounts.Account;
-import android.content.Context;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.net.http.AndroidHttpClient;
-
-import java.util.Collection;
-import java.util.Random;
-
-
-/**
- * A bidirectional client proxy that wraps and delegates requests to a TICL instance and routes
- * events generated by the TICL back to the associated listener.
- *
- */
-class AndroidClientProxy implements AndroidInvalidationClient {
-
- private static final Logger logger = AndroidLogger.forTag("InvClientProxy");
-
- /**
- * A reverse proxy for delegating raised invalidation events back to the client (via the
- * associated service).
- */
- class AndroidListenerProxy implements InvalidationListener {
-
- /** Binder that can be use to bind back to event listener service */
-
- final ListenerBinder binder;
-
- /**
- * Creates a new listener reverse proxy.
- */
- private AndroidListenerProxy() {
- this.binder = new ListenerBinder(service, Event.LISTENER_INTENT, metadata.getListenerClass());
- }
-
- @Override
- public void ready(InvalidationClient client) {
- Event event = Event.newBuilder(Event.Action.READY).setClientKey(clientKey).build();
- sendEvent(event);
- }
-
- @Override
- public void informRegistrationStatus(
- InvalidationClient client, ObjectId objectId, RegistrationState regState) {
- Event event = Event.newBuilder(Event.Action.INFORM_REGISTRATION_STATUS)
- .setClientKey(clientKey).setObjectId(objectId).setRegistrationState(regState).build();
- sendEvent(event);
- }
-
- @Override
- public void informRegistrationFailure(
- InvalidationClient client, ObjectId objectId, boolean isTransient, String errorMessage) {
- Event event = Event.newBuilder(Event.Action.INFORM_REGISTRATION_FAILURE)
- .setClientKey(clientKey).setObjectId(objectId).setIsTransient(isTransient)
- .setError(errorMessage).build();
- sendEvent(event);
- }
-
- @Override
- public void invalidate(
- InvalidationClient client, Invalidation invalidation, AckHandle ackHandle) {
- Event event = Event.newBuilder(Event.Action.INVALIDATE)
- .setClientKey(clientKey).setInvalidation(invalidation).setAckHandle(ackHandle).build();
- sendEvent(event);
- }
-
- @Override
- public void invalidateAll(InvalidationClient client, AckHandle ackHandle) {
- Event event = Event.newBuilder(Event.Action.INVALIDATE_ALL)
- .setClientKey(clientKey).setAckHandle(ackHandle).build();
- sendEvent(event);
- }
-
- @Override
- public void invalidateUnknownVersion(
- InvalidationClient client, ObjectId objectId, AckHandle ackHandle) {
- Event event = Event.newBuilder(Event.Action.INVALIDATE_UNKNOWN)
- .setClientKey(clientKey).setObjectId(objectId).setAckHandle(ackHandle).build();
- sendEvent(event);
- }
-
- @Override
- public void reissueRegistrations(InvalidationClient client, byte[] prefix, int prefixLength) {
- Event event = Event.newBuilder(Event.Action.REISSUE_REGISTRATIONS)
- .setClientKey(clientKey).setPrefix(prefix, prefixLength).build();
- sendEvent(event);
- }
-
- @Override
- public void informError(InvalidationClient client, ErrorInfo errorInfo) {
- Event event = Event.newBuilder(Event.Action.INFORM_ERROR)
- .setClientKey(clientKey).setErrorInfo(errorInfo).build();
- sendEvent(event);
- }
-
- /**
- * Releases any resources associated with the proxy listener.
- */
- public void release() {
- binder.release();
- }
-
- /**
- * Send event messages to application clients and provides common processing of the response.
- */
- private void sendEvent(final Event event) {
- binder.runWhenBound(new BoundWork<ListenerService>() {
- @Override
- public void run(ListenerService listenerService) {
- logger.fine("Sending %s event to %s", event.getAction(), clientKey);
- service.sendEvent(listenerService, event);
- }
- });
- }
- }
-
- /** The service associated with this proxy */
- private final AndroidInvalidationService service;
-
- /** the client key for this client proxy */
- private final String clientKey;
-
- /** The invalidation client to delegate requests to */
-
- final InvalidationClient delegate;
-
- /** The reverse listener proxy for this client proxy */
- private final AndroidListenerProxy listener;
-
- /** The stored state associated with this client */
- private final ClientMetadata metadata;
-
- /** The channel for this client */
- private final AndroidChannel channel;
-
- /** The system resources for this client */
- private final SystemResources resources;
-
- /** The HTTP client used by the underlying channel */
- private final AndroidHttpClient httpClient;
-
- /** {@code true} if client is started */
- private boolean started;
-
- /**
- * Creates a new client proxy instance.
- *
- * @param service the service within which the client proxy is executing.
- * @param storage the storage instance that contains client metadata and can be used to read or
- * write client properties.
- */
- AndroidClientProxy(AndroidInvalidationService service, AndroidStorage storage,
- ClientConfigP config) {
- this.service = service;
- this.metadata = storage.getClientMetadata();
- this.clientKey = metadata.getClientKey();
- this.listener = new AndroidListenerProxy();
- this.httpClient = AndroidChannel.getDefaultHttpClient(service);
-
- this.channel = new AndroidChannel(this, httpClient, service);
- this.resources =
- AndroidResourcesFactory.createResourcesBuilder(clientKey, channel, storage).build();
- String applicationName = getApplicationNameWithVersion(service,
- storage.getClientMetadata().getListenerPkg());
- this.delegate = createClient(resources, metadata.getClientType(), clientKey.getBytes(),
- applicationName, listener, config);
- }
-
- /**
- * Returns the application name string to pass to the Ticl, computed as a combination of the
- * listener package and the application version.
- */
-
- static String getApplicationNameWithVersion(Context context, String listenerPackage) {
- String appVersion = "unknown";
- try {
- PackageInfo packageInfo =
- context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
- String retrievedVersion = packageInfo.versionName;
- if (retrievedVersion != null) {
- appVersion = retrievedVersion;
- }
- } catch (NameNotFoundException exception) {
- // AndroidLogger does not use setSystemResources, so it's safe to use the logger here.
- logger.warning("Cannot retrieve current application version: %s", exception);
- }
- return listenerPackage + "#" + appVersion;
- }
-
- public final Account getAccount() {
- return new Account(metadata.getAccountName(), metadata.getAccountType());
- }
-
- public final String getAuthType() {
- return metadata.getAuthType();
- }
-
- @Override
- public final String getClientKey() {
- return metadata.getClientKey();
- }
-
- /** Returns the android service that is asociated with this proxy. */
- final AndroidInvalidationService getService() {
- return service;
- }
-
- /** Returns the network channel for this proxy. */
- final AndroidChannel getChannel() {
- return channel;
- }
-
- /** Returns the underlying invalidation client instance or {@code null} */
-
- final InvalidationClient getDelegate() {
- return delegate;
- }
-
- /** Returns the invalidation listener for this proxy */
-
- final AndroidListenerProxy getListener() {
- return listener;
- }
-
- /** Returns the storage used by the proxy. */
- final AndroidStorage getStorage() {
- return (AndroidStorage) resources.getStorage();
- }
-
- boolean isStarted() {
- return started;
- }
-
- @Override
- public void start() {
- if (started) {
- logger.info("Not starting Ticl since already started");
- return;
- }
- resources.start();
- delegate.start();
- started = true;
- }
-
- @Override
- public void stop() {
- // When a client is stopped, stop the TICL and its resources and remove it from the client
- // manager. This means that any subsequent requests (like another start) will be executed
- // against a clean TICL instance w/ no preexisting state from before the stop.
- if (!started) {
- logger.info("Not stopping Ticl since already stopped");
- return;
- }
- stopTicl();
- resources.stop();
- AndroidInvalidationService.getClientManager().remove(clientKey);
- }
-
- @Override
- public void register(Collection<ObjectId> objectIds) {
- delegate.register(objectIds);
- }
-
- @Override
- public void register(ObjectId objectId) {
- delegate.register(objectId);
- }
-
- @Override
- public void unregister(Collection<ObjectId> objectIds) {
- delegate.unregister(objectIds);
- }
-
- @Override
- public void unregister(ObjectId objectId) {
- delegate.unregister(objectId);
- }
-
- @Override
- public void acknowledge(AckHandle ackHandle) {
- delegate.acknowledge(ackHandle);
- }
-
- /**
- * Called when the client proxy is being removed from memory and will no longer be in use.
- * Releases any resources associated with the client proxy.
- */
- @Override
- public void release() {
- // Release the listener associated with the proxy
- listener.release();
-
- // Stop system resources associated with the client
- if (resources.isStarted()) {
- resources.stop();
- }
-
- // Close the HTTP client
- httpClient.close();
- }
-
- @Override
- public void destroy() {
-
- // Stop the client if started. This will also remove the client from the client manager
- if (started) {
- stop();
- }
-
- // Delete the storage associated with the client
- AndroidStorage storage = (AndroidStorage) resources.getStorage();
- storage.delete();
-
- // Remove any cached instance for this client.
- AndroidInvalidationService.getClientManager().remove(clientKey);
- }
-
- /**
- * Creates a new InvalidationClient instance that the proxy will delegate requests to and listen
- * for events from.
- */
- // Overridden by tests to inject mock clients or for listener interception
-
- InvalidationClient createClient(SystemResources resources, int clientType, byte[] clientName,
- String applicationName, InvalidationListener listener, ClientConfigP config) {
- // We always use C2DM, so set the channel-supports-offline-delivery bit on our config.
- final ClientConfigP.Builder configBuilder;
- if (config == null) {
- configBuilder = InvalidationClientCore.createConfig();
- } else {
- configBuilder = ClientConfigP.newBuilder(config);
- }
- configBuilder.setChannelSupportsOfflineDelivery(true);
- config = configBuilder.build();
- Random random = new Random(resources.getInternalScheduler().getCurrentTimeMs());
- return new InvalidationClientImpl(resources, random, clientType, clientName, config,
- applicationName, listener);
- }
-
-
- /** Stops the underlying TICL instance but does not stop system resources. */
-
- void stopTicl() {
- Preconditions.checkState(started);
- delegate.stop();
- started = false;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidHttpConstants.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidHttpConstants.java
deleted file mode 100644
index 42d63b62399..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidHttpConstants.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android;
-
-/**
- * Defines shared constants values used in the Android Invalidation HTTP interface.
- *
- */
-public class AndroidHttpConstants {
-
- /** The URL of the invalidation channel service */
- public static final String CHANNEL_URL = "https://clients4.google.com/";
-
- /** The MIME content type to use for requests that contain binary protobuf */
- public static final String PROTO_CONTENT_TYPE = "application/x-protobuffer";
-
- /** The relative URL to use to send inbound client requests to the Android frontend */
- public static final String REQUEST_URL = "/invalidation/android/request/";
-
- /** The relative URL to use to send mailbox retrieval requests to the Android frontend */
- public static final String MAILBOX_URL = "/invalidation/android/mailbox/";
-
- /**
- * The name of the query parameter that contains the service name that should be used to
- * validate the authentication token provided with the request.
- */
- public static final String SERVICE_PARAMETER = "service";
-
- /**
- * The name of the header that contains the echoed token. This token is included in all C2DM
- * messages to the client and is echoed back under this header on all client HTTP requests.
- */
- public static final String ECHO_HEADER = "echo-token";
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidInvalidationService.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidInvalidationService.java
deleted file mode 100644
index 4cbb0e0d2d2..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidInvalidationService.java
+++ /dev/null
@@ -1,597 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android;
-
-import com.google.ipc.invalidation.common.DigestFunction;
-import com.google.ipc.invalidation.common.ObjectIdDigestUtils;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.AndroidInvalidationClient;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.external.client.android.service.Request;
-import com.google.ipc.invalidation.external.client.android.service.Response;
-import com.google.ipc.invalidation.external.client.android.service.Response.Status;
-import com.google.ipc.invalidation.external.client.contrib.MultiplexingGcmListener;
-import com.google.ipc.invalidation.external.client.types.AckHandle;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-import com.google.ipc.invalidation.ticl.InvalidationClientCore;
-import com.google.ipc.invalidation.ticl.PersistenceUtils;
-import com.google.ipc.invalidation.util.TypedUtil;
-import com.google.protos.ipc.invalidation.Client.PersistentTiclState;
-
-import android.accounts.Account;
-import android.content.Context;
-import android.content.Intent;
-import android.os.IBinder;
-import android.util.Base64;
-
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicReference;
-
-
-/**
- * The AndroidInvalidationService class provides an Android service implementation that bridges
- * between the {@code InvalidationService} interface and invalidation client service instances
- * executing within the scope of that service. The invalidation service will have an associated
- * {@link AndroidClientManager} that is managing the set of active (in memory) clients associated
- * with the service. It processes requests from invalidation applications (as invocations on
- * the {@code InvalidationService} bound service interface along with GCM registration and
- * activity (from {@link ReceiverService}).
- *
- */
-public class AndroidInvalidationService extends AbstractInvalidationService {
-
- /**
- * Service that handles system GCM messages (with support from the base class). It receives
- * intents for GCM registration, errors and message delivery. It does some basic processing and
- * then forwards the messages to the {@link AndroidInvalidationService} for handling.
- */
- public static class ReceiverService extends MultiplexingGcmListener.AbstractListener {
-
- /**
- * Receiver for broadcasts by the multiplexed GCM service. It forwards them to
- * AndroidMessageReceiverService.
- */
- public static class Receiver extends MultiplexingGcmListener.AbstractListener.Receiver {
- /* This class is public so that it can be instantiated by the Android runtime. */
- @Override
- protected Class<?> getServiceClass() {
- return ReceiverService.class;
- }
- }
-
- public ReceiverService() {
- super("MsgRcvrSvc");
- }
-
- @Override
- public void onRegistered(String registrationId) {
- logger.info("GCM Registration received: %s", registrationId);
-
- // Upon receiving a new updated GCM ID, notify the invalidation service
- Intent serviceIntent =
- AndroidInvalidationService.createRegistrationIntent(this, registrationId);
- startService(serviceIntent);
- }
-
- @Override
- public void onUnregistered(String registrationId) {
- logger.info("GCM unregistered");
- }
-
- @Override
- protected void onMessage(Intent intent) {
- // Extract expected fields and do basic syntactic checks (but no value checking)
- // and forward the result on to the AndroidInvalidationService for processing.
- Intent serviceIntent;
- String clientKey = intent.getStringExtra(AndroidC2DMConstants.CLIENT_KEY_PARAM);
- if (clientKey == null) {
- logger.severe("GCM Intent does not contain client key value: %s", intent);
- return;
- }
- String encodedData = intent.getStringExtra(AndroidC2DMConstants.CONTENT_PARAM);
- String echoToken = intent.getStringExtra(AndroidC2DMConstants.ECHO_PARAM);
- if (encodedData != null) {
- try {
- byte [] rawData = Base64.decode(encodedData, Base64.URL_SAFE);
- serviceIntent = AndroidInvalidationService.createDataIntent(this, clientKey, echoToken,
- rawData);
- } catch (IllegalArgumentException exception) {
- logger.severe("Unable to decode intent data", exception);
- return;
- }
- } else {
- logger.severe("Received mailbox intent: %s", intent);
- return;
- }
- startService(serviceIntent);
- }
-
- @Override
- protected void onDeletedMessages(int total) {
- // This method must be implemented if we start using non-collapsable messages with GCM. For
- // now, there is nothing to do.
- }
- }
-
- /** The last created instance, for testing. */
-
- static AtomicReference<AndroidInvalidationService> lastInstanceForTest =
- new AtomicReference<AndroidInvalidationService>();
-
- /** For tests only, the number of C2DM errors received. */
- static final AtomicInteger numGcmErrorsForTest = new AtomicInteger(0);
-
- /** For tests only, the number of C2DM registration messages received. */
- static final AtomicInteger numGcmRegistrationForTest = new AtomicInteger(0);
-
- /** For tests only, the number of C2DM messages received. */
- static final AtomicInteger numGcmMessagesForTest = new AtomicInteger(0);
-
- /** For tests only, the number of onCreate calls made. */
- static final AtomicInteger numCreateForTest = new AtomicInteger(0);
-
- /** The client manager tracking in-memory client instances */
-
- protected static AndroidClientManager clientManager;
-
- private static final Logger logger = AndroidLogger.forTag("InvService");
-
- /** The HTTP URL of the channel service. */
- private static String channelUrl = AndroidHttpConstants.CHANNEL_URL;
-
- // The AndroidInvalidationService handles a set of internal intents that are used for
- // communication and coordination between the it and the GCM handling service. These
- // are documented here with action and extra names documented with package private
- // visibility since they are not intended for use by external components.
-
- /**
- * Sent when a new GCM registration activity occurs for the service. This can occur the first
- * time the service is run or at any subsequent time if the Android C2DM service decides to issue
- * a new GCM registration ID.
- */
- static final String REGISTRATION_ACTION = "register";
-
- /**
- * The name of the String extra that contains the registration ID for a register intent. If this
- * extra is not present, then it indicates that a C2DM notification regarding unregistration has
- * been received (not expected during normal operation conditions).
- */
- static final String REGISTER_ID = "id";
-
- /**
- * This intent is sent when a GCM message targeting the service is received.
- */
- static final String MESSAGE_ACTION = "message";
-
- /**
- * The name of the String extra that contains the client key for the GCM message.
- */
- static final String MESSAGE_CLIENT_KEY = "clientKey";
-
- /**
- * The name of the byte array extra that contains the encoded event for the GCM message.
- */
- static final String MESSAGE_DATA = "data";
-
- /** The name of the string extra that contains the echo token in the GCM message. */
- static final String MESSAGE_ECHO = "echo-token";
-
- /**
- * This intent is sent when GCM registration has failed irrevocably.
- */
- static final String ERROR_ACTION = "error";
-
- /**
- * The name of the String extra that contains the error message describing the registration
- * failure.
- */
- static final String ERROR_MESSAGE = "message";
-
- /** Returns the client manager for this service */
- static AndroidClientManager getClientManager() {
- return clientManager;
- }
-
- /**
- * Creates a new registration intent that notifies the service of a registration ID change
- */
- static Intent createRegistrationIntent(Context context, String registrationId) {
- Intent intent = new Intent(REGISTRATION_ACTION);
- intent.setClass(context, AndroidInvalidationService.class);
- if (registrationId != null) {
- intent.putExtra(AndroidInvalidationService.REGISTER_ID, registrationId);
- }
- return intent;
- }
-
- /**
- * Creates a new message intent to contains event data to deliver directly to a client.
- */
- static Intent createDataIntent(Context context, String clientKey, String token,
- byte [] data) {
- Intent intent = new Intent(MESSAGE_ACTION);
- intent.setClass(context, AndroidInvalidationService.class);
- intent.putExtra(MESSAGE_CLIENT_KEY, clientKey);
- intent.putExtra(MESSAGE_DATA, data);
- if (token != null) {
- intent.putExtra(MESSAGE_ECHO, token);
- }
- return intent;
- }
-
- /**
- * Creates a new message intent that references event data to retrieve from a mailbox.
- */
- static Intent createMailboxIntent(Context context, String clientKey, String token) {
- Intent intent = new Intent(MESSAGE_ACTION);
- intent.setClass(context, AndroidInvalidationService.class);
- intent.putExtra(MESSAGE_CLIENT_KEY, clientKey);
- if (token != null) {
- intent.putExtra(MESSAGE_ECHO, token);
- }
- return intent;
- }
-
- /**
- * Creates a new error intent that notifies the service of a registration failure.
- */
- static Intent createErrorIntent(Context context, String errorId) {
- Intent intent = new Intent(ERROR_ACTION);
- intent.setClass(context, AndroidInvalidationService.class);
- intent.putExtra(ERROR_MESSAGE, errorId);
- return intent;
- }
-
- /**
- * Overrides the channel URL set in package metadata to enable dynamic port assignment and
- * configuration during testing.
- */
-
- static void setChannelUrlForTest(String url) {
- channelUrl = url;
- }
-
- /**
- * Resets the state of the service to destroy any existing clients
- */
-
- static void reset() {
- if (clientManager != null) {
- clientManager.releaseAll();
- }
- }
-
- /** The function for computing persistence state digests when rewriting them. */
- private final DigestFunction digestFn = new ObjectIdDigestUtils.Sha1DigestFunction();
-
- public AndroidInvalidationService() {
- lastInstanceForTest.set(this);
- }
-
- @Override
- public void onCreate() {
- synchronized (lock) {
- super.onCreate();
-
- // Create the client manager
- if (clientManager == null) {
- clientManager = new AndroidClientManager(this);
- }
- numCreateForTest.incrementAndGet();
- }
- }
-
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- // Process GCM related messages from the ReceiverService. We do not check isCreated here because
- // this is part of the stop/start lifecycle, not bind/unbind.
- synchronized (lock) {
- logger.fine("Received action = %s", intent.getAction());
- if (MESSAGE_ACTION.equals(intent.getAction())) {
- handleMessage(intent);
- } else if (REGISTRATION_ACTION.equals(intent.getAction())) {
- handleRegistration(intent);
- } else if (ERROR_ACTION.equals(intent.getAction())) {
- handleError(intent);
- }
- final int retval = super.onStartCommand(intent, flags, startId);
-
- // Unless we are explicitly being asked to start, stop ourselves. Request.SERVICE_INTENT
- // is the intent used by InvalidationBinder to bind the service, and
- // AndroidInvalidationClientImpl uses the intent returned by InvalidationBinder.getIntent
- // as the argument to its startService call.
- if (!Request.SERVICE_INTENT.getAction().equals(intent.getAction())) {
- stopServiceIfNoClientsRemain(intent.getAction());
- }
- return retval;
- }
- }
-
- @Override
- public void onDestroy() {
- synchronized (lock) {
- reset();
- super.onDestroy();
- }
- }
-
- @Override
- public IBinder onBind(Intent intent) {
- return super.onBind(intent);
- }
-
- @Override
- public boolean onUnbind(Intent intent) {
- synchronized (lock) {
- logger.fine("onUnbind");
- super.onUnbind(intent);
-
- if ((clientManager != null) && (clientManager.getClientCount() > 0)) {
- // This isn't wrong, per se, but it's potentially unusual.
- logger.info(" clients still active in onUnbind");
- }
- stopServiceIfNoClientsRemain("onUnbind");
-
- // We don't care about the onRebind event, which is what the documentation says a "true"
- // return here will get us, but if we return false then we don't get a second onUnbind() event
- // in a bind/unbind/bind/unbind cycle, which we require.
- return true;
- }
- }
-
- // The following protected methods are called holding "lock" by AbstractInvalidationService.
-
- @Override
- protected void create(Request request, Response.Builder response) {
- String clientKey = request.getClientKey();
- int clientType = request.getClientType();
- Account account = request.getAccount();
- String authType = request.getAuthType();
- Intent eventIntent = request.getIntent();
- clientManager.create(clientKey, clientType, account, authType, eventIntent);
- response.setStatus(Status.SUCCESS);
- }
-
- @Override
- protected void resume(Request request, Response.Builder response) {
- String clientKey = request.getClientKey();
- AndroidClientProxy client = clientManager.get(clientKey);
- if (setResponseStatus(client, request, response)) {
- response.setAccount(client.getAccount());
- response.setAuthType(client.getAuthType());
- }
- }
-
- @Override
- protected void start(Request request, Response.Builder response) {
- String clientKey = request.getClientKey();
- AndroidInvalidationClient client = clientManager.get(clientKey);
- if (setResponseStatus(client, request, response)) {
- client.start();
- }
- }
-
- @Override
- protected void stop(Request request, Response.Builder response) {
- String clientKey = request.getClientKey();
- AndroidInvalidationClient client = clientManager.get(clientKey);
- if (setResponseStatus(client, request, response)) {
- client.stop();
- }
- }
-
- @Override
- protected void register(Request request, Response.Builder response) {
- String clientKey = request.getClientKey();
- AndroidInvalidationClient client = clientManager.get(clientKey);
- if (setResponseStatus(client, request, response)) {
- ObjectId objectId = request.getObjectId();
- client.register(objectId);
- }
- }
-
- @Override
- protected void unregister(Request request, Response.Builder response) {
- String clientKey = request.getClientKey();
- AndroidInvalidationClient client = clientManager.get(clientKey);
- if (setResponseStatus(client, request, response)) {
- ObjectId objectId = request.getObjectId();
- client.unregister(objectId);
- }
- }
-
- @Override
- protected void acknowledge(Request request, Response.Builder response) {
- String clientKey = request.getClientKey();
- AckHandle ackHandle = request.getAckHandle();
- AndroidInvalidationClient client = clientManager.get(clientKey);
- if (setResponseStatus(client, request, response)) {
- client.acknowledge(ackHandle);
- }
- }
-
- @Override
- protected void destroy(Request request, Response.Builder response) {
- String clientKey = request.getClientKey();
- AndroidInvalidationClient client = clientManager.get(clientKey);
- if (setResponseStatus(client, request, response)) {
- client.destroy();
- }
- }
-
- /**
- * If {@code client} is {@code null}, sets the {@code response} status to an error. Otherwise,
- * sets the status to {@code success}.
- * @return whether {@code client} was non-{@code null}. *
- */
- private boolean setResponseStatus(AndroidInvalidationClient client, Request request,
- Response.Builder response) {
- if (client == null) {
- response.setError("Client does not exist: " + request);
- response.setStatus(Status.INVALID_CLIENT);
- return false;
- } else {
- response.setStatus(Status.SUCCESS);
- return true;
- }
- }
-
- /** Returns the base URL used to send messages to the outbound network channel */
- String getChannelUrl() {
- synchronized (lock) {
- return channelUrl;
- }
- }
-
- private void handleMessage(Intent intent) {
- numGcmMessagesForTest.incrementAndGet();
- String clientKey = intent.getStringExtra(MESSAGE_CLIENT_KEY);
- AndroidClientProxy proxy = clientManager.get(clientKey);
-
- // Client is unknown or unstarted; we can't deliver the message, but we need to
- // remember that we dropped it if the client is known.
- if ((proxy == null) || !proxy.isStarted()) {
- logger.warning("Dropping GCM message for unknown or unstarted client: %s", clientKey);
- handleGcmMessageForUnstartedClient(proxy);
- return;
- }
-
- // We can deliver the message. Pass the new echo token to the channel.
- String echoToken = intent.getStringExtra(MESSAGE_ECHO);
- logger.fine("Update %s with new echo token: %s", clientKey, echoToken);
- proxy.getChannel().updateEchoToken(echoToken);
-
- byte [] message = intent.getByteArrayExtra(MESSAGE_DATA);
- if (message != null) {
- logger.fine("Deliver to %s message %s", clientKey, message);
- proxy.getChannel().receiveMessage(message);
- } else {
- logger.severe("Got mailbox intent: %s", intent);
- }
- }
-
- /**
- * Handles receipt of a GCM message for a client that was unknown or not started. If the client
- * was unknown, drops the message. If the client was not started, rewrites the client's
- * persistent state to have a last-message-sent-time of 0, ensuring that the client will
- * send a heartbeat to the server when restarted. Since we drop the received GCM message,
- * the client will be disconnected by the invalidation pusher; this heartbeat ensures a
- * timely reconnection.
- */
- private void handleGcmMessageForUnstartedClient(AndroidClientProxy proxy) {
- if (proxy == null) {
- // Unknown client; nothing to do.
- return;
- }
-
- // Client is not started. Open its storage. We are going to use unsafe calls here that
- // bypass the normal storage API. This is safe in this context because we hold a lock
- // that prevents anyone else from starting this client or accessing its storage. We
- // really should not be holding a lock across I/O, but at least this is only local
- // file I/O, and we're only writing a few bytes. Additionally, since we currently only
- // have one Ticl, we should only ever enter this function if we're not being used for
- // anything else.
- final String clientKey = proxy.getClientKey();
- logger.info("Received message for unloaded client; rewriting state file: %s", clientKey);
-
- // This storage must have been loaded, because we got this proxy from the client manager,
- // which always ensures that its entries have that property.
- AndroidStorage storageForClient = proxy.getStorage();
- PersistentTiclState clientState = decodeTiclState(clientKey, storageForClient);
- if (clientState == null) {
- // Logging done in decodeTiclState.
- return;
- }
-
- // Rewrite the last message sent time.
- PersistentTiclState newState = PersistentTiclState.newBuilder(clientState)
- .setLastMessageSendTimeMs(0).build();
-
- // Serialize the new state.
- byte[] newClientState = PersistenceUtils.serializeState(newState, digestFn);
-
- // Write it out.
- storageForClient.getPropertiesUnsafe().put(InvalidationClientCore.CLIENT_TOKEN_KEY,
- newClientState);
- storageForClient.storeUnsafe();
- }
-
- private void handleRegistration(Intent intent) {
- // Notify the client manager of the updated registration ID
- String id = intent.getStringExtra(REGISTER_ID);
- clientManager.informRegistrationIdChanged();
- numGcmRegistrationForTest.incrementAndGet();
- }
-
- private void handleError(Intent intent) {
- logger.severe("Unable to perform GCM registration: %s", intent.getStringExtra(ERROR_MESSAGE));
- numGcmErrorsForTest.incrementAndGet();
- }
-
- /**
- * Stops the service if there are no clients in the client manager.
- * @param debugInfo short string describing why the check was made
- */
- private void stopServiceIfNoClientsRemain(String debugInfo) {
- if ((clientManager == null) || clientManager.areAllClientsStopped()) {
- logger.info("Stopping AndroidInvalidationService since no clients remain: %s", debugInfo);
- stopSelf();
- } else {
- logger.fine("Not stopping service since %s clients remain (%s)",
- clientManager.getClientCount(), debugInfo);
- }
- }
-
- /**
- * Returns the persisted state for the client with key {@code clientKey} in
- * {@code storageForClient}, or {@code null} if no valid state could be found.
- * <p>
- * REQUIRES: {@code storageForClient}.load() has been called successfully.
- */
-
-
- PersistentTiclState decodeTiclState(final String clientKey, AndroidStorage storageForClient) {
- synchronized (lock) {
- // Retrieve the serialized state.
- final Map<String, byte[]> properties = storageForClient.getPropertiesUnsafe();
- byte[] clientStateBytes = TypedUtil.mapGet(properties,
- InvalidationClientCore.CLIENT_TOKEN_KEY);
- if (clientStateBytes == null) {
- logger.warning("No client state found in storage for %s: %s", clientKey,
- properties.keySet());
- return null;
- }
-
- // Deserialize it.
- PersistentTiclState clientState =
- PersistenceUtils.deserializeState(logger, clientStateBytes, digestFn);
- if (clientState == null) {
- logger.warning("Invalid client state found in storage for %s", clientKey);
- return null;
- }
- return clientState;
- }
- }
-
- /**
- * Returns whether the client with {@code clientKey} is loaded in the client manager.
- */
- public static boolean isLoadedForTest(String clientKey) {
- return (getClientManager() != null) && getClientManager().isLoadedForTest(clientKey);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidResourcesFactory.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidResourcesFactory.java
deleted file mode 100644
index 0b2ad30a24c..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidResourcesFactory.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android;
-
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.ipc.invalidation.external.client.SystemResources.NetworkChannel;
-import com.google.ipc.invalidation.external.client.SystemResources.Scheduler;
-import com.google.ipc.invalidation.external.client.SystemResources.Storage;
-import com.google.ipc.invalidation.external.client.SystemResourcesBuilder;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.util.NamedRunnable;
-
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-
-
-/**
- * SystemResources creator for the Android system service.
- *
- */
-public class AndroidResourcesFactory {
-
- /**
- * Implementation of {@link SystemResources.Scheduler} based on {@code ThreadExecutor}.
- *
- */
- private static class ExecutorBasedScheduler implements Scheduler {
-
- private SystemResources systemResources;
-
- /** Scheduler for running and scheduling tasks. */
- private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
-
- /** Thread that belongs to the scheduler. */
- private Thread thread = null;
-
- private final String threadName;
-
- /** Creates a scheduler with thread {@code name} for internal logging, etc. */
- private ExecutorBasedScheduler(final String name) {
- threadName = name;
- }
-
- @Override
- public long getCurrentTimeMs() {
- return System.currentTimeMillis();
- }
-
- @Override
- public void schedule(final int delayMs, final Runnable runnable) {
- // For simplicity, schedule first and then check when the event runs later if the resources
- // have been shut down.
- scheduler.schedule(new NamedRunnable("AndroidScheduler") {
- @Override
- public void run() {
- if (thread != Thread.currentThread()) {
- // Either at initialization or if the thread has been killed or restarted by the
- // Executor service.
- thread = Thread.currentThread();
- thread.setName(threadName);
- }
-
- if (systemResources.isStarted()) {
- runnable.run();
- } else {
- systemResources.getLogger().warning("Not running on internal thread since resources " +
- "not started %s, %s", delayMs, runnable);
- }
- }
- }, delayMs, TimeUnit.MILLISECONDS);
- }
-
- @Override
- public boolean isRunningOnThread() {
- return (thread == null) || (Thread.currentThread() == thread);
- }
-
- @Override
- public void setSystemResources(SystemResources resources) {
- this.systemResources = resources;
- }
- }
-
- //
- // End of nested classes.
- //
-
- /**
- * Constructs a {@link SystemResourcesBuilder} instance using default scheduling, Android-style
- * logging, and storage, and using {@code network} to send and receive messages.
- */
- public static SystemResourcesBuilder createResourcesBuilder(String logPrefix,
- NetworkChannel network, Storage storage) {
- SystemResourcesBuilder builder = new SystemResourcesBuilder(AndroidLogger.forPrefix(logPrefix),
- new ExecutorBasedScheduler("ticl" + logPrefix),
- new ExecutorBasedScheduler("ticl-listener" + logPrefix),
- network, storage);
- builder.setPlatform("Android-" + android.os.Build.VERSION.RELEASE);
- return builder;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidStorage.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidStorage.java
deleted file mode 100644
index 7a320a8d677..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/AndroidStorage.java
+++ /dev/null
@@ -1,331 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.SystemResources.Storage;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.external.client.types.Callback;
-import com.google.ipc.invalidation.external.client.types.SimplePair;
-import com.google.ipc.invalidation.external.client.types.Status;
-import com.google.ipc.invalidation.util.NamedRunnable;
-import com.google.protobuf.ByteString;
-import com.google.protos.ipc.invalidation.AndroidState.ClientMetadata;
-import com.google.protos.ipc.invalidation.AndroidState.ClientProperty;
-import com.google.protos.ipc.invalidation.AndroidState.StoredState;
-import com.google.protos.ipc.invalidation.ClientProtocol.Version;
-
-import android.accounts.Account;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-
-/**
- * Provides the storage and in-memory state model for Android client persistent state. There is
- * one storage instance for each client instance that is responsible for loading, making state
- * available, and storing the persisted state.
- * <b>
- * The class is thread safe <b>after</b> the {@link #create} or {@link #load} method has been
- * called to populate it with initial state.
- *
- */
-public class AndroidStorage implements Storage {
-
- /*
- * The current storage format is based upon a single file containing protocol buffer data. Each
- * client instance will have a separate state file with a name based upon a client-key derived
- * convention. The design could easily be evolved later to leverage a shared SQLite database
- * or other mechanisms without requiring any changes to the public interface.
- */
-
- /** Storage logger */
- private static final Logger logger = AndroidLogger.forTag("InvStorage");
-
- /** The version value that is stored within written state */
- private static final Version CURRENT_VERSION =
- Version.newBuilder().setMajorVersion(1).setMinorVersion(0).build();
-
- /** The name of the subdirectory in the application files store where state files are stored */
- static final String STATE_DIRECTORY = "InvalidationClient";
-
- /** A simple success constant */
- private static final Status SUCCESS = Status.newInstance(Status.Code.SUCCESS, "");
-
- /**
- * Deletes all persisted client state files stored in the state directory and then
- * the directory itself.
- */
- public static void reset(Context context) {
- File stateDir = context.getDir(STATE_DIRECTORY, Context.MODE_PRIVATE);
- for (File stateFile : stateDir.listFiles()) {
- stateFile.delete();
- }
- stateDir.delete();
- }
-
- /** The execution context */
- final Context context;
-
- /** The client key associated with this storage instance */
- final String key;
-
- /** the client metadata associated with the storage instance (or {@code null} if not loaded */
- private ClientMetadata metadata;
-
- /** Stores the client properties for a client */
- private final Map<String, byte []> properties = new ConcurrentHashMap<String, byte[]>();
-
- /** Executor used to schedule background reads and writes on a single shared thread */
-
- final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
-
- /**
- * Creates a new storage object for reading or writing state for the providing client key using
- * the provided execution context.
- */
-
- protected AndroidStorage(Context context, String key) {
- Preconditions.checkNotNull(context, "context");
- Preconditions.checkNotNull(key, "key");
- this.key = key;
- this.context = context;
- }
-
- ClientMetadata getClientMetadata() {
- return metadata;
- }
-
- @Override
- public void deleteKey(final String key, final Callback<Boolean> done) {
- scheduler.execute(new NamedRunnable("AndroidStorage.deleteKey") {
- @Override
- public void run() {
- properties.remove(key);
- store();
- done.accept(true);
- }
- });
- }
-
- @Override
- public void readAllKeys(final Callback<SimplePair<Status, String>> keyCallback) {
- scheduler.execute(new NamedRunnable("AndroidStorage.readAllKeys") {
- @Override
- public void run() {
- for (String key : properties.keySet()) {
- keyCallback.accept(SimplePair.of(SUCCESS, key));
- }
- }
- });
- }
-
- @Override
- public void readKey(final String key, final Callback<SimplePair<Status, byte[]>> done) {
- scheduler.execute(new NamedRunnable("AndroidStorage.readKey") {
- @Override
- public void run() {
- byte [] value = properties.get(key);
- if (value != null) {
- done.accept(SimplePair.of(SUCCESS, value));
- } else {
- Status status =
- Status.newInstance(Status.Code.PERMANENT_FAILURE, "No value in map for " + key);
- done.accept(SimplePair.of(status, (byte []) null));
- }
- }
- });
- }
-
- @Override
- public void writeKey(final String key, final byte[] value, final Callback<Status> done) {
- scheduler.execute(new NamedRunnable("AndroidStorage.writeKey") {
- @Override
- public void run() {
- properties.put(key, value);
- store();
- done.accept(SUCCESS);
- }
- });
- }
-
- @Override
- public void setSystemResources(SystemResources resources) {}
-
- /**
- * Returns the file where client state for this storage instance is stored.
- */
- File getStateFile() {
- File stateDir = context.getDir(STATE_DIRECTORY, Context.MODE_PRIVATE);
- return new File(stateDir, key);
- }
-
- /**
- * Returns the input stream that can be used to read state from the internal file storage for
- * the application.
- */
-
- protected InputStream getStateInputStream() throws FileNotFoundException {
- return new FileInputStream(getStateFile());
- }
-
- /**
- * Returns the output stream that can be used to write state to the internal file storage for
- * the application.
- */
-
- protected OutputStream getStateOutputStream() throws FileNotFoundException {
- return new FileOutputStream(getStateFile());
- }
-
- void create(int clientType, Account account, String authType,
- Intent eventIntent) {
- ComponentName component = eventIntent.getComponent();
- Preconditions.checkNotNull(component, "No component found in event intent");
- metadata = ClientMetadata.newBuilder()
- .setVersion(CURRENT_VERSION)
- .setClientKey(key)
- .setClientType(clientType)
- .setAccountName(account.name)
- .setAccountType(account.type)
- .setAuthType(authType)
- .setListenerPkg(component.getPackageName())
- .setListenerClass(component.getClassName())
- .build();
- store();
- }
-
- /**
- * Attempts to load any persisted client state for the stored client.
- *
- * @returns {@code true} if loaded successfully, false otherwise.
- */
- boolean load() {
- InputStream inputStream = null;
- try {
- // Load the state from internal storage and parse it the protocol
- inputStream = getStateInputStream();
- StoredState fullState = StoredState.parseFrom(inputStream);
- metadata = fullState.getMetadata();
- if (!key.equals(metadata.getClientKey())) {
- logger.severe("Unexpected client key mismatch: %s, %s", key, metadata.getClientKey());
- return false;
- }
- logger.fine("Loaded metadata: %s", metadata);
-
- // Unpack the client properties into a map for easy lookup / iteration / update
- for (ClientProperty clientProperty : fullState.getPropertyList()) {
- logger.fine("Loaded property: %s", clientProperty);
- properties.put(clientProperty.getKey(), clientProperty.getValue().toByteArray());
- }
- logger.fine("Loaded state for %s", key);
- return true;
- } catch (FileNotFoundException e) {
- // No state persisted on disk
- } catch (IOException exception) {
- // Log error regarding client state read and return null
- logger.severe("Error reading client state", exception);
- } finally {
- if (inputStream != null) {
- try {
- inputStream.close();
- } catch (IOException exception) {
- logger.severe("Unable to close state file", exception);
- }
- }
- }
- return false;
- }
-
- /**
- * Deletes all state associated with the storage instance.
- */
- void delete() {
- File stateFile = getStateFile();
- if (stateFile.exists()) {
- stateFile.delete();
- logger.info("Deleted state for %s from %s", key, stateFile.getName());
- }
- }
-
- /**
- * Store the current state into the persistent storage.
- */
- private void store() {
- StoredState.Builder stateBuilder =
- StoredState.newBuilder()
- .mergeMetadata(metadata);
- for (Map.Entry<String, byte []> entry : properties.entrySet()) {
- stateBuilder.addProperty(
- ClientProperty.newBuilder()
- .setKey(entry.getKey())
- .setValue(ByteString.copyFrom(entry.getValue()))
- .build());
- }
- StoredState state = stateBuilder.build();
- OutputStream outputStream = null;
- try {
- outputStream = getStateOutputStream();
- state.writeTo(outputStream);
- logger.info("State written for %s", key);
- } catch (FileNotFoundException exception) {
- // This should not happen when opening to create / replace
- logger.severe("Unable to open state file", exception);
- } catch (IOException exception) {
- logger.severe("Error writing state", exception);
- } finally {
- if (outputStream != null) {
- try {
- outputStream.close();
- } catch (IOException exception) {
- logger.warning("Unable to close state file", exception);
- }
- }
- }
- }
-
- /**
- * Returns the underlying properties map for direct manipulation. This is extremely
- * unsafe since it bypasses the concurrency control. It is intended only for use
- * in {@code AndroidInvalidationService#handleC2dmMessageForUnstartedClient}.
- */
- Map<String, byte[]> getPropertiesUnsafe() {
- return properties;
- }
-
- /**
- * Stores the properties to disk. This is extremely unsafe since it bypasses the
- * concurrency control. It is intended only for use in
- * {@code AndroidInvalidationService#handleC2dmMessageForUnstartedClient}.
- */
- void storeUnsafe() {
- store();
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/BaseC2DMReceiver.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/BaseC2DMReceiver.java
deleted file mode 100644
index 7732cd6fa9a..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/BaseC2DMReceiver.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android.c2dm;
-
-
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-
-import android.app.IntentService;
-import android.content.Context;
-import android.content.Intent;
-
-/**
- * Service base class that receives events for C2DM registrations and messages. Subclasses
- * should override the {@code onYYY} event handler methods to add appropriate logic for
- * registration or message handling.
- */
-public abstract class BaseC2DMReceiver extends IntentService {
- private static final Logger logger = AndroidLogger.forTag("BaseC2DMReceiver");
-
- /**
- * If {@code true} indicates that the wakelock associated with messages should be automatically
- * released after the {onYYY} handler has been called. Otherwise, the subclass is responsible for
- * releasing the lock (if any).
- */
- private final boolean automaticallyReleaseWakelock;
-
- /**
- * Creates a new receiver instance
- *
- * @param name the name for the receiver service. Used only for debug logging.
- * @param automaticallyReleaseWakeLock if {@code true} indicates that the wakelock associated with
- * messages should be automatically released after the {onYYY} handler has been called.
- * Otherwise, the subclass is responsible for releasing the lock (if any).
- */
- protected BaseC2DMReceiver(String name, boolean automaticallyReleaseWakeLock) {
- super(name);
- // Always redeliver if evicted while processing intents.
- setIntentRedelivery(true);
- this.automaticallyReleaseWakelock = automaticallyReleaseWakeLock;
- }
-
- @Override
- protected void onHandleIntent(Intent intent) {
- logger.fine("Handle intent: %s", intent);
- try {
- // Examine the action and raise the appropriate onYYY event
- if (intent.getAction().equals(C2DMessaging.ACTION_MESSAGE)) {
- onMessage(getApplicationContext(), intent);
- } else if (intent.getAction().equals(C2DMessaging.ACTION_REGISTRATION_ERROR)) {
- onRegistrationError(getApplicationContext(),
- intent.getExtras().getString(C2DMessaging.EXTRA_REGISTRATION_ERROR));
- } else if (intent.getAction().equals(C2DMessaging.ACTION_REGISTERED)) {
- onRegistered(getApplicationContext(),
- intent.getExtras().getString(C2DMessaging.EXTRA_REGISTRATION_ID));
- } else if (intent.getAction().equals(C2DMessaging.ACTION_UNREGISTERED)) {
- onUnregistered(getApplicationContext());
- }
- } finally {
- if (automaticallyReleaseWakelock) {
- releaseWakeLock(intent);
- }
- }
- }
-
- /**
- * Called when a cloud message has been received.
- *
- * @param context the context the intent was received in
- * @param intent the received intent
- */
- protected abstract void onMessage(Context context, Intent intent);
-
- /**
- * Called on registration error. Override to provide better error messages.
- *
- * This is called in the context of a Service - no dialog or UI.
- *
- * @param context the context the intent was received in
- * @param errorId the errorId String
- */
- protected abstract void onRegistrationError(Context context, String errorId);
-
- /**
- * Called when a registration token has been received.
- *
- * @param context the context the intent was received in
- * @param registrationId the registration ID received from C2DM
- */
- protected abstract void onRegistered(Context context, String registrationId);
-
- /**
- * Called when the device has been unregistered.
- *
- * @param context the context of the received intent
- */
- protected abstract void onUnregistered(Context context);
-
- /**
- * Releases the WakeLock registered to the current class.
- *
- * The WakeLock is only released if the extra C2DMessaging.EXTRA_RELEASE_WAKELOCK is true.
- *
- * @param intent the intent to check for the flag to release the wakelock
- */
- protected final void releaseWakeLock(Intent intent) {
- if (intent.getBooleanExtra(C2DMessaging.EXTRA_RELEASE_WAKELOCK, false)) {
- WakeLockManager.getInstance(getApplicationContext()).release(getClass());
- }
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMBroadcastReceiver.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMBroadcastReceiver.java
deleted file mode 100644
index c0f5bfd24cd..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMBroadcastReceiver.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android.c2dm;
-
-import android.app.Activity;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-
-/**
- * Helper class to handle BroadcastReceiver behavior. It can only run for a limited amount of time
- * so it starts the real service for longer activities (which then gets the power lock and releases
- * it when it is done).
- *
- * Based on the open source chrometophone project.
- */
-public class C2DMBroadcastReceiver extends BroadcastReceiver {
-
- @Override
- public final void onReceive(Context context, Intent intent) {
- // To keep things in one place, we run everything in the base receiver intent service
- C2DMManager.runIntentInService(context, intent);
- setResult(Activity.RESULT_OK, null /* data */, null /* extra */);
- }
-
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMManager.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMManager.java
deleted file mode 100644
index 8fcd373fdbf..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMManager.java
+++ /dev/null
@@ -1,653 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android.c2dm;
-
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.ticl.android.AndroidC2DMConstants;
-
-import android.app.AlarmManager;
-import android.app.IntentService;
-import android.app.PendingIntent;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.content.pm.ServiceInfo;
-import android.os.AsyncTask;
-
-import java.util.HashSet;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * Class for managing C2DM registration and dispatching of messages to observers.
- *
- * Requires setting the {@link #SENDER_ID_METADATA_FIELD} metadata field with the correct e-mail to
- * be used for the C2DM registration.
- *
- * This is based on the open source chrometophone project.
- */
-public class C2DMManager extends IntentService {
-
- private static final Logger logger = AndroidLogger.forTag("C2DM");
-
- /** Maximum amount of time to wait for manager initialization to complete */
- private static final long MAX_INIT_SECONDS = 30;
-
- /** Timeout after which wakelocks will be automatically released. */
- private static final int WAKELOCK_TIMEOUT_MS = 30 * 1000;
-
- /**
- * The action of intents sent from the android c2dm framework regarding registration
- */
-
- public static final String REGISTRATION_CALLBACK_INTENT =
- "com.google.android.c2dm.intent.REGISTRATION";
-
- /**
- * The action of intents sent from the Android C2DM framework when we are supposed to retry
- * registration.
- */
- private static final String C2DM_RETRY = "com.google.android.c2dm.intent.RETRY";
-
- /**
- * The key in the bundle to use for the sender ID when registering for C2DM.
- *
- * The value of the field itself must be the account that the server-side pushing messages
- * towards the client is using when talking to C2DM.
- */
- private static final String EXTRA_SENDER = "sender";
-
- /**
- * The key in the bundle to use for boilerplate code identifying the client application towards
- * the Android C2DM framework
- */
- private static final String EXTRA_APPLICATION_PENDING_INTENT = "app";
-
- /**
- * The action of intents sent to the Android C2DM framework when we want to register
- */
- private static final String REQUEST_UNREGISTRATION_INTENT =
- "com.google.android.c2dm.intent.UNREGISTER";
-
- /**
- * The action of intents sent to the Android C2DM framework when we want to unregister
- */
- private static final String REQUEST_REGISTRATION_INTENT =
- "com.google.android.c2dm.intent.REGISTER";
-
- /**
- * The package for the Google Services Framework
- */
- private static final String GSF_PACKAGE = "com.google.android.gsf";
-
- /**
- * The action of intents sent from the Android C2DM framework when a message is received.
- */
-
- public static final String C2DM_INTENT = "com.google.android.c2dm.intent.RECEIVE";
-
- /**
- * The key in the bundle to use when we want to read the C2DM registration ID after a successful
- * registration
- */
-
- public static final String EXTRA_REGISTRATION_ID = "registration_id";
-
- /**
- * The key in the bundle to use when we want to see if we were unregistered from C2DM
- */
-
- static final String EXTRA_UNREGISTERED = "unregistered";
-
- /**
- * The key in the bundle to use when we want to see if there was any errors when we tried to
- * register.
- */
-
- static final String EXTRA_ERROR = "error";
-
- /**
- * The android:name we read from the meta-data for the C2DMManager service in the
- * AndroidManifest.xml file when we want to know which sender id we should use when registering
- * towards C2DM
- */
-
- static final String SENDER_ID_METADATA_FIELD = "sender_id";
-
- /**
- * If {@code true}, newly-registered observers will be informed of the current registration id
- * if one is already held. Used in service lifecycle testing to suppress inconvenient
- * events.
- */
- public static final AtomicBoolean disableRegistrationCallbackOnRegisterForTest =
- new AtomicBoolean(false);
-
- /**
- * C2DMMManager is initialized asynchronously because it requires I/O that should not be done on
- * the main thread. This latch will only be changed to zero once this initialization has been
- * completed successfully. No intents should be handled or other work done until the latch
- * reaches the initialized state.
- */
- private final CountDownLatch initLatch = new CountDownLatch(1);
-
- /**
- * The sender ID we have read from the meta-data in AndroidManifest.xml for this service.
- */
- private String senderId;
-
- /**
- * Observers to dispatch messages from C2DM to
- */
- private Set<C2DMObserver> observers;
-
- /**
- * A field which is set to true whenever a C2DM registration is in progress. It is set to false
- * otherwise.
- */
- private boolean registrationInProcess;
-
- /**
- * The context read during onCreate() which is used throughout the lifetime of this service.
- */
- private Context context;
-
- /**
- * A field which is set to true whenever a C2DM unregistration is in progress. It is set to false
- * otherwise.
- */
- private boolean unregistrationInProcess;
-
- /**
- * A reference to our helper service for handling WakeLocks.
- */
- private WakeLockManager wakeLockManager;
-
- /**
- * Called from the broadcast receiver and from any observer wanting to register (observers usually
- * go through calling C2DMessaging.register(...). Will process the received intent, call
- * handleMessage(), onRegistered(), etc. in background threads, with a wake lock, while keeping
- * the service alive.
- *
- * @param context application to run service in
- * @param intent the intent received
- */
-
- static void runIntentInService(Context context, Intent intent) {
- // This is called from C2DMBroadcastReceiver and C2DMessaging, there is no init.
- WakeLockManager.getInstance(context).acquire(C2DMManager.class, WAKELOCK_TIMEOUT_MS);
- intent.setClassName(context, C2DMManager.class.getCanonicalName());
- context.startService(intent);
- }
-
- public C2DMManager() {
- super("C2DMManager");
- // Always redeliver intents if evicted while processing
- setIntentRedelivery(true);
- }
-
- @Override
- public void onCreate() {
- super.onCreate();
- // Use the mock context when testing, otherwise the service application context.
- context = getApplicationContext();
- wakeLockManager = WakeLockManager.getInstance(context);
-
- // Spawn an AsyncTask performing the blocking IO operations.
- new AsyncTask<Void, Void, Void>() {
- @Override
- protected Void doInBackground(Void... unused) {
- // C2DMSettings relies on SharedPreferencesImpl which performs disk access.
- C2DMManager manager = C2DMManager.this;
- manager.observers = C2DMSettings.getObservers(context);
- manager.registrationInProcess = C2DMSettings.isRegistering(context);
- manager.unregistrationInProcess = C2DMSettings.isUnregistering(context);
- return null;
- }
-
- @Override
- protected void onPostExecute(Void unused) {
- logger.fine("Initialized");
- initLatch.countDown();
- }
- }.execute();
-
- senderId = readSenderIdFromMetaData(this);
- if (senderId == null) {
- stopSelf();
- }
- }
-
- @Override
- public final void onHandleIntent(Intent intent) {
- try {
- // OK to block here (if needed) because IntentService guarantees that onHandleIntent will
- // only be called on a background thread.
- logger.fine("Handle intent = %s", intent);
- waitForInitialization();
- if (intent.getAction().equals(REGISTRATION_CALLBACK_INTENT)) {
- handleRegistration(intent);
- } else if (intent.getAction().equals(C2DM_INTENT)) {
- onMessage(intent);
- } else if (intent.getAction().equals(C2DM_RETRY)) {
- register();
- } else if (intent.getAction().equals(C2DMessaging.ACTION_REGISTER)) {
- registerObserver(intent);
- } else if (intent.getAction().equals(C2DMessaging.ACTION_UNREGISTER)) {
- unregisterObserver(intent);
- } else {
- logger.warning("Receieved unknown action: %s", intent.getAction());
- }
- } finally {
- // Release the power lock, so device can get back to sleep.
- // The lock is reference counted by default, so multiple
- // messages are ok, but because sometimes Android reschedules
- // services we need to handle the case that the wakelock should
- // never be underlocked.
- if (wakeLockManager.isHeld(C2DMManager.class)) {
- wakeLockManager.release(C2DMManager.class);
- }
- }
- }
-
- /** Returns true of the C2DMManager is fully initially */
-
- boolean isInitialized() {
- return initLatch.getCount() == 0;
- }
-
- /**
- * Blocks until asynchronous initialization work has been completed.
- */
- private void waitForInitialization() {
- boolean interrupted = false;
- try {
- if (initLatch.await(MAX_INIT_SECONDS, TimeUnit.SECONDS)) {
- return;
- }
- logger.warning("Initialization timeout");
-
- } catch (InterruptedException e) {
- // Unexpected, so to ensure a consistent state wait for initialization to complete and
- // then interrupt so higher level code can handle the interrupt.
- logger.fine("Latch wait interrupted");
- interrupted = true;
- } finally {
- if (interrupted) {
- logger.warning("Initialization interrupted");
- Thread.currentThread().interrupt();
- }
- }
-
- // Either an unexpected interrupt or a timeout occurred during initialization. Set to a default
- // clean state (no registration work in progress, no observers) and proceed.
- observers = new HashSet<C2DMObserver>();
- }
-
- /**
- * Called when a cloud message has been received.
- *
- * @param intent the received intent
- */
- private void onMessage(Intent intent) {
- boolean matched = false;
- for (C2DMObserver observer : observers) {
- if (observer.matches(intent)) {
- Intent outgoingIntent = createOnMessageIntent(
- observer.getObserverClass(), context, intent);
- deliverObserverIntent(observer, outgoingIntent);
- matched = true;
- }
- }
- if (!matched) {
- logger.info("No receivers matched intent: %s", intent);
- }
- }
-
- /**
- * Returns an intent to deliver a C2DM message to {@code observerClass}.
- * @param context Android context to use to create the intent
- * @param intent the C2DM message intent to deliver
- */
-
- public static Intent createOnMessageIntent(Class<?> observerClass,
- Context context, Intent intent) {
- Intent outgoingIntent = new Intent(intent);
- outgoingIntent.setAction(C2DMessaging.ACTION_MESSAGE);
- outgoingIntent.setClass(context, observerClass);
- return outgoingIntent;
- }
-
- /**
- * Called on registration error. Override to provide better error messages.
- *
- * This is called in the context of a Service - no dialog or UI.
- *
- * @param errorId the errorId String
- */
- private void onRegistrationError(String errorId) {
- setRegistrationInProcess(false);
- for (C2DMObserver observer : observers) {
- deliverObserverIntent(observer,
- createOnRegistrationErrorIntent(observer.getObserverClass(),
- context, errorId));
- }
- }
-
- /**
- * Returns an intent to deliver the C2DM error {@code errorId} to {@code observerClass}.
- * @param context Android context to use to create the intent
- */
-
- public static Intent createOnRegistrationErrorIntent(Class<?> observerClass,
- Context context, String errorId) {
- Intent errorIntent = new Intent(context, observerClass);
- errorIntent.setAction(C2DMessaging.ACTION_REGISTRATION_ERROR);
- errorIntent.putExtra(C2DMessaging.EXTRA_REGISTRATION_ERROR, errorId);
- return errorIntent;
- }
-
- /**
- * Called when a registration token has been received.
- *
- * @param registrationId the registration ID received from C2DM
- */
- private void onRegistered(String registrationId) {
- setRegistrationInProcess(false);
- C2DMSettings.setC2DMRegistrationId(context, registrationId);
- try {
- C2DMSettings.setApplicationVersion(context, getCurrentApplicationVersion(this));
- } catch (NameNotFoundException e) {
- logger.severe("Unable to find our own package name when storing application version: %s",
- e.getMessage());
- }
- for (C2DMObserver observer : observers) {
- onRegisteredSingleObserver(registrationId, observer);
- }
- }
-
- /**
- * Informs the given observer about the registration ID
- */
- private void onRegisteredSingleObserver(String registrationId, C2DMObserver observer) {
- if (!disableRegistrationCallbackOnRegisterForTest.get()) {
- deliverObserverIntent(observer,
- createOnRegisteredIntent(observer.getObserverClass(), context, registrationId));
- }
- }
-
- /**
- * Returns an intent to deliver a new C2DM {@code registrationId} to {@code observerClass}.
- * @param context Android context to use to create the intent
- */
-
- public static Intent createOnRegisteredIntent(Class<?> observerClass, Context context,
- String registrationId) {
- Intent outgoingIntent = new Intent(context, observerClass);
- outgoingIntent.setAction(C2DMessaging.ACTION_REGISTERED);
- outgoingIntent.putExtra(C2DMessaging.EXTRA_REGISTRATION_ID, registrationId);
- return outgoingIntent;
- }
-
- /**
- * Called when the device has been unregistered.
- */
- private void onUnregistered() {
- setUnregisteringInProcess(false);
- C2DMSettings.clearC2DMRegistrationId(context);
- for (C2DMObserver observer : observers) {
- onUnregisteredSingleObserver(observer);
- }
- }
-
- /**
- * Informs the given observer that the application is no longer registered to C2DM
- */
- private void onUnregisteredSingleObserver(C2DMObserver observer) {
- Intent outgoingIntent = new Intent(context, observer.getObserverClass());
- outgoingIntent.setAction(C2DMessaging.ACTION_UNREGISTERED);
- deliverObserverIntent(observer, outgoingIntent);
- }
-
- /**
- * Starts the observer service by delivering it the provided intent. If the observer has asked us
- * to get a WakeLock for it, we do that and inform the observer that the WakeLock has been
- * acquired through the flag C2DMessaging.EXTRA_RELEASE_WAKELOCK.
- */
- private void deliverObserverIntent(C2DMObserver observer, Intent intent) {
- if (observer.isHandleWakeLock()) {
- // Set the extra so the observer knows that it needs to release the wake lock
- intent.putExtra(C2DMessaging.EXTRA_RELEASE_WAKELOCK, true);
- wakeLockManager.acquire(observer.getObserverClass(), WAKELOCK_TIMEOUT_MS);
- }
- context.startService(intent);
- }
-
- /**
- * Registers an observer.
- *
- * If this was the first observer we also start registering towards C2DM. If we were already
- * registered, we do a callback to inform about the current C2DM registration ID.
- *
- * <p>We also start a registration if the application version stored does not match the
- * current version number. This leads to any observer registering after an upgrade will trigger
- * a new C2DM registration.
- */
- private void registerObserver(Intent intent) {
- C2DMObserver observer = C2DMObserver.createFromIntent(intent);
- observers.add(observer);
- C2DMSettings.setObservers(context, observers);
- if (C2DMSettings.hasC2DMRegistrationId(context)) {
- onRegisteredSingleObserver(C2DMSettings.getC2DMRegistrationId(context), observer);
- if (!isApplicationVersionCurrent() && !isRegistrationInProcess()) {
- logger.fine("Registering to C2DM since application version is not current.");
- register();
- }
- } else {
- if (!isRegistrationInProcess()) {
- logger.fine("Registering to C2DM since we have no C2DM registration.");
- register();
- }
- }
- }
-
- /**
- * Unregisters an observer.
- *
- * The observer is moved to unregisteringObservers which only gets messages from C2DMManager if
- * we unregister from C2DM completely. If this was the last observer, we also start the process of
- * unregistering from C2DM.
- */
- private void unregisterObserver(Intent intent) {
- C2DMObserver observer = C2DMObserver.createFromIntent(intent);
- if (observers.remove(observer)) {
- C2DMSettings.setObservers(context, observers);
- onUnregisteredSingleObserver(observer);
- }
- if (observers.isEmpty()) {
- // No more observers, need to unregister
- if (!isUnregisteringInProcess()) {
- unregister();
- }
- }
- }
-
- /**
- * Called when the Android C2DM framework sends us a message regarding registration.
- *
- * This method parses the intent from the Android C2DM framework and calls the appropriate
- * methods for when we are registered, unregistered or if there was an error when trying to
- * register.
- */
- private void handleRegistration(Intent intent) {
- String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID);
- String error = intent.getStringExtra(EXTRA_ERROR);
- String removed = intent.getStringExtra(EXTRA_UNREGISTERED);
- logger.fine("Got registration message: registrationId = %s, error = %s, removed = %s",
- registrationId, error, removed);
- if (removed != null) {
- onUnregistered();
- } else if (error != null) {
- handleRegistrationBackoffOnError(error);
- } else {
- handleRegistration(registrationId);
- }
- }
-
- /**
- * Informs observers about a registration error, and schedules a registration retry if the error
- * was transient.
- */
- private void handleRegistrationBackoffOnError(String error) {
- logger.severe("Registration error %s", error);
- onRegistrationError(error);
- if (C2DMessaging.ERR_SERVICE_NOT_AVAILABLE.equals(error)) {
- long backoffTimeMs = C2DMSettings.getBackoff(context);
- createAlarm(backoffTimeMs);
- increaseBackoff(backoffTimeMs);
- }
- }
-
- /**
- * When C2DM registration fails, we call this method to schedule a retry in the future.
- */
- private void createAlarm(long backoffTimeMs) {
- logger.fine("Scheduling registration retry, backoff = %d", backoffTimeMs);
- Intent retryIntent = new Intent(C2DM_RETRY);
- PendingIntent retryPIntent = PendingIntent.getBroadcast(context, 0, retryIntent, 0);
- AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
- am.set(AlarmManager.ELAPSED_REALTIME, backoffTimeMs, retryPIntent);
- }
-
- /**
- * Increases the backoff time for retrying C2DM registration
- */
- private void increaseBackoff(long backoffTimeMs) {
- backoffTimeMs *= 2;
- C2DMSettings.setBackoff(context, backoffTimeMs);
- }
-
- /**
- * When C2DM registration is complete, this method resets the backoff and makes sure all observers
- * are informed
- */
- private void handleRegistration(String registrationId) {
- C2DMSettings.resetBackoff(context);
- onRegistered(registrationId);
- }
-
- private void setRegistrationInProcess(boolean registrationInProcess) {
- C2DMSettings.setRegistering(context, registrationInProcess);
- this.registrationInProcess = registrationInProcess;
- }
-
- private boolean isRegistrationInProcess() {
- return registrationInProcess;
- }
-
- private void setUnregisteringInProcess(boolean unregisteringInProcess) {
- C2DMSettings.setUnregistering(context, unregisteringInProcess);
- this.unregistrationInProcess = unregisteringInProcess;
- }
-
- private boolean isUnregisteringInProcess() {
- return unregistrationInProcess;
- }
-
- /**
- * Initiate c2d messaging registration for the current application
- */
- private void register() {
- Intent registrationIntent = new Intent(REQUEST_REGISTRATION_INTENT);
- registrationIntent.setPackage(GSF_PACKAGE);
- registrationIntent.putExtra(
- EXTRA_APPLICATION_PENDING_INTENT, PendingIntent.getBroadcast(context, 0, new Intent(), 0));
- registrationIntent.putExtra(EXTRA_SENDER, senderId);
- setRegistrationInProcess(true);
- context.startService(registrationIntent);
- }
-
- /**
- * Unregister the application. New messages will be blocked by server.
- */
- private void unregister() {
- Intent regIntent = new Intent(REQUEST_UNREGISTRATION_INTENT);
- regIntent.setPackage(GSF_PACKAGE);
- regIntent.putExtra(
- EXTRA_APPLICATION_PENDING_INTENT, PendingIntent.getBroadcast(context, 0, new Intent(), 0));
- setUnregisteringInProcess(true);
- context.startService(regIntent);
- }
-
- /**
- * Checks if the stored application version is the same as the current application version.
- */
- private boolean isApplicationVersionCurrent() {
- try {
- String currentApplicationVersion = getCurrentApplicationVersion(this);
- if (currentApplicationVersion == null) {
- return false;
- }
- return currentApplicationVersion.equals(C2DMSettings.getApplicationVersion(context));
- } catch (NameNotFoundException e) {
- logger.fine("Unable to find our own package name when reading application version: %s",
- e.getMessage());
- return false;
- }
- }
-
- /**
- * Retrieves the current application version.
- */
-
- public static String getCurrentApplicationVersion(Context context) throws NameNotFoundException {
- PackageInfo packageInfo =
- context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
- return packageInfo.versionName;
- }
-
- /**
- * Reads the meta-data to find the field specified in SENDER_ID_METADATA_FIELD. The value of that
- * field is used when registering towards C2DM. If no value is found,
- * {@link AndroidC2DMConstants#SENDER_ID} is returned.
- */
- static String readSenderIdFromMetaData(Context context) {
- String senderId = AndroidC2DMConstants.SENDER_ID;
- try {
- ServiceInfo serviceInfo = context.getPackageManager().getServiceInfo(
- new ComponentName(context, C2DMManager.class), PackageManager.GET_META_DATA);
- if (serviceInfo.metaData != null) {
- String manifestSenderId = serviceInfo.metaData.getString(SENDER_ID_METADATA_FIELD);
- if (manifestSenderId != null) {
- logger.fine("Using manifest-specified sender-id: %s", manifestSenderId);
- senderId = manifestSenderId;
- } else {
- logger.severe("No meta-data element with the name %s found on the service declaration",
- SENDER_ID_METADATA_FIELD);
- }
- }
- } catch (NameNotFoundException exception) {
- logger.info("Could not find C2DMManager service info in manifest");
- }
- return senderId;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMObserver.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMObserver.java
deleted file mode 100644
index 51c8403aa5d..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMObserver.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android.c2dm;
-
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-
-import android.app.Service;
-import android.content.Intent;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-
-/**
- * Represents a C2DM observer that gets notifications whenever the
- * application receives a C2DM message or something changes regarding C2DM registration status.
- *
- * An observer may have its own unique filter so that not all messages are dispatched to all
- * observers.
- */
-public class C2DMObserver {
-
- /** Logger */
- private static final Logger logger = AndroidLogger.forTag("C2DMObserver");
-
- /** JSON key name for the observer class name string value */
- private static final String KEY_CLASS = "class";
-
- /** JSON key name for the filter field name string value */
- private static final String KEY_FILTER_KEY = "filterKey";
-
- /** JSON key name for the value field string value */
- private static final String KEY_FILTER_VALUE = "filterValue";
-
- /** JSON kye name for the handle wake lock boolean field */
- private static final String KEY_HANDLE_WAKE_LOCK = "handleWakeLock";
-
- /** Service class that handles messages for this observer */
- private final Class<? extends Service> messageService;
-
- /** Select field name (or {@code null} if none) */
- private final String selectKey;
-
- /** Select field value (or {@code null} if none) */
- private final String selectValue;
-
- /** {@code true} if the observer handles the wake lock */
- private final boolean handleWakeLock;
-
- /**
- * Creates a new observer using the state stored within the provided JSON object (normally
- * created by {@link #toJSON()}.
- */
- static C2DMObserver createFromJSON(JSONObject json) {
- try {
- // Extract instance state value from the appropriate JSON fields.
- String canonicalClassString = json.getString(KEY_CLASS);
- Class<? extends Service> clazz =
- Class.forName(canonicalClassString).asSubclass(Service.class);
- String filterKey = json.has(KEY_FILTER_KEY) ? json.getString(KEY_FILTER_KEY) : null;
- String filterValue = json.has(KEY_FILTER_VALUE) ? json.getString(KEY_FILTER_VALUE) : null;
- Boolean handleWakeLock =
- json.has(KEY_HANDLE_WAKE_LOCK) && json.getBoolean(KEY_HANDLE_WAKE_LOCK);
- return new C2DMObserver(clazz, filterKey, filterValue, handleWakeLock);
- } catch (JSONException e) {
- logger.severe("Unable to parse observer. Source: %s", json);
- } catch (ClassNotFoundException e) {
- logger.severe("Unable to parse observer. Class not found. Source: %s", json);
- }
- return null;
- }
-
- /**
- * Creates a new observer from the extra values contained in the provided intent.
- */
- static C2DMObserver createFromIntent(Intent intent) {
- String canonicalClassString = intent.getStringExtra(C2DMessaging.EXTRA_CANONICAL_CLASS);
- try {
- // Extract observer state from the intent built by the C2DM manager.
- Class<? extends Service> clazz =
- Class.forName(canonicalClassString).asSubclass(Service.class);
- String filterKey = intent.getStringExtra(C2DMessaging.EXTRA_FILTER_KEY);
- String filterValue = intent.getStringExtra(C2DMessaging.EXTRA_FILTER_VALUE);
- boolean handleWakeLock = intent.getBooleanExtra(C2DMessaging.EXTRA_HANDLE_WAKELOCK, false);
- return new C2DMObserver(clazz, filterKey, filterValue, handleWakeLock);
- } catch (ClassNotFoundException e) {
- logger.severe("Unable to register observer class %s", canonicalClassString);
- return null;
- }
- }
-
- /**
- * Creates a new observer for the provided service, selection criteria, and wake lock behavior.
- */
-
- C2DMObserver(Class<? extends Service> messageService, String selectKey, String selectValue,
- boolean handleWakeLock) {
- Preconditions.checkNotNull(messageService);
- this.messageService = messageService;
- this.selectKey = selectKey;
- this.selectValue = selectValue;
- this.handleWakeLock = handleWakeLock;
- }
-
- /**
- * Returns the JSON object representation of the observer state.
- */
- JSONObject toJSON() {
- try {
- JSONObject json = new JSONObject();
- json.put(KEY_CLASS, messageService.getCanonicalName());
- json.put(KEY_FILTER_KEY, selectKey);
- json.put(KEY_FILTER_VALUE, selectValue);
- json.put(KEY_HANDLE_WAKE_LOCK, handleWakeLock);
- return json;
- } catch (JSONException e) {
- logger.severe("Unable to create JSON object from observer %s", toString());
- return null;
- }
- }
-
- /**
- * Returns {@code true} if the provided intent matches the selection criteria for this
- * observer.
- */
- boolean matches(Intent intent) {
- if (selectKey == null) {
- return true;
- }
- if (intent.hasExtra(selectKey)) {
- return selectValue == null || selectValue.equals(intent.getStringExtra(selectKey));
- }
- return false;
- }
-
- Class<?> getObserverClass() {
- return messageService;
- }
-
-
- String getFilterKey() {
- return selectKey;
- }
-
-
- String getFilterValue() {
- return selectValue;
- }
-
-
- boolean isHandleWakeLock() {
- return handleWakeLock;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
- C2DMObserver that = (C2DMObserver) o;
- if (!messageService.equals(that.messageService)) {
- return false;
- }
- if (selectKey != null ? !selectKey.equals(that.selectKey) : that.selectKey != null) {
- return false;
- }
- if (selectValue != null ? !selectValue.equals(that.selectValue) : that.selectValue
- != null) {
- return false;
- }
- return handleWakeLock == that.handleWakeLock;
- }
-
- @Override
- public int hashCode() {
- int result = messageService.hashCode();
- result = 31 * result + (selectKey != null ? selectKey.hashCode() : 0);
- result = 31 * result + (selectValue != null ? selectValue.hashCode() : 0);
- result = 31 * result + (handleWakeLock ? 1 : 0);
- return result;
- }
-
- @Override
- public String toString() {
- return "C2DMObserver{" + "mClass=" + messageService + ", mFilterKey='" + selectKey + '\''
- + ", mFilterValue='" + selectValue + '\'' + ", mHandleWakeLock=" + handleWakeLock + '}';
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMSettings.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMSettings.java
deleted file mode 100644
index 481ecaf2bf1..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMSettings.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android.c2dm;
-
-
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-
-import android.content.Context;
-import android.content.SharedPreferences;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * Stores and provides access to private settings used by the C2DM manager.
- */
-public class C2DMSettings {
-
- private static final Logger logger = AndroidLogger.forTag("C2DMSettings");
-
-
- static final String PREFERENCE_PACKAGE = "com.google.android.c2dm.manager";
-
-
- static final String REGISTRATION_ID = "registrationId";
-
- private static final String APPLICATION_VERSION = "applicationVersion";
-
- private static final String BACKOFF = "c2dm_backoff";
-
- private static final long BACKOFF_DEFAULT = 30000;
-
- private static final String OBSERVERS = "observers";
-
- private static final String REGISTERING = "registering";
-
- private static final String UNREGISTERING = "unregistering";
-
- /**
- * Sets the C2DM registration ID.
- */
- static void setC2DMRegistrationId(Context context, String registrationId) {
- storeField(context, REGISTRATION_ID, registrationId);
- }
-
- /**
- * Clears the C2DM registration ID.
- */
- static void clearC2DMRegistrationId(Context context) {
- storeField(context, REGISTRATION_ID, null);
- }
-
- /**
- * Retrieves the C2DM registration ID (or {@code null} if not stored).
- */
- static String getC2DMRegistrationId(Context context) {
- return retrieveField(context, REGISTRATION_ID, null);
- }
-
- /**
- * Returns {@code true} if there is a C2DM registration ID stored.
- */
- static boolean hasC2DMRegistrationId(Context context) {
- return getC2DMRegistrationId(context) != null;
- }
-
- /**
- * Sets the application version.
- */
- static void setApplicationVersion(Context context, String applicationVersion) {
- storeField(context, APPLICATION_VERSION, applicationVersion);
- }
-
- /**
- * Retrieves the application version (or {@code null} if not stored).
- */
- static String getApplicationVersion(Context context) {
- return retrieveField(context, APPLICATION_VERSION, null);
- }
-
- /**
- * Returns the backoff setting.
- */
- static long getBackoff(Context context) {
- return retrieveField(context, BACKOFF, BACKOFF_DEFAULT);
- }
-
- /**
- * Sets the backoff setting.
- * @param context
- * @param backoff
- */
- static void setBackoff(Context context, long backoff) {
- storeField(context, BACKOFF, backoff);
- }
-
- /**
- * Resets the backoff setting to the default value.
- */
- static void resetBackoff(Context context) {
- setBackoff(context, BACKOFF_DEFAULT);
- }
-
- /**
- * Sets the boolean flag indicating C2DM registration is in process.
- */
- static void setRegistering(Context context, boolean registering) {
- storeField(context, REGISTERING, registering);
- }
-
- /**
- * Returns {@code true} if C2DM registration is in process.
- */
- static boolean isRegistering(Context context) {
- return retrieveField(context, REGISTERING, false);
- }
-
- /**
- * Sets the boolean flag indicating C2DM unregistration is in process.
- */
- static void setUnregistering(Context context, boolean registering) {
- storeField(context, UNREGISTERING, registering);
- }
-
- /**
- * Returns the boolean flag indicating C2DM unregistration is in process.
- */
- static boolean isUnregistering(Context context) {
- return retrieveField(context, UNREGISTERING, false);
- }
-
- /**
- * Returns the set of stored observers.
- */
- static Set<C2DMObserver> getObservers(Context context) {
- return createC2DMObserversFromJSON(retrieveField(context, OBSERVERS, null));
- }
-
- /**
- * Sets the set of stored observers.
- */
- static void setObservers(Context context, Set<C2DMObserver> observers) {
- storeField(context, OBSERVERS, createJsonObserversFromC2DMObservers(observers));
- }
-
- private static Set<C2DMObserver> createC2DMObserversFromJSON(String jsonString) {
- // The observer set is stored in a json array of objects that contain the
- // observer json representation produced by C2DMObserver.toJSON. Iterate over
- // this array and recreate observers from the objects.
- Set<C2DMObserver> observers = new HashSet<C2DMObserver>();
- if (jsonString == null) {
- return observers;
- }
- try {
- JSONArray array = new JSONArray(jsonString);
- for (int i = 0; i < array.length(); i++) {
- JSONObject jsonObserver = array.getJSONObject(i);
- C2DMObserver observer = C2DMObserver.createFromJSON(jsonObserver);
- if (observer != null) {
- observers.add(observer);
- }
- }
- } catch (JSONException e) {
- logger.severe("Unable to parse observers. Source: %s", jsonString);
- observers.clear(); // No partial result
- }
- return observers;
- }
-
- private static String createJsonObserversFromC2DMObservers(Set<C2DMObserver> observers) {
- // Stores the observers as an array of json objects in the format produced by
- // C2DMObserver.toJSON
- JSONArray array = new JSONArray();
- for (C2DMObserver observer : observers) {
- JSONObject json = observer.toJSON();
- if (json != null) {
- array.put(json);
- }
- }
- return array.toString();
- }
-
- private static boolean retrieveField(Context context, String field, boolean defaultValue) {
- SharedPreferences preferences = getPreferences(context);
- return preferences.getBoolean(field, defaultValue);
- }
-
- private static void storeField(Context context, String field, boolean value) {
- SharedPreferences preferences = getPreferences(context);
- SharedPreferences.Editor editor = preferences.edit();
- editor.putBoolean(field, value);
- editor.commit();
- }
-
- private static long retrieveField(Context context, String field, long defaultValue) {
- SharedPreferences preferences = getPreferences(context);
- return preferences.getLong(field, defaultValue);
- }
-
- private static void storeField(Context context, String field, long value) {
- SharedPreferences preferences = getPreferences(context);
- SharedPreferences.Editor editor = preferences.edit();
- editor.putLong(field, value);
- editor.commit();
- }
-
- private static String retrieveField(Context context, String field, String defaultValue) {
- SharedPreferences preferences = getPreferences(context);
- return preferences.getString(field, defaultValue);
- }
-
- private static void storeField(Context context, String field, String value) {
- SharedPreferences preferences = getPreferences(context);
- SharedPreferences.Editor editor = preferences.edit();
- editor.putString(field, value);
- editor.commit();
- if (value == null) {
- logger.fine("Cleared field %s", field);
- }
- }
-
- private static SharedPreferences getPreferences(Context context) {
- return context.getSharedPreferences(PREFERENCE_PACKAGE, Context.MODE_PRIVATE);
- }
-
- /** Sets the C2DM registration id to {@code registrationId}. */
- public static void setC2DMRegistrationIdForTest(Context context, String registrationId) {
- setC2DMRegistrationId(context, registrationId);
- }
-
- /** Sets the C2DM application version to {@code version}. */
- public static void setApplicationVersionForTest(Context context, String version) {
- setApplicationVersion(context, version);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMTestUtil.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMTestUtil.java
deleted file mode 100644
index 8ae94287357..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMTestUtil.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android.c2dm;
-
-
-import android.content.Context;
-
-/**
- * Provides utility methods that allow manipulation of underlying C2DM state for testing.
- *
- */
-
-public class C2DMTestUtil {
-
- // Not instantiable
- private C2DMTestUtil() {}
-
- /**
- * Clears the C2DM registration ID for the application from within settings.
- */
- public static void clearRegistrationId(Context context) {
- C2DMSettings.clearC2DMRegistrationId(context);
- }
-
- /**
- * Sets the C2DM registration ID for the application stored within settings.
- */
- public static void setRegistrationId(Context context, String registrationId) {
- C2DMSettings.setC2DMRegistrationId(context, registrationId);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMessaging.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMessaging.java
deleted file mode 100644
index 8fb2eba2492..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/C2DMessaging.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android.c2dm;
-
-import android.app.Service;
-import android.content.Context;
-import android.content.Intent;
-
-
-/**
- * Utilities for device registration.
- *
- * Will keep track of the registration token in a private preference.
- *
- * This is based on the open source chrometophone project.
- */
-public class C2DMessaging {
- static final String ACTION_MESSAGE = "com.google.android.c2dm.manager.intent.MESSAGE";
-
- static final String ACTION_REGISTER = "com.google.android.c2dm.manager.intent.REGISTER";
-
- static final String ACTION_UNREGISTER = "com.google.android.c2dm.manager.intent.UNREGISTER";
-
- static final String ACTION_REGISTERED = "com.google.android.c2dm.manager.intent.REGISTERED";
-
- static final String ACTION_UNREGISTERED = "com.google.android.c2dm.manager.intent.UNREGISTERED";
-
- static final String ACTION_REGISTRATION_ERROR =
- "com.google.android.c2dm.manager.intent.REGISTRATION_ERROR";
-
- static final String EXTRA_REGISTRATION_ID =
- "com.google.android.c2dm.manager.extra.REGISTRATION_ID";
-
- static final String EXTRA_REGISTRATION_ERROR = "com.google.android.c2dm.manager.extra.ERROR";
-
- static final String EXTRA_CANONICAL_CLASS =
- "com.google.android.c2dm.manager.extra.CANONICAL_CLASS";
-
- static final String EXTRA_FILTER_KEY = "com.google.android.c2dm.manager.extra.FILTER_KEY";
-
- static final String EXTRA_FILTER_VALUE = "com.google.android.c2dm.manager.extra.FILTER_VALUE";
-
- static final String EXTRA_HANDLE_WAKELOCK =
- "com.google.android.c2dm.manager.extra.HANDLE_WAKELOCK";
-
- static final String EXTRA_RELEASE_WAKELOCK =
- "com.google.android.c2dm.manager.extra.RELEASE_WAKELOCK";
-
- /**
- * The device can't read the response, or there was a 500/503 from the server that can be retried
- * later. The C2DMManager will automatically use exponential back off and retry.
- */
- public static final String ERR_SERVICE_NOT_AVAILABLE = "SERVICE_NOT_AVAILABLE";
-
- /**
- * There is no Google account on the phone. The application should ask the user to open the
- * account manager and add a Google account. Fix on the device side.
- */
- public static final String ERR_ACCOUNT_MISSING = "ACCOUNT_MISSING";
-
- /**
- * Bad password. The application should ask the user to enter his/her password, and let user retry
- * manually later. Fix on the device side.
- */
- public static final String ERR_AUTHENTICATION_FAILED = "AUTHENTICATION_FAILED";
-
- /**
- * The user has too many applications registered. The application should tell the user to
- * uninstall some other applications, let user retry manually. Fix on the device side.
- */
- public static final String ERR_TOO_MANY_REGISTRATIONS = "TOO_MANY_REGISTRATIONS";
-
- /**
- * Invalid parameters found in C2DM registration or message.
- */
- public static final String ERR_INVALID_PARAMETERS = "INVALID_PARAMETERS";
-
- /**
- * The sender account is not recognized.
- */
- public static final String ERR_INVALID_SENDER = "INVALID_SENDER";
-
- /** Incorrect phone registration with Google. This phone doesn't currently support C2DM. */
- public static final String ERR_PHONE_REGISTRATION_ERROR = "PHONE_REGISTRATION_ERROR";
-
- public static String getSenderId(Context context) {
- return C2DMManager.readSenderIdFromMetaData(context);
- }
-
- /**
- * Returns the current C2DM registration ID for the application or {@code null} if not yet full
- * registered.
- */
- public static String getRegistrationId(Context context) {
- return C2DMSettings.getC2DMRegistrationId(context);
- }
-
- /**
- * Registers a new C2DM observer service that will receive registration notifications and
- * delivered messages. Receipt of messages can be made conditional based upon the presence of a
- * particular extra in the c2dm message and optionally the value of that extra.
- *
- * @param context the current application context
- * @param clazz the service that will receive c2dm activity intents
- * @param selectKey the name of an extra that will be present in messages selected for this
- * observer. If {@code null}, all messages are delivered.
- * @param selectValue defines a specific value that must match for the messages selected for this
- * observer. If {@code null}, any value will match.
- * @param handleWakeLock if {@code true} indicates that a wake lock should be acquired from the
- * {@link WakeLockManager} before messages are delivered to the observer and that the
- * observer will be responsible for releasing the lock.
- */
- public static void register(Context context, Class<? extends Service> clazz,
- String selectKey, String selectValue, boolean handleWakeLock) {
-
- Intent intent = new Intent();
- intent.setAction(ACTION_REGISTER);
- intent.putExtra(EXTRA_CANONICAL_CLASS, clazz.getCanonicalName());
- intent.putExtra(EXTRA_FILTER_KEY, selectKey);
- intent.putExtra(EXTRA_FILTER_VALUE, selectValue);
- intent.putExtra(EXTRA_HANDLE_WAKELOCK, handleWakeLock);
- C2DMManager.runIntentInService(context, intent);
- }
-
- /**
- * Unregisters an existing C2DM observer service so it will no longer receive notifications or
- * messages (or than a final unregister notification indicating that the observer has been
- * unregistered.
- *
- * @param context the current application context
- * @param clazz the service that will receive c2dm activity intents
- * @param selectKey the name of an extra that will be present in messages selected for this
- * observer. If {@code null}, all messages are delivered.
- * @param selectValue defines a specific value that must match for the messages selected for this
- * observer. If {@code null}, any value will match.
- * @param handleWakeLock if {@code true} indicates that a wake lock should be acquired from the
- * {@link WakeLockManager} before messages are delivered to the observer and that the
- * observer will be responsible for releasing the lock.
- */
- public static void unregister(Context context, Class<?> clazz, String selectKey,
- String selectValue, boolean handleWakeLock) {
- Intent intent = new Intent();
- intent.setAction(ACTION_UNREGISTER);
- intent.putExtra(EXTRA_CANONICAL_CLASS, clazz.getCanonicalName());
- intent.putExtra(EXTRA_FILTER_KEY, selectKey);
- intent.putExtra(EXTRA_FILTER_VALUE, selectValue);
- intent.putExtra(EXTRA_HANDLE_WAKELOCK, handleWakeLock);
- C2DMManager.runIntentInService(context, intent);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/WakeLockManager.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/WakeLockManager.java
deleted file mode 100644
index afa51ca1fa0..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android/c2dm/WakeLockManager.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android.c2dm;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-
-import android.content.Context;
-import android.os.Build;
-import android.os.PowerManager;
-import android.os.PowerManager.WakeLock;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-/**
- * Singleton that manages wake locks identified by a key. Wake locks are refcounted so if they are
- * acquired multiple times with the same key they will not unlocked until they are released an
- * equivalent number of times.
- */
-public class WakeLockManager {
- /** Logger. */
- private static final Logger logger = AndroidLogger.forTag("WakeLockMgr");
-
- /** Lock over all state. Must be acquired by all non-private methods. */
- private static final Object LOCK = new Object();
-
- /**
- * SDK_INT version taken from android.BUILD.VERSION_CODE.ICE_CREAM_SANDWICH. We cannot reference
- * the field directly because if it is not inlined by the Java compiler, it will not be available
- * in the earlier versions of Android for which the version check in acquire() exists.
- */
- private static final int ICE_CREAM_SANDWICH_VERSION_CODE = 14;
-
- /** Singleton instance. */
- private static WakeLockManager theManager;
-
- /** Wake locks by key. */
- private final Map<Object, PowerManager.WakeLock> wakeLocks =
- new HashMap<Object, PowerManager.WakeLock>();
-
- private final PowerManager powerManager;
-
- private final Context applicationContext;
-
- private WakeLockManager(Context context) {
- powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
- applicationContext = Preconditions.checkNotNull(context);
- }
-
- /** Returns the wake lock manager. */
- public static WakeLockManager getInstance(Context context) {
- Preconditions.checkNotNull(context);
- Preconditions.checkNotNull(context.getApplicationContext());
- synchronized (LOCK) {
- if (theManager == null) {
- theManager = new WakeLockManager(context.getApplicationContext());
- } else {
- Preconditions.checkState(theManager.applicationContext == context.getApplicationContext(),
- "Provided context %s does not match stored context %s",
- context.getApplicationContext(), theManager.applicationContext);
- }
- return theManager;
- }
- }
-
- /**
- * Acquires a wake lock identified by the {@code key} that will be automatically released after at
- * most {@code timeoutMs}.
- */
- public void acquire(Object key, int timeoutMs) {
- synchronized (LOCK) {
- cleanup();
- Preconditions.checkNotNull(key, "Key can not be null");
-
- // Prior to ICS, acquiring a lock with a timeout and then explicitly releasing the lock
- // results in runtime errors. We rely on the invalidation system correctly releasing locks
- // rather than defensively requesting a timeout.
- if (Build.VERSION.SDK_INT >= ICE_CREAM_SANDWICH_VERSION_CODE) {
- log(key, "acquiring with timeout " + timeoutMs);
- getWakeLock(key).acquire(timeoutMs);
- } else {
- log(key, "acquiring");
- getWakeLock(key).acquire();
- }
- }
- }
-
- /**
- * Releases the wake lock identified by the {@code key} if it is currently held.
- */
- public void release(Object key) {
- synchronized (LOCK) {
- cleanup();
- Preconditions.checkNotNull(key, "Key can not be null");
- PowerManager.WakeLock wakelock = getWakeLock(key);
-
- // If the lock is not held (if for instance there is a wake lock timeout), we cannot release
- // again without triggering a RuntimeException.
- if (!wakelock.isHeld()) {
- logger.warning("Over-release of wakelock: %s", key);
- return;
- }
-
- // We held the wake lock recently, so it's likely safe to release it. Between the isHeld()
- // check and the release() call, the wake lock may time out however and we catch the resulting
- // RuntimeException.
- try {
- wakelock.release();
- } catch (RuntimeException exception) {
- logger.warning("Over-release of wakelock: %s, %s", key, exception);
- }
- log(key, "released");
-
- // Now if the lock is not held, that means we were the last holder, so we should remove it
- // from the map.
- if (!wakelock.isHeld()) {
- wakeLocks.remove(key);
- log(key, "freed");
- }
- }
- }
-
- /**
- * Returns whether there is currently a wake lock held for the provided {@code key}.
- */
- public boolean isHeld(Object key) {
- synchronized (LOCK) {
- cleanup();
- Preconditions.checkNotNull(key, "Key can not be null");
- if (!wakeLocks.containsKey(key)) {
- return false;
- }
- return getWakeLock(key).isHeld();
- }
- }
-
- /** Returns whether the manager has any active (held) wake locks. */
-
- public boolean hasWakeLocks() {
- synchronized (LOCK) {
- cleanup();
- return !wakeLocks.isEmpty();
- }
- }
-
- /** Discards (without releasing) all wake locks. */
-
- public void resetForTest() {
- synchronized (LOCK) {
- cleanup();
- wakeLocks.clear();
- }
- }
-
- /**
- * Returns a wake lock to use for {@code key}. If a lock is already present in the map,
- * returns that lock. Else, creates a new lock, installs it in the map, and returns it.
- * <p>
- * REQUIRES: caller must hold {@link #LOCK}.
- */
- private PowerManager.WakeLock getWakeLock(Object key) {
- if (key == null) {
- throw new IllegalArgumentException("Key can not be null");
- }
- PowerManager.WakeLock wakeLock = wakeLocks.get(key);
- if (wakeLock == null) {
- wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, key.toString());
- wakeLocks.put(key, wakeLock);
- }
- return wakeLock;
- }
-
- /**
- * Removes any non-held wake locks from {@link #wakeLocks}. Such locks may be present when a
- * wake lock acquired with a timeout is not released before the timeout expires. We only
- * explicitly remove wake locks from the map when {@link #release} is called, so a timeout results
- * in a non-held wake lock in the map.
- * <p>
- * Must be called as the first line of all non-private methods.
- * <p>
- * REQUIRES: caller must hold {@link #LOCK}.
- */
- private void cleanup() {
- Iterator<Map.Entry<Object, WakeLock>> wakeLockIter = wakeLocks.entrySet().iterator();
-
- // Check each map entry.
- while (wakeLockIter.hasNext()) {
- Map.Entry<Object, WakeLock> wakeLockEntry = wakeLockIter.next();
- if (!wakeLockEntry.getValue().isHeld()) {
- // Warn and remove the entry from the map if the lock is not held.
- logger.warning("Found un-held wakelock '%s' -- timed-out?", wakeLockEntry.getKey());
- wakeLockIter.remove();
- }
- }
- }
-
- /** Logs a debug message that {@code action} has occurred for {@code key}. */
- private static void log(Object key, String action) {
- logger.fine("WakeLock %s for key: {%s}", action, key);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidClock.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidClock.java
deleted file mode 100644
index 21deb67878f..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidClock.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2;
-
-
-/**
- * Interface for the Android Ticl that provides a source of time.
- *
- */
-public interface AndroidClock {
- /**
- * Implementation of {@code AndroidClock} that uses {@link System#currentTimeMillis()}.
- */
- static class SystemClock implements AndroidClock {
- @Override
- public long nowMs() {
- return System.currentTimeMillis();
- }
- }
-
- /** Returns milliseconds elapsed since the Unix epoch. */
- long nowMs();
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidIntentProtocolValidator.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidIntentProtocolValidator.java
deleted file mode 100644
index b12f40638ad..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidIntentProtocolValidator.java
+++ /dev/null
@@ -1,306 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2;
-
-import com.google.ipc.invalidation.common.ClientProtocolAccessor;
-import com.google.ipc.invalidation.common.ClientProtocolAccessor.VersionAccessor;
-import com.google.ipc.invalidation.common.ProtoValidator;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.ticl.android2.AndroidServiceAccessor.AndroidNetworkSendRequestAccessor;
-import com.google.ipc.invalidation.ticl.android2.AndroidServiceAccessor.AndroidTiclStateAccessor;
-import com.google.ipc.invalidation.ticl.android2.AndroidServiceAccessor.AndroidTiclStateAccessor.MetadataAccessor;
-import com.google.ipc.invalidation.ticl.android2.AndroidServiceAccessor.AndroidTiclStateWithDigestAccessor;
-import com.google.ipc.invalidation.ticl.android2.AndroidServiceAccessor.ClientDowncallAccessor;
-import com.google.ipc.invalidation.ticl.android2.AndroidServiceAccessor.InternalDowncallAccessor;
-import com.google.ipc.invalidation.ticl.android2.AndroidServiceAccessor.ListenerUpcallAccessor;
-import com.google.protobuf.MessageLite;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidNetworkSendRequest;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidSchedulerEvent;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidTiclStateWithDigest;
-import com.google.protos.ipc.invalidation.AndroidService.ClientDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.InternalDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall;
-import com.google.protos.ipc.invalidation.ClientProtocol.Version;
-
-/**
- * Validator for Android internal protocol intents and messages.
- * <p>
- * This class works by defining instances of {@code MessageInfo} for each protocol buffer
- * that requires validation. A {@code MessageInfo} takes two parameters: an <i>accessor</i>
- * that allows it to read the fields of an instance of the message to be validated, and a list
- * of {@code FieldInfo} objects that, for each field in the message, specify whether the field
- * is required or optional. Additionally, a {@code FieldInfo} may have a reference to a
- * {@code MessageInfo} object that specifies how to recursively validate the field.
- * <p>
- * For example, the validation for the {@code ACK} downcall protocol buffer is specified as follows:
- * <code>
- * static final MessageInfo ACK = new MessageInfo(
- * ClientDowncallAccessor.ACK_DOWNCALL_ACCESSOR,
- * FieldInfo.newRequired(ClientDowncallAccessor.AckDowncallAccessor.ACK_HANDLE));
- * </code>
- * This specifies that the {@code ACK_DOWNCALL_ACCESSOR} is to be used to read the fields of
- * protocol buffers to be validated, and that instances of those protocol buffers should have
- * exactly one field (ack handle) set.
- * <p>
- * For a more complicated example, the {{@link DowncallMessageInfos#REGISTRATIONS} validator
- * requires one or the other (but not both) of two fields to be set, and those fields are
- * recursively validated.
- *
- */
-public final class AndroidIntentProtocolValidator extends ProtoValidator {
- /** Validation for composite (major/minor) versions. */
- static final MessageInfo VERSION = new MessageInfo(ClientProtocolAccessor.VERSION_ACCESSOR,
- FieldInfo.newRequired(VersionAccessor.MAJOR_VERSION),
- FieldInfo.newRequired(VersionAccessor.MINOR_VERSION)) {
- @Override
- public boolean postValidate(MessageLite message) {
- // Versions must be non-negative.
- Version version = (Version) message;
- if ((version.getMajorVersion() < 0) || (version.getMinorVersion() < 0)) {
- return false;
- }
- return true;
- }
- };
-
- /** Validation for public client downcalls. */
- static class DowncallMessageInfos {
- static final MessageInfo ACK = new MessageInfo(
- ClientDowncallAccessor.ACK_DOWNCALL_ACCESSOR,
- FieldInfo.newRequired(ClientDowncallAccessor.AckDowncallAccessor.ACK_HANDLE));
-
- static final MessageInfo REGISTRATIONS = new MessageInfo(
- ClientDowncallAccessor.REGISTRATION_DOWNCALL_ACCESSOR,
- FieldInfo.newOptional(ClientDowncallAccessor.RegistrationDowncallAccessor.REGISTRATIONS),
- FieldInfo.newOptional(
- ClientDowncallAccessor.RegistrationDowncallAccessor.UNREGISTRATIONS)) {
- @Override
- public boolean postValidate(MessageLite message) {
- int numSetFields = 0;
- for (FieldInfo fieldInfo : getAllFields()) {
- if (ClientDowncallAccessor.REGISTRATION_DOWNCALL_ACCESSOR.hasField(
- message, fieldInfo.getFieldDescriptor())) {
- ++numSetFields;
- }
- }
- return numSetFields == 1; // Registrations or unregistrations, but not both.
- }
- };
-
- static final MessageInfo DOWNCALL_MSG = new MessageInfo(
- AndroidServiceAccessor.CLIENT_DOWNCALL_ACCESSOR,
- FieldInfo.newRequired(AndroidServiceAccessor.ClientDowncallAccessor.VERSION, VERSION),
- FieldInfo.newOptional(AndroidServiceAccessor.ClientDowncallAccessor.SERIAL),
- FieldInfo.newOptional(AndroidServiceAccessor.ClientDowncallAccessor.ACK, ACK),
- FieldInfo.newOptional(
- AndroidServiceAccessor.ClientDowncallAccessor.REGISTRATIONS, REGISTRATIONS),
- FieldInfo.newOptional(AndroidServiceAccessor.ClientDowncallAccessor.START),
- FieldInfo.newOptional(AndroidServiceAccessor.ClientDowncallAccessor.STOP)) {
- @Override
- public boolean postValidate(MessageLite message) {
- int numSetFields = 0;
- for (FieldInfo fieldInfo : getAllFields()) {
- if (AndroidServiceAccessor.CLIENT_DOWNCALL_ACCESSOR.hasField(
- message, fieldInfo.getFieldDescriptor())) {
- ++numSetFields;
- }
- }
- return numSetFields == 2; // Version plus exactly one operation. Serial not currently used.
- }
- };
- }
-
- /** Validation for client internal downcalls. */
- static class InternalDowncallInfos {
- private static MessageInfo NETWORK_STATUS = new MessageInfo(
- InternalDowncallAccessor.NETWORK_STATUS_ACCESSOR,
- FieldInfo.newRequired(InternalDowncallAccessor.NetworkStatusAccessor.IS_ONLINE));
-
- private static MessageInfo SERVER_MESSAGE = new MessageInfo(
- InternalDowncallAccessor.SERVER_MESSAGE_ACCESSOR,
- FieldInfo.newRequired(InternalDowncallAccessor.ServerMessageAccessor.DATA));
-
- // We do not post-validate the config in this message, since the Ticl should be doing it, and
- // it's not clear that we should be peering into Ticl protocol buffers anyway.
- private static MessageInfo CREATE_CLIENT_MESSAGE = new MessageInfo(
- InternalDowncallAccessor.CREATE_CLIENT_ACCESSOR,
- FieldInfo.newRequired(InternalDowncallAccessor.CreateClientAccessor.CLIENT_CONFIG),
- FieldInfo.newRequired(InternalDowncallAccessor.CreateClientAccessor.CLIENT_NAME),
- FieldInfo.newRequired(InternalDowncallAccessor.CreateClientAccessor.CLIENT_TYPE),
- FieldInfo.newRequired(InternalDowncallAccessor.CreateClientAccessor.SKIP_START_FOR_TEST));
-
- static final MessageInfo INTERNAL_DOWNCALL_MSG = new MessageInfo(
- AndroidServiceAccessor.INTERNAL_DOWNCALL_ACCESSOR,
- FieldInfo.newRequired(InternalDowncallAccessor.VERSION, VERSION),
- FieldInfo.newOptional(InternalDowncallAccessor.NETWORK_STATUS, NETWORK_STATUS),
- FieldInfo.newOptional(InternalDowncallAccessor.SERVER_MESSAGE, SERVER_MESSAGE),
- FieldInfo.newOptional(InternalDowncallAccessor.NETWORK_ADDR_CHANGE),
- FieldInfo.newOptional(InternalDowncallAccessor.CREATE_CLIENT, CREATE_CLIENT_MESSAGE)) {
- @Override
- public boolean postValidate(MessageLite message) {
- int numSetFields = 0;
- for (FieldInfo fieldInfo : getAllFields()) {
- if (AndroidServiceAccessor.INTERNAL_DOWNCALL_ACCESSOR.hasField(
- message, fieldInfo.getFieldDescriptor())) {
- ++numSetFields;
- }
- }
- return numSetFields == 2; // Version plus exactly one operation. Serial not currently used.
- }
- };
- }
-
- /** Validation for listener upcalls. */
- static class ListenerUpcallInfos {
- static final MessageInfo ERROR = new MessageInfo(ListenerUpcallAccessor.ERROR_UPCALL_ACCESSOR,
- FieldInfo.newRequired(ListenerUpcallAccessor.ErrorUpcallAccessor.ERROR_CODE),
- FieldInfo.newRequired(ListenerUpcallAccessor.ErrorUpcallAccessor.ERROR_MESSAGE),
- FieldInfo.newRequired(ListenerUpcallAccessor.ErrorUpcallAccessor.IS_TRANSIENT));
-
- // TODO: validate INVALIDATE_UNKNOWN and INVALIDATION sub-messages.
- static final MessageInfo INVALIDATE = new MessageInfo(
- ListenerUpcallAccessor.INVALIDATE_UPCALL_ACCESSOR,
- FieldInfo.newRequired(ListenerUpcallAccessor.InvalidateUpcallAccessor.ACK_HANDLE),
- FieldInfo.newOptional(ListenerUpcallAccessor.InvalidateUpcallAccessor.INVALIDATE_ALL),
- FieldInfo.newOptional(ListenerUpcallAccessor.InvalidateUpcallAccessor.INVALIDATE_UNKNOWN),
- FieldInfo.newOptional(ListenerUpcallAccessor.InvalidateUpcallAccessor.INVALIDATION)) {
- @Override
- public boolean postValidate(MessageLite message) {
- int numSetFields = 0;
- for (FieldInfo fieldInfo : getAllFields()) {
- if (ListenerUpcallAccessor.INVALIDATE_UPCALL_ACCESSOR.hasField(
- message, fieldInfo.getFieldDescriptor())) {
- ++numSetFields;
- }
- }
- return numSetFields == 2; // Handle plus exactly one operation. Serial not currently used.
- }
- };
-
- static final MessageInfo REGISTRATION_FAILURE = new MessageInfo(
- ListenerUpcallAccessor.REGISTRATION_FAILURE_UPCALL_ACCESSOR,
- FieldInfo.newRequired(ListenerUpcallAccessor.RegistrationFailureUpcallAccessor.MESSAGE),
- FieldInfo.newRequired(ListenerUpcallAccessor.RegistrationFailureUpcallAccessor.OBJECT_ID),
- FieldInfo.newRequired(ListenerUpcallAccessor.RegistrationFailureUpcallAccessor.TRANSIENT));
-
- static final MessageInfo REGISTRATION_STATUS = new MessageInfo(
- ListenerUpcallAccessor.REGISTRATION_STATUS_UPCALL_ACCESSOR,
- FieldInfo.newRequired(
- ListenerUpcallAccessor.RegistrationStatusUpcallAccessor.IS_REGISTERED),
- FieldInfo.newRequired(ListenerUpcallAccessor.RegistrationStatusUpcallAccessor.OBJECT_ID));
-
- static final MessageInfo REISSUE_REGISTRATIONS = new MessageInfo(
- ListenerUpcallAccessor.REISSUE_REGISTRATIONS_UPCALL_ACCESSOR,
- FieldInfo.newRequired(ListenerUpcallAccessor.ReissueRegistrationsUpcallAccessor.LENGTH),
- FieldInfo.newRequired(ListenerUpcallAccessor.ReissueRegistrationsUpcallAccessor.PREFIX));
-
- static final MessageInfo LISTENER_UPCALL_MESSAGE = new MessageInfo(
- AndroidServiceAccessor.LISTENER_UPCALL_ACCESSOR,
- FieldInfo.newRequired(ListenerUpcallAccessor.VERSION, VERSION),
- FieldInfo.newOptional(ListenerUpcallAccessor.SERIAL),
- FieldInfo.newOptional(ListenerUpcallAccessor.ERROR, ERROR),
- FieldInfo.newOptional(ListenerUpcallAccessor.INVALIDATE, INVALIDATE),
- FieldInfo.newOptional(ListenerUpcallAccessor.READY),
- FieldInfo.newOptional(ListenerUpcallAccessor.REGISTRATION_FAILURE, REGISTRATION_FAILURE),
- FieldInfo.newOptional(ListenerUpcallAccessor.REGISTRATION_STATUS, REGISTRATION_STATUS),
- FieldInfo.newOptional(
- ListenerUpcallAccessor.REISSUE_REGISTRATIONS, REISSUE_REGISTRATIONS)) {
- @Override
- public boolean postValidate(MessageLite message) {
- int numSetFields = 0;
- for (FieldInfo fieldInfo : getAllFields()) {
- if (AndroidServiceAccessor.LISTENER_UPCALL_ACCESSOR.hasField(
- message, fieldInfo.getFieldDescriptor())) {
- ++numSetFields;
- }
- }
- return numSetFields == 2; // Version plus exactly one operation. Serial not currently used.
- }
- };
- }
-
- /** Validation for internal protocol buffers. */
- static class InternalInfos {
- static final MessageInfo ANDROID_SCHEDULER_EVENT = new MessageInfo(
- AndroidServiceAccessor.ANDROID_SCHEDULER_EVENT_ACCESSOR,
- FieldInfo.newRequired(
- AndroidServiceAccessor.AndroidSchedulerEventAccessor.VERSION, VERSION),
- FieldInfo.newRequired(AndroidServiceAccessor.AndroidSchedulerEventAccessor.EVENT_NAME),
- FieldInfo.newRequired(AndroidServiceAccessor.AndroidSchedulerEventAccessor.TICL_ID));
-
- static final MessageInfo ANDROID_NETWORK_SEND_REQUEST = new MessageInfo(
- AndroidServiceAccessor.ANDROID_NETWORK_SEND_REQUEST_ACCESSOR,
- FieldInfo.newRequired(AndroidNetworkSendRequestAccessor.VERSION, VERSION),
- FieldInfo.newRequired(AndroidNetworkSendRequestAccessor.MESSAGE));
-
- // We do not post-validate the config in this message, since the Ticl should be doing it, and
- // it's not clear that we should be peering into Ticl protocol buffers anyway.
- static final MessageInfo PERSISTED_STATE_METADATA = new MessageInfo(
- AndroidTiclStateAccessor.METADATA_ACCESSOR,
- FieldInfo.newRequired(MetadataAccessor.CLIENT_CONFIG),
- FieldInfo.newRequired(MetadataAccessor.CLIENT_NAME),
- FieldInfo.newRequired(MetadataAccessor.CLIENT_TYPE),
- FieldInfo.newRequired(MetadataAccessor.TICL_ID));
-
- static final MessageInfo ANDROID_TICL_STATE = new MessageInfo(
- AndroidServiceAccessor.ANDROID_TICL_STATE_ACCESSOR,
- FieldInfo.newRequired(AndroidTiclStateAccessor.METADATA, PERSISTED_STATE_METADATA),
- FieldInfo.newRequired(AndroidTiclStateAccessor.TICL_STATE),
- FieldInfo.newRequired(AndroidTiclStateAccessor.VERSION));
-
- static final MessageInfo ANDROID_TICL_STATE_WITH_DIGEST = new MessageInfo(
- AndroidServiceAccessor.ANDROID_TICL_STATE_WITH_DIGEST_ACCESSOR,
- FieldInfo.newRequired(AndroidTiclStateWithDigestAccessor.DIGEST),
- FieldInfo.newRequired(AndroidTiclStateWithDigestAccessor.STATE, ANDROID_TICL_STATE));
- }
-
- /** Returns whether {@code downcall} has a valid set of fields with valid values. */
- boolean isDowncallValid(ClientDowncall downcall) {
- return checkMessage(downcall, DowncallMessageInfos.DOWNCALL_MSG);
- }
-
- /** Returns whether {@code downcall} has a valid set of fields with valid values. */
- boolean isInternalDowncallValid(InternalDowncall downcall) {
- return checkMessage(downcall, InternalDowncallInfos.INTERNAL_DOWNCALL_MSG);
- }
-
- /** Returns whether {@code upcall} has a valid set of fields with valid values. */
- boolean isListenerUpcallValid(ListenerUpcall upcall) {
- return checkMessage(upcall, ListenerUpcallInfos.LISTENER_UPCALL_MESSAGE);
- }
-
- /** Returns whether {@code event} has a valid set of fields with valid values. */
- boolean isSchedulerEventValid(AndroidSchedulerEvent event) {
- return checkMessage(event, InternalInfos.ANDROID_SCHEDULER_EVENT);
- }
-
- /** Returns whether {@code request} has a valid set of fields with valid values. */
- public boolean isNetworkSendRequestValid(AndroidNetworkSendRequest request) {
- return checkMessage(request, InternalInfos.ANDROID_NETWORK_SEND_REQUEST);
- }
-
- /**
- * Returns whether {@code state} has a valid set of fields with valid values. Does not
- * verify the digest.
- */
- boolean isTiclStateValid(AndroidTiclStateWithDigest state) {
- return checkMessage(state, InternalInfos.ANDROID_TICL_STATE_WITH_DIGEST);
- }
-
- public AndroidIntentProtocolValidator(Logger logger) {
- super(logger);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInternalScheduler.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInternalScheduler.java
deleted file mode 100644
index 55a8321f82b..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInternalScheduler.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.SystemResources.Scheduler;
-import com.google.ipc.invalidation.ticl.RecurringTask;
-import com.google.ipc.invalidation.util.NamedRunnable;
-import com.google.ipc.invalidation.util.TypedUtil;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidSchedulerEvent;
-
-import android.app.AlarmManager;
-import android.app.PendingIntent;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-
-import java.util.HashMap;
-import java.util.Map;
-
-
-/**
- * Scheduler for controlling access to internal Ticl state in Android.
- * <p>
- * This class maintains a map from recurring task names to the recurring task instances in the
- * associated Ticl. To schedule a recurring task, it uses the {@link AlarmManager} to schedule
- * an intent to itself at the appropriate time in the future. This intent contains the name of
- * the task to run; when it is received, this class looks up the appropriate recurring task
- * instance and runs it.
- * <p>
- * Note that this class only supports scheduling recurring tasks, not ordinary runnables. In
- * order for it to be used, the application must declare the AlarmReceiver of the scheduler
- * in the application's manifest file; see the implementation comment in AlarmReceiver for
- * details.
- *
- */
-public final class AndroidInternalScheduler implements Scheduler {
- /** Class that receives AlarmManager broadcasts and reissues them as intents for this service. */
- public static final class AlarmReceiver extends BroadcastReceiver {
- /*
- * This class needs to be public so that it can be instantiated by the Android runtime.
- * Additionally, it should be declared as a broadcast receiver in the application manifest:
- * <receiver android:name="com.google.ipc.invalidation.ticl.android2.\
- * AndroidInternalScheduler$AlarmReceiver" android:enabled="true"/>
- */
-
- @Override
- public void onReceive(Context context, Intent intent) {
- // Resend the intent to the service so that it's processed on the handler thread and with
- // the automatic shutdown logic provided by IntentService.
- intent.setClassName(context, new AndroidTiclManifest(context).getTiclServiceClass());
- context.startService(intent);
- }
- }
-
- /**
- * If {@code true}, {@link #isRunningOnThread} will verify that calls are being made from either
- * the {@link TiclService} or the {@link TestableTiclService.TestableClient}.
- */
- public static boolean checkStackForTest = false;
-
- /** Class name of the testable client class, for checking call stacks in tests. */
- private static final String TESTABLE_CLIENT_CLASSNAME_FOR_TEST =
- "com.google.ipc.invalidation.ticl.android2.TestableTiclService$TestableClient";
-
- /**
- * {@link RecurringTask}-created runnables that can be executed by this instance, by their names.
- */
- private final Map<String, Runnable> registeredTasks = new HashMap<String, Runnable>();
-
- /** Android system context. */
- private final Context context;
-
- /** Source of time for computing scheduling delays. */
- private final AndroidClock clock;
-
- private Logger logger;
-
- /** Id of the Ticl for which this scheduler will process events. */
- private long ticlId = -1;
-
- AndroidInternalScheduler(Context context, AndroidClock clock) {
- this.context = Preconditions.checkNotNull(context);
- this.clock = Preconditions.checkNotNull(clock);
- }
-
- @Override
- public void setSystemResources(SystemResources resources) {
- this.logger = Preconditions.checkNotNull(resources.getLogger());
- }
-
- @Override
- public void schedule(int delayMs, Runnable runnable) {
- if (!(runnable instanceof NamedRunnable)) {
- throw new RuntimeException("Unsupported: can only schedule named runnables, not " + runnable);
- }
- // Create an intent that will cause the service to run the right recurring task. We explicitly
- // target it to our AlarmReceiver so that no other process in the system can receive it and so
- // that our AlarmReceiver will not be able to receive events from any other broadcaster (which
- // it would be if we used action-based targeting).
- String taskName = ((NamedRunnable) runnable).getName();
- Intent eventIntent = ProtocolIntents.newSchedulerIntent(taskName, ticlId);
- eventIntent.setClass(context, AlarmReceiver.class);
-
- // Create a pending intent that will cause the AlarmManager to fire the above intent.
- PendingIntent sender = PendingIntent.getBroadcast(context,
- (int) (Integer.MAX_VALUE * Math.random()), eventIntent, PendingIntent.FLAG_ONE_SHOT);
-
- // Schedule the pending intent after the appropriate delay.
- AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
- long executeMs = clock.nowMs() + delayMs;
- alarmManager.set(AlarmManager.RTC, executeMs, sender);
- }
-
- /**
- * Handles an event intent created in {@link #schedule} by running the corresponding recurring
- * task.
- * <p>
- * REQUIRES: a recurring task with the name in the intent be present in {@link #registeredTasks}.
- */
- void handleSchedulerEvent(AndroidSchedulerEvent event) {
- Runnable recurringTaskRunnable = Preconditions.checkNotNull(
- TypedUtil.mapGet(registeredTasks, event.getEventName()),
- "No task registered for %s", event.getEventName());
- if (ticlId != event.getTiclId()) {
- logger.warning("Ignoring event with wrong ticl id (not %s): %s", ticlId, event);
- return;
- }
- recurringTaskRunnable.run();
- }
-
- /**
- * Registers {@code task} so that it can be subsequently run by the scheduler.
- * <p>
- * REQUIRES: no recurring task with the same name be already present in {@link #registeredTasks}.
- */
- void registerTask(String name, Runnable runnable) {
- Runnable previous = registeredTasks.put(name, runnable);
- Preconditions.checkState(previous == null,
- "Cannot overwrite task registered on %s, %s; tasks = %s",
- name, this, registeredTasks.keySet());
- }
-
- @Override
- public boolean isRunningOnThread() {
- if (!checkStackForTest) {
- return true;
- }
- // If requested, check that the current stack looks legitimate.
- for (StackTraceElement stackElement : Thread.currentThread().getStackTrace()) {
- if (stackElement.getMethodName().equals("onHandleIntent") &&
- stackElement.getClassName().contains("TiclService")) {
- // Called from the TiclService.
- return true;
- }
- if (stackElement.getClassName().equals(TESTABLE_CLIENT_CLASSNAME_FOR_TEST)) {
- // Called from the TestableClient.
- return true;
- }
- }
- return false;
- }
-
- @Override
- public long getCurrentTimeMs() {
- return clock.nowMs();
- }
-
- /** Removes the registered tasks. */
- void reset() {
- logger.fine("Clearing registered tasks on %s", this);
- registeredTasks.clear();
- }
-
- /**
- * Sets the id of the ticl for which this scheduler will process events. We do not know the
- * Ticl id until done constructing the Ticl, and we need the scheduler to construct a Ticl. This
- * method breaks what would otherwise be a dependency cycle on getting the Ticl id.
- */
- void setTiclId(long ticlId) {
- this.ticlId = ticlId;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInvalidationClientImpl.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInvalidationClientImpl.java
deleted file mode 100644
index e8b3d4b13b4..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInvalidationClientImpl.java
+++ /dev/null
@@ -1,260 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.InvalidationClient;
-import com.google.ipc.invalidation.external.client.InvalidationListener;
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.types.AckHandle;
-import com.google.ipc.invalidation.external.client.types.ErrorInfo;
-import com.google.ipc.invalidation.external.client.types.Invalidation;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-import com.google.ipc.invalidation.ticl.InvalidationClientCore;
-import com.google.ipc.invalidation.ticl.ProtoConverter;
-import com.google.ipc.invalidation.ticl.android2.ProtocolIntents.ListenerUpcalls;
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidTiclState;
-import com.google.protos.ipc.invalidation.Client.AckHandleP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ApplicationClientIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientConfigP;
-
-import android.app.Service;
-import android.content.Context;
-import android.content.Intent;
-
-import java.util.Arrays;
-import java.util.Map;
-import java.util.Random;
-
-
-/**
- * Android specialization of {@link InvalidationClientCore}. Configures the internal scheduler of
- * the provided resources with references to the recurring tasks in the Ticl and also provides
- * an {@link InvalidationListener} instance to the Ticl that will forward upcalls to the
- * actual application listener using {@link Intent}s.
- * <p>
- * This class requires that {@code SystemResources} {@code Storage} implementations be synchronous.
- * I.e., they must invoke their callbacks inline. We require this because it is very difficult
- * to handle asynchrony in an Android {@code IntentService}. Every async point requires marshalling
- * the Ticl state to disk. Additionally, we must be able to resume processing where we left off;
- * i.e., we must be able to (morally) save the value of the program counter. Intents, unlike Java
- * callbacks, do not implicitly save the PC value, so we need to manually encode it in Intent
- * data. This is extremely awkward, so we avoid asynchrony in the storage API.
- *
- */
-class AndroidInvalidationClientImpl extends InvalidationClientCore {
- /** Class implementing the application listener stub (allows overriding default for tests). */
- static Class<? extends Service> listenerServiceClassForTest = null;
-
- /**
- * {@link InvalidationListener} implementation that forwards all calls to a remote listener
- * using Android intents.
- */
- static class IntentForwardingListener implements InvalidationListener {
-
- /** Android system context. */
- private final Context context;
-
- /** Logger from Ticl resources. */
- private final Logger logger;
-
- IntentForwardingListener(Context context, Logger logger) {
- this.context = Preconditions.checkNotNull(context);
- this.logger = Preconditions.checkNotNull(logger);
- }
-
- // All calls are implemented by marshalling the arguments to an Intent and sending the Intent
- // to the application.
-
- @Override
- public void ready(InvalidationClient client) {
- issueIntent(context, ListenerUpcalls.newReadyIntent());
- }
-
- @Override
- public void invalidate(InvalidationClient client, Invalidation invalidation,
- AckHandle ackHandle) {
- try {
- AckHandleP ackHandleP = AckHandleP.parseFrom(ackHandle.getHandleData());
- issueIntent(context, ListenerUpcalls.newInvalidateIntent(
- ProtoConverter.convertToInvalidationProto(invalidation), ackHandleP));
- } catch (InvalidProtocolBufferException exception) {
- // Log and drop invalid call.
- logBadAckHandle("invalidate", ackHandle);
- }
- }
-
- @Override
- public void invalidateUnknownVersion(InvalidationClient client, ObjectId objectId,
- AckHandle ackHandle) {
- try {
- AckHandleP ackHandleP = AckHandleP.parseFrom(ackHandle.getHandleData());
- issueIntent(context, ListenerUpcalls.newInvalidateUnknownIntent(
- ProtoConverter.convertToObjectIdProto(objectId), ackHandleP));
- } catch (InvalidProtocolBufferException exception) {
- // Log and drop invalid call.
- logBadAckHandle("invalidateUnknownVersion", ackHandle);
- }
- }
-
- @Override
- public void invalidateAll(InvalidationClient client, AckHandle ackHandle) {
- try {
- AckHandleP ackHandleP = AckHandleP.parseFrom(ackHandle.getHandleData());
- issueIntent(context, ListenerUpcalls.newInvalidateAllIntent(ackHandleP));
- } catch (InvalidProtocolBufferException exception) {
- // Log and drop invalid call.
- logBadAckHandle("invalidateAll", ackHandle);
- }
- }
-
- @Override
- public void informRegistrationStatus(
- InvalidationClient client, ObjectId objectId, RegistrationState regState) {
- Intent intent = ListenerUpcalls.newRegistrationStatusIntent(
- ProtoConverter.convertToObjectIdProto(objectId),
- regState == RegistrationState.REGISTERED);
- issueIntent(context, intent);
- }
-
- @Override
- public void informRegistrationFailure(InvalidationClient client, ObjectId objectId,
- boolean isTransient, String errorMessage) {
- issueIntent(context, ListenerUpcalls.newRegistrationFailureIntent(
- ProtoConverter.convertToObjectIdProto(objectId), isTransient, errorMessage));
- }
-
- @Override
- public void reissueRegistrations(InvalidationClient client, byte[] prefix, int prefixLength) {
- issueIntent(context, ListenerUpcalls.newReissueRegistrationsIntent(prefix, prefixLength));
- }
-
- @Override
- public void informError(InvalidationClient client, ErrorInfo errorInfo) {
- issueIntent(context, ListenerUpcalls.newErrorIntent(errorInfo));
- }
-
- /**
- * Sends {@code intent} to the real listener via the listener intent service class.
- */
- static void issueIntent(Context context, Intent intent) {
- intent.setClassName(context, (listenerServiceClassForTest != null) ?
- listenerServiceClassForTest.getName() :
- new AndroidTiclManifest(context).getListenerServiceClass());
- context.startService(intent);
- }
-
- /**
- * Logs a warning that a listener upcall to {@code method} has been dropped because
- * {@code unparseableHandle} could not be parsed.
- */
- private void logBadAckHandle(String method, AckHandle unparseableHandle) {
- logger.warning("Dropping call to %s; could not parse ack handle data %s",
- method, Arrays.toString(unparseableHandle.getHandleData()));
- }
- }
-
- /**
- * Unique identifier for this Ticl. This is used to ensure that scheduler intents for other Ticls
- * are not incorrectly delivered to this instance.
- */
- private final long schedulingId;
-
- /**
- * Creates a fresh instance.
- *
- * @param context Android system context
- * @param resources Ticl resources to use
- * @param random random number generator for the Ticl
- * @param clientType type of the Ticl
- * @param clientName unique application name for the Ticl
- * @param config configuration to use
- */
- AndroidInvalidationClientImpl(Context context, SystemResources resources, Random random,
- int clientType, byte[] clientName, ClientConfigP config) {
- super(resources, random, clientType, clientName, config, getApplicationName(context),
- new IntentForwardingListener(context, resources.getLogger()));
- this.schedulingId = resources.getInternalScheduler().getCurrentTimeMs();
- resources.getLogger().fine("Create new Ticl scheduling id: %s", schedulingId);
- initializeSchedulerWithRecurringTasks();
- }
-
- /**
- * Creates an instance with state restored from {@code marshalledState}. Other parameters are as
- * in {@link InvalidationClientCore}.
- */
- AndroidInvalidationClientImpl(Context context, SystemResources resources, Random random,
- AndroidTiclState marshalledState) {
- super(resources,
- random,
- marshalledState.getMetadata().getClientType(),
- marshalledState.getMetadata().getClientName().toByteArray(),
- marshalledState.getMetadata().getClientConfig(),
- getApplicationName(context),
- marshalledState.getTiclState(),
- new IntentForwardingListener(context, resources.getLogger()));
- this.schedulingId = marshalledState.getMetadata().getTiclId();
- initializeSchedulerWithRecurringTasks();
- }
-
- /** Returns the name of the application using the Ticl. */
- private static String getApplicationName(Context context) {
- return context.getPackageName();
- }
-
- /**
- * Provides the internal scheduler with references to each of the recurring tasks that can be
- * executed.
- */
- private void initializeSchedulerWithRecurringTasks() {
- Preconditions.checkState(
- getResources().getInternalScheduler() instanceof AndroidInternalScheduler,
- "Scheduler must be an AndroidInternalScheduler, not %s",
- getResources().getInternalScheduler());
- AndroidInternalScheduler scheduler =
- (AndroidInternalScheduler) getResources().getInternalScheduler();
- for (Map.Entry<String, Runnable> entry : getRecurringTasks().entrySet()) {
- scheduler.registerTask(entry.getKey(), entry.getValue());
- }
- }
-
- /** Returns the scheduling id of this Ticl. */
- long getSchedulingId() {
- return schedulingId;
- }
-
- // This method appears to serve no purpose, since it's just a delegation to the superclass method
- // with the same access level (protected). However, protected also implies package access, so what
- // this is doing is making this method visible to TiclStateManager.
- @Override
- protected ApplicationClientIdP getApplicationClientIdP() {
- return super.getApplicationClientIdP();
- }
-
- // Similar rationale as getApplicationClientIdP.
- @Override
- protected ClientConfigP getConfig() {
- return super.getConfig();
- }
-
- // Similar rationale as getApplicationClientIdP.
- @Override
- protected boolean isStarted() {
- return super.isStarted();
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInvalidationClientStub.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInvalidationClientStub.java
deleted file mode 100644
index b4c05afe263..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInvalidationClientStub.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.InvalidationClient;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.types.AckHandle;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-import com.google.ipc.invalidation.ticl.ProtoConverter;
-import com.google.ipc.invalidation.ticl.android2.ProtocolIntents.ClientDowncalls;
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protos.ipc.invalidation.Client.AckHandleP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ObjectIdP;
-
-import android.content.Context;
-import android.content.Intent;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-
-/**
- * Implementation of {@link InvalidationClient} that uses intents to send commands to an Android
- * service hosting the actual Ticl. This class is a proxy for the Android service.
- *
- */
-class AndroidInvalidationClientStub implements InvalidationClient {
- /** Android system context. */
- private final Context context;
-
- /** Class implementing the Ticl service. */
- private final String serviceClass;
-
- /** logger. */
- private final Logger logger;
-
- /** Creates an instance from {@code context} and {@code logger}. */
- AndroidInvalidationClientStub(Context context, Logger logger) {
- this.context = Preconditions.checkNotNull(context.getApplicationContext());
- this.logger = Preconditions.checkNotNull(logger);
- this.serviceClass = new AndroidTiclManifest(context).getTiclServiceClass();
- }
-
- @Override
- public void start() {
- throw new UnsupportedOperationException(
- "Android clients are automatically started when created");
- }
-
- // All calls work by marshalling the arguments to an Intent and sending the Intent to the Ticl
- // service.
-
- @Override
- public void stop() {
- issueIntent(ClientDowncalls.newStopIntent());
- }
-
- @Override
- public void register(ObjectId objectId) {
- List<ObjectIdP> objects = new ArrayList<ObjectIdP>(1);
- objects.add(ProtoConverter.convertToObjectIdProto(objectId));
- issueIntent(ClientDowncalls.newRegistrationIntent(objects));
- }
-
- @Override
- public void register(Collection<ObjectId> objectIds) {
- List<ObjectIdP> objectIdPs = ProtoConverter.convertToObjectIdProtoList(objectIds);
- issueIntent(ClientDowncalls.newRegistrationIntent(objectIdPs));
- }
-
- @Override
- public void unregister(ObjectId objectId) {
- List<ObjectIdP> objects = new ArrayList<ObjectIdP>(1);
- objects.add(ProtoConverter.convertToObjectIdProto(objectId));
- issueIntent(ClientDowncalls.newUnregistrationIntent(objects));
- }
-
- @Override
- public void unregister(Collection<ObjectId> objectIds) {
- List<ObjectIdP> objectIdPs = ProtoConverter.convertToObjectIdProtoList(objectIds);
- issueIntent(ClientDowncalls.newUnregistrationIntent(objectIdPs));
- }
-
- @Override
- public void acknowledge(AckHandle ackHandle) {
- try {
- AckHandleP ackHandleP = AckHandleP.parseFrom(ackHandle.getHandleData());
- issueIntent(ClientDowncalls.newAcknowledgeIntent(ackHandleP));
- } catch (InvalidProtocolBufferException exception) {
- logger.warning("Dropping acknowledge(); could not parse ack handle data %s",
- Arrays.toString(ackHandle.getHandleData()));
- }
- }
-
- /** Sends {@code intent} to the service implemented by {@link #serviceClass}. */
- private void issueIntent(Intent intent) {
- intent.setClassName(context, serviceClass);
- context.startService(intent);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInvalidationListenerIntentMapper.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInvalidationListenerIntentMapper.java
deleted file mode 100644
index e65a692103c..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInvalidationListenerIntentMapper.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2;
-
-import com.google.ipc.invalidation.external.client.InvalidationClient;
-import com.google.ipc.invalidation.external.client.InvalidationListener;
-import com.google.ipc.invalidation.external.client.InvalidationListener.RegistrationState;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.external.client.types.AckHandle;
-import com.google.ipc.invalidation.external.client.types.ErrorInfo;
-import com.google.ipc.invalidation.ticl.ProtoConverter;
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.ErrorUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.InvalidateUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.RegistrationFailureUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.RegistrationStatusUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.ReissueRegistrationsUpcall;
-
-import android.content.Context;
-import android.content.Intent;
-
-import java.util.Arrays;
-
-
-/**
- * Routes intents to the appropriate methods in {@link InvalidationListener}. Typically, an instance
- * of the mapper should be created in {@code IntentService#onCreate} and the {@link #handleIntent}
- * method called in {@code IntentService#onHandleIntent}.
- *
- */
-public final class AndroidInvalidationListenerIntentMapper {
-
- /** The logger. */
- private final AndroidLogger logger = AndroidLogger.forPrefix("");
-
- private final AndroidIntentProtocolValidator validator =
- new AndroidIntentProtocolValidator(logger);
-
- /** Client passed to the listener (supports downcalls). */
- public final InvalidationClient client;
-
- /** Listener to which intents are routed. */
- private final InvalidationListener listener;
-
- /**
- * Initializes
- *
- * @param listener the listener to which intents should be routed
- * @param context the context used by the listener to issue downcalls to the TICL
- */
- public AndroidInvalidationListenerIntentMapper(InvalidationListener listener, Context context) {
- client = new AndroidInvalidationClientStub(context, logger);
- this.listener = listener;
- }
-
- /**
- * Handles a listener upcall by decoding the protocol buffer in {@code intent} and dispatching
- * to the appropriate method on the {@link #listener}.
- */
- public void handleIntent(Intent intent) {
- // TODO: use wakelocks
-
- // Unmarshall the arguments from the Intent and make the appropriate call on the listener.
- ListenerUpcall upcall = tryParseIntent(intent);
- if (upcall == null) {
- return;
- }
-
- if (upcall.hasReady()) {
- listener.ready(client);
- } else if (upcall.hasInvalidate()) {
- // Handle all invalidation-related upcalls on a common path, since they require creating
- // an AckHandleP.
- onInvalidateUpcall(upcall, listener);
- } else if (upcall.hasRegistrationStatus()) {
- RegistrationStatusUpcall regStatus = upcall.getRegistrationStatus();
- listener.informRegistrationStatus(client,
- ProtoConverter.convertFromObjectIdProto(regStatus.getObjectId()),
- regStatus.getIsRegistered() ?
- RegistrationState.REGISTERED : RegistrationState.UNREGISTERED);
- } else if (upcall.hasRegistrationFailure()) {
- RegistrationFailureUpcall failure = upcall.getRegistrationFailure();
- listener.informRegistrationFailure(client,
- ProtoConverter.convertFromObjectIdProto(failure.getObjectId()),
- failure.getTransient(),
- failure.getMessage());
- } else if (upcall.hasReissueRegistrations()) {
- ReissueRegistrationsUpcall reissueRegs = upcall.getReissueRegistrations();
- listener.reissueRegistrations(client, reissueRegs.getPrefix().toByteArray(),
- reissueRegs.getLength());
- } else if (upcall.hasError()) {
- ErrorUpcall error = upcall.getError();
- ErrorInfo errorInfo = ErrorInfo.newInstance(error.getErrorCode(), error.getIsTransient(),
- error.getErrorMessage(), null);
- listener.informError(client, errorInfo);
- } else {
- logger.warning("Dropping listener Intent with unknown call: %s", upcall);
- }
- }
-
- /**
- * Handles an invalidation-related listener {@code upcall} by dispatching to the appropriate
- * method on an instance of {@link #listenerClass}.
- */
- private void onInvalidateUpcall(ListenerUpcall upcall, InvalidationListener listener) {
- InvalidateUpcall invalidate = upcall.getInvalidate();
- AckHandle ackHandle = AckHandle.newInstance(invalidate.getAckHandle().toByteArray());
- if (invalidate.hasInvalidation()) {
- listener.invalidate(client,
- ProtoConverter.convertFromInvalidationProto(invalidate.getInvalidation()),
- ackHandle);
- } else if (invalidate.hasInvalidateAll()) {
- listener.invalidateAll(client, ackHandle);
- } else if (invalidate.hasInvalidateUnknown()) {
- listener.invalidateUnknownVersion(client,
- ProtoConverter.convertFromObjectIdProto(invalidate.getInvalidateUnknown()), ackHandle);
- } else {
- throw new RuntimeException("Invalid invalidate upcall: " + invalidate);
- }
- }
-
- /**
- * Returns a valid {@link ListenerUpcall} from {@code intent}, or {@code null} if one
- * could not be parsed.
- */
- private ListenerUpcall tryParseIntent(Intent intent) {
- if (intent == null) {
- return null;
- }
- byte[] upcallBytes = intent.getByteArrayExtra(ProtocolIntents.LISTENER_UPCALL_KEY);
- if (upcallBytes == null) {
- return null;
- }
- try {
- ListenerUpcall upcall = ListenerUpcall.parseFrom(upcallBytes);
- if (!validator.isListenerUpcallValid(upcall)) {
- logger.warning("Ignoring invalid listener upcall: %s", upcall);
- return null;
- }
- return upcall;
- } catch (InvalidProtocolBufferException exception) {
- logger.severe("Could not parse listener upcall from %s", Arrays.toString(upcallBytes));
- return null;
- }
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInvalidationListenerStub.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInvalidationListenerStub.java
deleted file mode 100644
index 247309ddf36..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidInvalidationListenerStub.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2;
-
-import com.google.ipc.invalidation.external.client.InvalidationListener;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-
-import android.app.IntentService;
-import android.content.Intent;
-
-
-/**
- * Class implementing the {@link InvalidationListener} in the application using the client.
- * This class is configured with the name of the application class implementing the
- * {@link InvalidationListener} for the application. It receives upcalls from the Ticl as
- * {@link Intent}s and dispatches them against dynamically created instances of the provided
- * class. In this way, it serves as a bridge between the intent protocol and the application.
- */
-public class AndroidInvalidationListenerStub extends IntentService {
- /* This class needs to be public so that the Android runtime can start it as a service. */
-
- private final AndroidLogger logger = AndroidLogger.forPrefix("");
-
- /** The mapper used to route intents to the invalidation listener. */
- private AndroidInvalidationListenerIntentMapper intentMapper;
-
- public AndroidInvalidationListenerStub() {
- super("");
- }
-
- @Override
- public void onCreate() {
- super.onCreate();
- InvalidationListener listener = createListener(getListenerClass());
- intentMapper = new AndroidInvalidationListenerIntentMapper(listener, getApplicationContext());
- }
-
- @SuppressWarnings("unchecked")
- private Class<? extends InvalidationListener> getListenerClass() {
- try {
- // Find the listener class that the application wants to use to receive upcalls.
- return (Class<? extends InvalidationListener>)
- Class.forName(new AndroidTiclManifest(this).getListenerClass());
- } catch (ClassNotFoundException exception) {
- throw new RuntimeException("Invalid listener class", exception);
- }
- }
-
- /**
- * Handles a listener upcall by decoding the protocol buffer in {@code intent} and dispatching
- * to the appropriate method on an instance of {@link #listenerClass}.
- */
- @Override
- public void onHandleIntent(Intent intent) {
- logger.fine("onHandleIntent({0})", AndroidStrings.toLazyCompactString(intent));
- intentMapper.handleIntent(intent);
- }
-
- private InvalidationListener createListener(Class<? extends InvalidationListener> listenerClass) {
- // Create an instance of the application listener class to handle the upcall.
- try {
- return listenerClass.newInstance();
- } catch (InstantiationException exception) {
- throw new RuntimeException("Could not create listener", exception);
- } catch (IllegalAccessException exception) {
- throw new RuntimeException("Could not create listener", exception);
- }
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidManifest.xml b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidManifest.xml
deleted file mode 100644
index 4d665386ee7..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidManifest.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
- <!-- Copyright 2011 Google Inc. All Rights Reserved. -->
- <!-- Test application for Android Client API and implementation. -->
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.google.ipc.invalidation.ticl.android2.tests"
- android:versionName="2.3.0">
- <!--Unit test runner application -->
- <application>
- <uses-library android:name="android.test.runner"/>
- </application>
-
- <instrumentation
- android:name="android.test.InstrumentationTestRunner"
- android:targetPackage="com.google.ipc.invalidation.ticl.android2"/>
- </manifest>
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidServiceAccessor.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidServiceAccessor.java
deleted file mode 100644
index 32111396393..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidServiceAccessor.java
+++ /dev/null
@@ -1,1217 +0,0 @@
-/*
- * Copyright 2011 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.
- */
-// GENERATED CODE. DO NOT EDIT. (But isn't it pretty?)
-package com.google.ipc.invalidation.ticl.android2;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.common.ProtoValidator.Accessor;
-
-import com.google.ipc.invalidation.common.ProtoValidator.Descriptor;
-
-import com.google.protobuf.MessageLite;
-
-import com.google.protos.ipc.invalidation.AndroidService.AndroidNetworkSendRequest;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidSchedulerEvent;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidTiclState;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidTiclState.Metadata;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidTiclStateWithDigest;
-import com.google.protos.ipc.invalidation.AndroidService.ClientDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.ClientDowncall.RegistrationDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.ClientDowncall.AckDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.ClientDowncall.StopDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.ClientDowncall.StartDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.InternalDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.InternalDowncall.CreateClient;
-import com.google.protos.ipc.invalidation.AndroidService.InternalDowncall.NetworkStatus;
-import com.google.protos.ipc.invalidation.AndroidService.InternalDowncall.ServerMessage;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.ErrorUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.ReissueRegistrationsUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.RegistrationFailureUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.RegistrationStatusUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.InvalidateUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.ReadyUpcall;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Set;
-
-/** Class providing access to fields of protocol buffers in a generic way without using Java reflection. */
-public class AndroidServiceAccessor {
- /** Class to access fields in {@link AndroidNetworkSendRequest} protos. */
- public static class AndroidNetworkSendRequestAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "version",
- "message"
- ));
-
- public static final Descriptor VERSION = new Descriptor("version");
- public static final Descriptor MESSAGE = new Descriptor("message");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- AndroidNetworkSendRequest message = (AndroidNetworkSendRequest) rawMessage;
- if (field == VERSION) {
- return message.hasVersion();
- }
- if (field == MESSAGE) {
- return message.hasMessage();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- AndroidNetworkSendRequest message = (AndroidNetworkSendRequest) rawMessage;
- if (field == VERSION) {
- return message.getVersion();
- }
- if (field == MESSAGE) {
- return message.getMessage();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final AndroidNetworkSendRequestAccessor ANDROID_NETWORK_SEND_REQUEST_ACCESSOR = new AndroidNetworkSendRequestAccessor();
-
- /** Class to access fields in {@link AndroidSchedulerEvent} protos. */
- public static class AndroidSchedulerEventAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "version",
- "event_name",
- "ticl_id"
- ));
-
- public static final Descriptor VERSION = new Descriptor("version");
- public static final Descriptor EVENT_NAME = new Descriptor("event_name");
- public static final Descriptor TICL_ID = new Descriptor("ticl_id");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- AndroidSchedulerEvent message = (AndroidSchedulerEvent) rawMessage;
- if (field == VERSION) {
- return message.hasVersion();
- }
- if (field == EVENT_NAME) {
- return message.hasEventName();
- }
- if (field == TICL_ID) {
- return message.hasTiclId();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- AndroidSchedulerEvent message = (AndroidSchedulerEvent) rawMessage;
- if (field == VERSION) {
- return message.getVersion();
- }
- if (field == EVENT_NAME) {
- return message.getEventName();
- }
- if (field == TICL_ID) {
- return message.getTiclId();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final AndroidSchedulerEventAccessor ANDROID_SCHEDULER_EVENT_ACCESSOR = new AndroidSchedulerEventAccessor();
-
- /** Class to access fields in {@link AndroidTiclState} protos. */
- public static class AndroidTiclStateAccessor implements Accessor {
- /** Class to access fields in {@link Metadata} protos. */
- public static class MetadataAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "client_type",
- "client_name",
- "ticl_id",
- "client_config"
- ));
-
- public static final Descriptor CLIENT_TYPE = new Descriptor("client_type");
- public static final Descriptor CLIENT_NAME = new Descriptor("client_name");
- public static final Descriptor TICL_ID = new Descriptor("ticl_id");
- public static final Descriptor CLIENT_CONFIG = new Descriptor("client_config");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- Metadata message = (Metadata) rawMessage;
- if (field == CLIENT_TYPE) {
- return message.hasClientType();
- }
- if (field == CLIENT_NAME) {
- return message.hasClientName();
- }
- if (field == TICL_ID) {
- return message.hasTiclId();
- }
- if (field == CLIENT_CONFIG) {
- return message.hasClientConfig();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- Metadata message = (Metadata) rawMessage;
- if (field == CLIENT_TYPE) {
- return message.getClientType();
- }
- if (field == CLIENT_NAME) {
- return message.getClientName();
- }
- if (field == TICL_ID) {
- return message.getTiclId();
- }
- if (field == CLIENT_CONFIG) {
- return message.getClientConfig();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final MetadataAccessor METADATA_ACCESSOR = new MetadataAccessor();
-
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "version",
- "ticl_state",
- "metadata"
- ));
-
- public static final Descriptor VERSION = new Descriptor("version");
- public static final Descriptor TICL_STATE = new Descriptor("ticl_state");
- public static final Descriptor METADATA = new Descriptor("metadata");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- AndroidTiclState message = (AndroidTiclState) rawMessage;
- if (field == VERSION) {
- return message.hasVersion();
- }
- if (field == TICL_STATE) {
- return message.hasTiclState();
- }
- if (field == METADATA) {
- return message.hasMetadata();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- AndroidTiclState message = (AndroidTiclState) rawMessage;
- if (field == VERSION) {
- return message.getVersion();
- }
- if (field == TICL_STATE) {
- return message.getTiclState();
- }
- if (field == METADATA) {
- return message.getMetadata();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final AndroidTiclStateAccessor ANDROID_TICL_STATE_ACCESSOR = new AndroidTiclStateAccessor();
-
- /** Class to access fields in {@link AndroidTiclStateWithDigest} protos. */
- public static class AndroidTiclStateWithDigestAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "state",
- "digest"
- ));
-
- public static final Descriptor STATE = new Descriptor("state");
- public static final Descriptor DIGEST = new Descriptor("digest");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- AndroidTiclStateWithDigest message = (AndroidTiclStateWithDigest) rawMessage;
- if (field == STATE) {
- return message.hasState();
- }
- if (field == DIGEST) {
- return message.hasDigest();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- AndroidTiclStateWithDigest message = (AndroidTiclStateWithDigest) rawMessage;
- if (field == STATE) {
- return message.getState();
- }
- if (field == DIGEST) {
- return message.getDigest();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final AndroidTiclStateWithDigestAccessor ANDROID_TICL_STATE_WITH_DIGEST_ACCESSOR = new AndroidTiclStateWithDigestAccessor();
-
- /** Class to access fields in {@link ClientDowncall} protos. */
- public static class ClientDowncallAccessor implements Accessor {
- /** Class to access fields in {@link RegistrationDowncall} protos. */
- public static class RegistrationDowncallAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "registrations",
- "unregistrations"
- ));
-
- public static final Descriptor REGISTRATIONS = new Descriptor("registrations");
- public static final Descriptor UNREGISTRATIONS = new Descriptor("unregistrations");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationDowncall message = (RegistrationDowncall) rawMessage;
- if (field == REGISTRATIONS) {
- return message.getRegistrationsCount() > 0;
- }
- if (field == UNREGISTRATIONS) {
- return message.getUnregistrationsCount() > 0;
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationDowncall message = (RegistrationDowncall) rawMessage;
- if (field == REGISTRATIONS) {
- return message.getRegistrationsList();
- }
- if (field == UNREGISTRATIONS) {
- return message.getUnregistrationsList();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final RegistrationDowncallAccessor REGISTRATION_DOWNCALL_ACCESSOR = new RegistrationDowncallAccessor();
-
- /** Class to access fields in {@link AckDowncall} protos. */
- public static class AckDowncallAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "ack_handle"
- ));
-
- public static final Descriptor ACK_HANDLE = new Descriptor("ack_handle");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- AckDowncall message = (AckDowncall) rawMessage;
- if (field == ACK_HANDLE) {
- return message.hasAckHandle();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- AckDowncall message = (AckDowncall) rawMessage;
- if (field == ACK_HANDLE) {
- return message.getAckHandle();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final AckDowncallAccessor ACK_DOWNCALL_ACCESSOR = new AckDowncallAccessor();
-
- /** Class to access fields in {@link StopDowncall} protos. */
- public static class StopDowncallAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- ));
-
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- StopDowncall message = (StopDowncall) rawMessage;
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- StopDowncall message = (StopDowncall) rawMessage;
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final StopDowncallAccessor STOP_DOWNCALL_ACCESSOR = new StopDowncallAccessor();
-
- /** Class to access fields in {@link StartDowncall} protos. */
- public static class StartDowncallAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- ));
-
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- StartDowncall message = (StartDowncall) rawMessage;
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- StartDowncall message = (StartDowncall) rawMessage;
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final StartDowncallAccessor START_DOWNCALL_ACCESSOR = new StartDowncallAccessor();
-
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "serial",
- "version",
- "start",
- "stop",
- "ack",
- "registrations"
- ));
-
- public static final Descriptor SERIAL = new Descriptor("serial");
- public static final Descriptor VERSION = new Descriptor("version");
- public static final Descriptor START = new Descriptor("start");
- public static final Descriptor STOP = new Descriptor("stop");
- public static final Descriptor ACK = new Descriptor("ack");
- public static final Descriptor REGISTRATIONS = new Descriptor("registrations");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ClientDowncall message = (ClientDowncall) rawMessage;
- if (field == SERIAL) {
- return message.hasSerial();
- }
- if (field == VERSION) {
- return message.hasVersion();
- }
- if (field == START) {
- return message.hasStart();
- }
- if (field == STOP) {
- return message.hasStop();
- }
- if (field == ACK) {
- return message.hasAck();
- }
- if (field == REGISTRATIONS) {
- return message.hasRegistrations();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ClientDowncall message = (ClientDowncall) rawMessage;
- if (field == SERIAL) {
- return message.getSerial();
- }
- if (field == VERSION) {
- return message.getVersion();
- }
- if (field == START) {
- return message.getStart();
- }
- if (field == STOP) {
- return message.getStop();
- }
- if (field == ACK) {
- return message.getAck();
- }
- if (field == REGISTRATIONS) {
- return message.getRegistrations();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ClientDowncallAccessor CLIENT_DOWNCALL_ACCESSOR = new ClientDowncallAccessor();
-
- /** Class to access fields in {@link InternalDowncall} protos. */
- public static class InternalDowncallAccessor implements Accessor {
- /** Class to access fields in {@link CreateClient} protos. */
- public static class CreateClientAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "client_type",
- "client_name",
- "client_config",
- "skip_start_for_test"
- ));
-
- public static final Descriptor CLIENT_TYPE = new Descriptor("client_type");
- public static final Descriptor CLIENT_NAME = new Descriptor("client_name");
- public static final Descriptor CLIENT_CONFIG = new Descriptor("client_config");
- public static final Descriptor SKIP_START_FOR_TEST = new Descriptor("skip_start_for_test");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- CreateClient message = (CreateClient) rawMessage;
- if (field == CLIENT_TYPE) {
- return message.hasClientType();
- }
- if (field == CLIENT_NAME) {
- return message.hasClientName();
- }
- if (field == CLIENT_CONFIG) {
- return message.hasClientConfig();
- }
- if (field == SKIP_START_FOR_TEST) {
- return message.hasSkipStartForTest();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- CreateClient message = (CreateClient) rawMessage;
- if (field == CLIENT_TYPE) {
- return message.getClientType();
- }
- if (field == CLIENT_NAME) {
- return message.getClientName();
- }
- if (field == CLIENT_CONFIG) {
- return message.getClientConfig();
- }
- if (field == SKIP_START_FOR_TEST) {
- return message.getSkipStartForTest();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final CreateClientAccessor CREATE_CLIENT_ACCESSOR = new CreateClientAccessor();
-
- /** Class to access fields in {@link NetworkStatus} protos. */
- public static class NetworkStatusAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "is_online"
- ));
-
- public static final Descriptor IS_ONLINE = new Descriptor("is_online");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- NetworkStatus message = (NetworkStatus) rawMessage;
- if (field == IS_ONLINE) {
- return message.hasIsOnline();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- NetworkStatus message = (NetworkStatus) rawMessage;
- if (field == IS_ONLINE) {
- return message.getIsOnline();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final NetworkStatusAccessor NETWORK_STATUS_ACCESSOR = new NetworkStatusAccessor();
-
- /** Class to access fields in {@link ServerMessage} protos. */
- public static class ServerMessageAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "data"
- ));
-
- public static final Descriptor DATA = new Descriptor("data");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ServerMessage message = (ServerMessage) rawMessage;
- if (field == DATA) {
- return message.hasData();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ServerMessage message = (ServerMessage) rawMessage;
- if (field == DATA) {
- return message.getData();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ServerMessageAccessor SERVER_MESSAGE_ACCESSOR = new ServerMessageAccessor();
-
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "version",
- "server_message",
- "network_status",
- "network_addr_change",
- "create_client"
- ));
-
- public static final Descriptor VERSION = new Descriptor("version");
- public static final Descriptor SERVER_MESSAGE = new Descriptor("server_message");
- public static final Descriptor NETWORK_STATUS = new Descriptor("network_status");
- public static final Descriptor NETWORK_ADDR_CHANGE = new Descriptor("network_addr_change");
- public static final Descriptor CREATE_CLIENT = new Descriptor("create_client");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- InternalDowncall message = (InternalDowncall) rawMessage;
- if (field == VERSION) {
- return message.hasVersion();
- }
- if (field == SERVER_MESSAGE) {
- return message.hasServerMessage();
- }
- if (field == NETWORK_STATUS) {
- return message.hasNetworkStatus();
- }
- if (field == NETWORK_ADDR_CHANGE) {
- return message.hasNetworkAddrChange();
- }
- if (field == CREATE_CLIENT) {
- return message.hasCreateClient();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- InternalDowncall message = (InternalDowncall) rawMessage;
- if (field == VERSION) {
- return message.getVersion();
- }
- if (field == SERVER_MESSAGE) {
- return message.getServerMessage();
- }
- if (field == NETWORK_STATUS) {
- return message.getNetworkStatus();
- }
- if (field == NETWORK_ADDR_CHANGE) {
- return message.getNetworkAddrChange();
- }
- if (field == CREATE_CLIENT) {
- return message.getCreateClient();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final InternalDowncallAccessor INTERNAL_DOWNCALL_ACCESSOR = new InternalDowncallAccessor();
-
- /** Class to access fields in {@link ListenerUpcall} protos. */
- public static class ListenerUpcallAccessor implements Accessor {
- /** Class to access fields in {@link ErrorUpcall} protos. */
- public static class ErrorUpcallAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "error_code",
- "error_message",
- "is_transient"
- ));
-
- public static final Descriptor ERROR_CODE = new Descriptor("error_code");
- public static final Descriptor ERROR_MESSAGE = new Descriptor("error_message");
- public static final Descriptor IS_TRANSIENT = new Descriptor("is_transient");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ErrorUpcall message = (ErrorUpcall) rawMessage;
- if (field == ERROR_CODE) {
- return message.hasErrorCode();
- }
- if (field == ERROR_MESSAGE) {
- return message.hasErrorMessage();
- }
- if (field == IS_TRANSIENT) {
- return message.hasIsTransient();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ErrorUpcall message = (ErrorUpcall) rawMessage;
- if (field == ERROR_CODE) {
- return message.getErrorCode();
- }
- if (field == ERROR_MESSAGE) {
- return message.getErrorMessage();
- }
- if (field == IS_TRANSIENT) {
- return message.getIsTransient();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ErrorUpcallAccessor ERROR_UPCALL_ACCESSOR = new ErrorUpcallAccessor();
-
- /** Class to access fields in {@link ReissueRegistrationsUpcall} protos. */
- public static class ReissueRegistrationsUpcallAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "prefix",
- "length"
- ));
-
- public static final Descriptor PREFIX = new Descriptor("prefix");
- public static final Descriptor LENGTH = new Descriptor("length");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ReissueRegistrationsUpcall message = (ReissueRegistrationsUpcall) rawMessage;
- if (field == PREFIX) {
- return message.hasPrefix();
- }
- if (field == LENGTH) {
- return message.hasLength();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ReissueRegistrationsUpcall message = (ReissueRegistrationsUpcall) rawMessage;
- if (field == PREFIX) {
- return message.getPrefix();
- }
- if (field == LENGTH) {
- return message.getLength();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ReissueRegistrationsUpcallAccessor REISSUE_REGISTRATIONS_UPCALL_ACCESSOR = new ReissueRegistrationsUpcallAccessor();
-
- /** Class to access fields in {@link RegistrationFailureUpcall} protos. */
- public static class RegistrationFailureUpcallAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "object_id",
- "transient",
- "message"
- ));
-
- public static final Descriptor OBJECT_ID = new Descriptor("object_id");
- public static final Descriptor TRANSIENT = new Descriptor("transient");
- public static final Descriptor MESSAGE = new Descriptor("message");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationFailureUpcall message = (RegistrationFailureUpcall) rawMessage;
- if (field == OBJECT_ID) {
- return message.hasObjectId();
- }
- if (field == TRANSIENT) {
- return message.hasTransient();
- }
- if (field == MESSAGE) {
- return message.hasMessage();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationFailureUpcall message = (RegistrationFailureUpcall) rawMessage;
- if (field == OBJECT_ID) {
- return message.getObjectId();
- }
- if (field == TRANSIENT) {
- return message.getTransient();
- }
- if (field == MESSAGE) {
- return message.getMessage();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final RegistrationFailureUpcallAccessor REGISTRATION_FAILURE_UPCALL_ACCESSOR = new RegistrationFailureUpcallAccessor();
-
- /** Class to access fields in {@link RegistrationStatusUpcall} protos. */
- public static class RegistrationStatusUpcallAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "object_id",
- "is_registered"
- ));
-
- public static final Descriptor OBJECT_ID = new Descriptor("object_id");
- public static final Descriptor IS_REGISTERED = new Descriptor("is_registered");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationStatusUpcall message = (RegistrationStatusUpcall) rawMessage;
- if (field == OBJECT_ID) {
- return message.hasObjectId();
- }
- if (field == IS_REGISTERED) {
- return message.hasIsRegistered();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- RegistrationStatusUpcall message = (RegistrationStatusUpcall) rawMessage;
- if (field == OBJECT_ID) {
- return message.getObjectId();
- }
- if (field == IS_REGISTERED) {
- return message.getIsRegistered();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final RegistrationStatusUpcallAccessor REGISTRATION_STATUS_UPCALL_ACCESSOR = new RegistrationStatusUpcallAccessor();
-
- /** Class to access fields in {@link InvalidateUpcall} protos. */
- public static class InvalidateUpcallAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "ack_handle",
- "invalidation",
- "invalidate_unknown",
- "invalidate_all"
- ));
-
- public static final Descriptor ACK_HANDLE = new Descriptor("ack_handle");
- public static final Descriptor INVALIDATION = new Descriptor("invalidation");
- public static final Descriptor INVALIDATE_UNKNOWN = new Descriptor("invalidate_unknown");
- public static final Descriptor INVALIDATE_ALL = new Descriptor("invalidate_all");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- InvalidateUpcall message = (InvalidateUpcall) rawMessage;
- if (field == ACK_HANDLE) {
- return message.hasAckHandle();
- }
- if (field == INVALIDATION) {
- return message.hasInvalidation();
- }
- if (field == INVALIDATE_UNKNOWN) {
- return message.hasInvalidateUnknown();
- }
- if (field == INVALIDATE_ALL) {
- return message.hasInvalidateAll();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- InvalidateUpcall message = (InvalidateUpcall) rawMessage;
- if (field == ACK_HANDLE) {
- return message.getAckHandle();
- }
- if (field == INVALIDATION) {
- return message.getInvalidation();
- }
- if (field == INVALIDATE_UNKNOWN) {
- return message.getInvalidateUnknown();
- }
- if (field == INVALIDATE_ALL) {
- return message.getInvalidateAll();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final InvalidateUpcallAccessor INVALIDATE_UPCALL_ACCESSOR = new InvalidateUpcallAccessor();
-
- /** Class to access fields in {@link ReadyUpcall} protos. */
- public static class ReadyUpcallAccessor implements Accessor {
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- ));
-
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ReadyUpcall message = (ReadyUpcall) rawMessage;
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ReadyUpcall message = (ReadyUpcall) rawMessage;
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ReadyUpcallAccessor READY_UPCALL_ACCESSOR = new ReadyUpcallAccessor();
-
- private static final Set<String> ALL_FIELD_NAMES = new HashSet<String>(
- Arrays.<String>asList(
- "serial",
- "version",
- "ready",
- "invalidate",
- "registration_status",
- "registration_failure",
- "reissue_registrations",
- "error"
- ));
-
- public static final Descriptor SERIAL = new Descriptor("serial");
- public static final Descriptor VERSION = new Descriptor("version");
- public static final Descriptor READY = new Descriptor("ready");
- public static final Descriptor INVALIDATE = new Descriptor("invalidate");
- public static final Descriptor REGISTRATION_STATUS = new Descriptor("registration_status");
- public static final Descriptor REGISTRATION_FAILURE = new Descriptor("registration_failure");
- public static final Descriptor REISSUE_REGISTRATIONS = new Descriptor("reissue_registrations");
- public static final Descriptor ERROR = new Descriptor("error");
-
- /** Returns whether {@code field} is present in {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public boolean hasField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ListenerUpcall message = (ListenerUpcall) rawMessage;
- if (field == SERIAL) {
- return message.hasSerial();
- }
- if (field == VERSION) {
- return message.hasVersion();
- }
- if (field == READY) {
- return message.hasReady();
- }
- if (field == INVALIDATE) {
- return message.hasInvalidate();
- }
- if (field == REGISTRATION_STATUS) {
- return message.hasRegistrationStatus();
- }
- if (field == REGISTRATION_FAILURE) {
- return message.hasRegistrationFailure();
- }
- if (field == REISSUE_REGISTRATIONS) {
- return message.hasReissueRegistrations();
- }
- if (field == ERROR) {
- return message.hasError();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- /** Returns the {@code field} from {@code message}. */
- @Override
- @SuppressWarnings("unchecked")
- public Object getField(MessageLite rawMessage, Descriptor field) {
- Preconditions.checkNotNull(rawMessage);
- Preconditions.checkNotNull(field);
- ListenerUpcall message = (ListenerUpcall) rawMessage;
- if (field == SERIAL) {
- return message.getSerial();
- }
- if (field == VERSION) {
- return message.getVersion();
- }
- if (field == READY) {
- return message.getReady();
- }
- if (field == INVALIDATE) {
- return message.getInvalidate();
- }
- if (field == REGISTRATION_STATUS) {
- return message.getRegistrationStatus();
- }
- if (field == REGISTRATION_FAILURE) {
- return message.getRegistrationFailure();
- }
- if (field == REISSUE_REGISTRATIONS) {
- return message.getReissueRegistrations();
- }
- if (field == ERROR) {
- return message.getError();
- }
- throw new IllegalArgumentException("Bad descriptor: " + field);
- }
-
- @Override
- public Set<String> getAllFieldNames() {
- return ALL_FIELD_NAMES;
- }
- }
- public static final ListenerUpcallAccessor LISTENER_UPCALL_ACCESSOR = new ListenerUpcallAccessor();
-
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidStorage.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidStorage.java
deleted file mode 100644
index b9231e5e67b..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidStorage.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.ipc.invalidation.external.client.SystemResources.Storage;
-import com.google.ipc.invalidation.external.client.types.Callback;
-import com.google.ipc.invalidation.external.client.types.SimplePair;
-import com.google.ipc.invalidation.external.client.types.Status;
-import com.google.ipc.invalidation.ticl.InvalidationClientCore;
-
-import android.content.Context;
-
-import java.io.DataInputStream;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-
-/**
- * Implementation of {@link Storage} for the Android Ticl. This implementation supports only
- * the {@link InvalidationClientCore#CLIENT_TOKEN_KEY}. As required by Android storage
- * implementations, it executes all callbacks synchronously.
- *
- */
-public class AndroidStorage implements Storage {
- /** Name of the file in which state will be stored. */
- private static final String STATE_FILENAME = "ticl_storage.bin";
-
- /** Maximum size of the file which we are willing to read. */
- private static final int MAX_STATE_FILE_SIZE_BYTES = 4096;
-
- private final Context context;
-
- public AndroidStorage(Context context) {
- this.context = Preconditions.checkNotNull(context);
- }
-
- @Override
- public void setSystemResources(SystemResources resources) {
- }
-
- @Override
- public void writeKey(String key, byte[] value, Callback<Status> done) {
- // We only support the CLIENT_TOKEN_KEY.
- if (!key.equals(InvalidationClientCore.CLIENT_TOKEN_KEY)) {
- done.accept(Status.newInstance(Status.Code.PERMANENT_FAILURE, "Key unsupported: " + key));
- return;
- }
- // Write the data.
- FileOutputStream outstream = null;
- Status status = null;
- try {
- outstream = context.openFileOutput(STATE_FILENAME, Context.MODE_PRIVATE);
- outstream.write(value);
- status = Status.newInstance(Status.Code.SUCCESS, "");
- } catch (FileNotFoundException exception) {
- status = Status.newInstance(Status.Code.PERMANENT_FAILURE, "File not found: " + exception);
- } catch (IOException exception) {
- status = Status.newInstance(Status.Code.PERMANENT_FAILURE, "File not found: " + exception);
- } finally {
- if (outstream != null) {
- try {
- outstream.close();
- } catch (IOException exception) {
- status = Status.newInstance(
- Status.Code.PERMANENT_FAILURE, "Failed to close file: " + exception);
- }
- }
- }
- done.accept(status);
- }
-
- @Override
- public void readKey(String key, Callback<SimplePair<Status, byte[]>> done) {
- // We only support the CLIENT_TOKEN_KEY.
- if (!key.equals(InvalidationClientCore.CLIENT_TOKEN_KEY)) {
- Status status = Status.newInstance(Status.Code.PERMANENT_FAILURE, "Key unsupported: " + key);
- done.accept(SimplePair.of(status, (byte[]) null));
- return;
- }
- // Read and return the data.
- FileInputStream instream = null;
- SimplePair<Status, byte[]> result = null;
- try {
- instream = context.openFileInput(STATE_FILENAME);
- long fileSizeBytes = instream.getChannel().size();
- if (fileSizeBytes > MAX_STATE_FILE_SIZE_BYTES) {
- Status status =
- Status.newInstance(Status.Code.PERMANENT_FAILURE, "File too big: " + fileSizeBytes);
- result = SimplePair.of(status, (byte[]) null);
- }
- // Cast to int must be safe due to the above size check.
- DataInputStream input = new DataInputStream(instream);
- byte[] fileData = new byte[(int) fileSizeBytes];
- input.readFully(fileData);
- result = SimplePair.of(Status.newInstance(Status.Code.SUCCESS, ""), fileData);
- } catch (FileNotFoundException exception) {
- Status status =
- Status.newInstance(Status.Code.PERMANENT_FAILURE, "File not found: " + exception);
- result = SimplePair.of(status, (byte[]) null);
- } catch (IOException exception) {
- Status status =
- Status.newInstance(Status.Code.TRANSIENT_FAILURE, "IO exception: " + exception);
- result = SimplePair.of(status, (byte[]) null);
- } finally {
- if (instream != null) {
- try {
- instream.close();
- } catch (IOException exception) {
- Status status =
- Status.newInstance(
- Status.Code.TRANSIENT_FAILURE, "Failed to close file: " + exception);
- result = SimplePair.of(status, (byte[]) null);
- }
- }
- }
- done.accept(result);
- }
-
- @Override
- public void deleteKey(String key, Callback<Boolean> done) {
- // We only support the CLIENT_TOKEN_KEY.
- if (!key.equals(InvalidationClientCore.CLIENT_TOKEN_KEY)) {
- done.accept(false);
- return;
- }
- if (!context.getFileStreamPath(STATE_FILENAME).exists()) {
- // Deletion "succeeds" if the key didn't exist.
- done.accept(true);
- } else {
- // Otherwise it succeeds based on whether the IO operation succeeded.
- done.accept(context.deleteFile(STATE_FILENAME));
- }
- }
-
- @Override
- public void readAllKeys(Callback<SimplePair<Status, String>> keyCallback) {
- // If the state file exists, supply the CLIENT_TOKEN_KEY as a present key.
- if (context.getFileStreamPath(STATE_FILENAME).exists()) {
- Status status = Status.newInstance(Status.Code.SUCCESS, "");
- keyCallback.accept(SimplePair.of(status, InvalidationClientCore.CLIENT_TOKEN_KEY));
- }
- keyCallback.accept(null);
- }
-
- static void deleteStateForTest(Context context) {
- context.deleteFile(STATE_FILENAME);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidStrings.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidStrings.java
deleted file mode 100644
index 4bc6c5be891..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidStrings.java
+++ /dev/null
@@ -1,390 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2;
-
-import com.google.common.base.Joiner;
-import com.google.ipc.invalidation.common.CommonProtoStrings2;
-import com.google.ipc.invalidation.util.TextBuilder;
-import com.google.protobuf.ByteString;
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidNetworkSendRequest;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidSchedulerEvent;
-import com.google.protos.ipc.invalidation.AndroidService.ClientDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.ClientDowncall.AckDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.ClientDowncall.RegistrationDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.InternalDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.InternalDowncall.CreateClient;
-import com.google.protos.ipc.invalidation.AndroidService.InternalDowncall.NetworkStatus;
-import com.google.protos.ipc.invalidation.AndroidService.InternalDowncall.ServerMessage;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.ErrorUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.InvalidateUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.RegistrationFailureUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.RegistrationStatusUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.ReissueRegistrationsUpcall;
-import com.google.protos.ipc.invalidation.Client.AckHandleP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ObjectIdP;
-
-import android.content.Intent;
-
-import java.util.List;
-
-
-/**
- * Utilities to format Android protocol buffers and intents as compact strings suitable for logging.
- * By convention, methods take a {@link TextBuilder} and the object to format and return the
- * builder. Null object arguments are permitted.
- *
- * <p>{@link #toCompactString} methods immediately append a description of the object to the given
- * {@link TextBuilder}s. {@link #toLazyCompactString} methods return an object that defers the work
- * of formatting the provided argument until {@link Object#toString} is called.
- *
- */
-public class AndroidStrings {
-
- /**
- * String to return when the argument is unknown (suggests a new protocol field or invalid
- * proto).
- */
- static final String UNKNOWN_MESSAGE = "UNKNOWN@AndroidStrings";
-
- /**
- * String to return when there is an error formatting an argument.
- */
- static final String ERROR_MESSAGE = "ERROR@AndroidStrings";
-
- /**
- * Returns an object that lazily evaluates {@link #toCompactString} when {@link Object#toString}
- * is called.
- */
- public static Object toLazyCompactString(final Intent intent) {
- return new Object() {
- @Override
- public String toString() {
- TextBuilder builder = new TextBuilder();
- AndroidStrings.toCompactString(builder, intent);
- return builder.toString();
- }
- };
- }
-
- /** Appends a description of the given client {@code downcall} to the given {@code builder}. */
- public static TextBuilder toCompactString(TextBuilder builder,
- ClientDowncall downcall) {
- if (downcall == null) {
- return builder;
- }
- builder.append(ProtocolIntents.CLIENT_DOWNCALL_KEY).append("::");
- if (downcall.hasStart()) {
- builder.append("start()");
- } else if (downcall.hasStop()) {
- builder.append("stop()");
- } else if (downcall.hasAck()) {
- toCompactString(builder, downcall.getAck());
- } else if (downcall.hasRegistrations()) {
- toCompactString(builder, downcall.getRegistrations());
- } else {
- builder.append(UNKNOWN_MESSAGE);
- }
- return builder;
- }
-
- /** Appends a description of the given {@code ack} downcall to the given {@code builder}. */
- public static TextBuilder toCompactString(TextBuilder builder, AckDowncall ack) {
- if (ack == null) {
- return builder;
- }
- builder.append("ack(");
- serializedAckHandleToCompactString(builder, ack.getAckHandle());
- return builder.append(")");
- }
-
- /**
- * Appends a description of the given {@code registration} downcall to the given {@code builder}.
- */
- public static TextBuilder toCompactString(TextBuilder builder,
- RegistrationDowncall registration) {
- if (registration == null) {
- return builder;
- }
- List<ObjectIdP> objects;
- if (registration.getRegistrationsCount() > 0) {
- builder.append("register(");
- objects = registration.getRegistrationsList();
- } else {
- builder.append("unregister(");
- objects = registration.getUnregistrationsList();
- }
- return CommonProtoStrings2.toCompactStringForObjectIds(builder, objects).append(")");
- }
-
- /** Appends a description of the given internal {@code downcall} to the given {@code builder}. */
- public static TextBuilder toCompactString(TextBuilder builder,
- InternalDowncall downcall) {
- if (downcall == null) {
- return builder;
- }
- builder.append(ProtocolIntents.INTERNAL_DOWNCALL_KEY).append("::");
- if (downcall.hasServerMessage()) {
- toCompactString(builder, downcall.getServerMessage());
- } else if (downcall.hasNetworkStatus()) {
- toCompactString(builder, downcall.getNetworkStatus());
- } else if (downcall.hasNetworkAddrChange()) {
- builder.append("newtworkAddrChange()");
- } else if (downcall.hasCreateClient()) {
- toCompactString(builder, downcall.getCreateClient());
- } else {
- builder.append(UNKNOWN_MESSAGE);
- }
- return builder;
- }
-
- /** Appends a description of the given {@code serverMessage} to the given {@code builder}. */
- public static TextBuilder toCompactString(TextBuilder builder,
- ServerMessage serverMessage) {
- if (serverMessage == null) {
- return builder;
- }
- return builder.append("serverMessage(").append(serverMessage.getData()).append(")");
- }
-
- /** Appends a description of the given {@code networkStatus} to the given {@code builder}. */
- public static TextBuilder toCompactString(TextBuilder builder,
- NetworkStatus networkStatus) {
- if (networkStatus == null) {
- return builder;
- }
- return builder.append("networkStatus(isOnline = ").append(networkStatus.getIsOnline())
- .append(")");
- }
-
- /**
- * Appends a description of the given {@code createClient} command to the given {@code builder}.
- */
- public static TextBuilder toCompactString(TextBuilder builder,
- CreateClient createClient) {
- if (createClient == null) {
- return builder;
- }
- return builder.append("createClient(type = ").append(createClient.getClientType())
- .append(", name = ").append(createClient.getClientName()).append(", skipStartForTest = ")
- .append(createClient.getSkipStartForTest()).append(")");
- }
-
- /** Appends a description of the given listener {@code upcall} to the given {@code builder}. */
- public static TextBuilder toCompactString(TextBuilder builder,
- ListenerUpcall upcall) {
- if (upcall == null) {
- return builder;
- }
- builder.append(ProtocolIntents.LISTENER_UPCALL_KEY).append("::");
- if (upcall.hasReady()) {
- builder.append(".ready()");
- } else if (upcall.hasInvalidate()) {
- toCompactString(builder, upcall.getInvalidate());
- } else if (upcall.hasRegistrationStatus()) {
- toCompactString(builder, upcall.getRegistrationStatus());
- } else if (upcall.hasRegistrationFailure()) {
- toCompactString(builder, upcall.getRegistrationFailure());
- } else if (upcall.hasReissueRegistrations()) {
- toCompactString(builder, upcall.getReissueRegistrations());
- } else if (upcall.hasError()) {
- toCompactString(builder, upcall.getError());
- } else {
- builder.append(UNKNOWN_MESSAGE);
- }
- return builder;
- }
-
- /** Appends a description of the given {@code invalidate} command to the given {@code builder}. */
- public static TextBuilder toCompactString(TextBuilder builder,
- InvalidateUpcall invalidate) {
- if (invalidate == null) {
- return builder;
- }
- builder.append("invalidate(ackHandle = ");
- serializedAckHandleToCompactString(builder, invalidate.getAckHandle());
- builder.append(", ");
- if (invalidate.hasInvalidation()) {
- CommonProtoStrings2.toCompactString(builder, invalidate.getInvalidation());
- } else if (invalidate.getInvalidateAll()) {
- builder.append("ALL");
- } else if (invalidate.hasInvalidateUnknown()) {
- builder.append("UNKNOWN: ");
- CommonProtoStrings2.toCompactString(builder, invalidate.getInvalidateUnknown());
- }
- return builder.append(")");
- }
-
- /** Appends a description of the given {@code status} upcall to the given {@code builder}. */
- public static TextBuilder toCompactString(TextBuilder builder,
- RegistrationStatusUpcall status) {
- if (status == null) {
- return builder;
- }
- builder.append("registrationStatus(objectId = ");
- CommonProtoStrings2.toCompactString(builder, status.getObjectId());
- return builder.append(", isRegistered = ").append(status.getIsRegistered()).append(")");
- }
-
- /** Appends a description of the given {@code failure} upcall to the given {@code builder}. */
- public static TextBuilder toCompactString(TextBuilder builder,
- RegistrationFailureUpcall failure) {
- if (failure == null) {
- return builder;
- }
- builder.append("registrationFailure(objectId = ");
- CommonProtoStrings2.toCompactString(builder, failure.getObjectId());
- return builder.append(", isTransient = ").append(failure.getTransient()).append(")");
- }
-
- /**
- * Appends a description of the given {@code reissue} registrations upcall to the given
- * {@code builder}.
- */
- public static TextBuilder toCompactString(TextBuilder builder,
- ReissueRegistrationsUpcall reissue) {
- if (reissue == null) {
- return builder;
- }
- builder.append("reissueRegistrations(prefix = ");
- return builder.append(reissue.getPrefix()).append(", length = ").append(reissue.getLength())
- .append(")");
- }
-
- /** Appends a description of the given {@code error} upcall to the given {@code builder}. */
- public static TextBuilder toCompactString(TextBuilder builder, ErrorUpcall error) {
- if (error == null) {
- return builder;
- }
- return builder.append("error(code = ").append(error.getErrorCode()).append(", message = ")
- .append(error.getErrorMessage()).append(", isTransient = ").append(error.getIsTransient())
- .append(")");
- }
-
- /** Appends a description of the given {@code request} to the given {@code builder}. */
- public static TextBuilder toCompactString(TextBuilder builder,
- AndroidNetworkSendRequest request) {
- if (request == null) {
- return builder;
- }
- return builder.append(ProtocolIntents.OUTBOUND_MESSAGE_KEY).append("(")
- .append(request.getMessage()).append(")");
- }
-
- /** Appends a description of the given (@code event} to the given {@code builder}. */
- public static TextBuilder toCompactString(TextBuilder builder,
- AndroidSchedulerEvent event) {
- if (event == null) {
- return builder;
- }
- return builder.append(ProtocolIntents.SCHEDULER_KEY).append("(eventName = ")
- .append(event.getEventName()).append(", ticlId = ").append(event.getTiclId()).append(")");
- }
-
- /** See spec in implementation notes. */
- public static TextBuilder toCompactString(TextBuilder builder, AckHandleP ackHandle) {
- if (ackHandle == null) {
- return builder;
- }
- return CommonProtoStrings2.toCompactString(builder.appendFormat("AckHandle: "),
- ackHandle.getInvalidation());
- }
-
- /**
- * Appends a description of the given {@code intent} to the given {@code builder}. If the intent
- * includes some recognized extras, formats the extra context as well.
- */
- public static TextBuilder toCompactString(TextBuilder builder, Intent intent) {
- if (intent == null) {
- return builder;
- }
- builder.append("intent(");
- try {
- if (!tryParseExtra(builder, intent)) {
- builder.append(UNKNOWN_MESSAGE).append(", extras = ")
- .append(Joiner.on(", ").join(intent.getExtras().keySet()));
- }
- } catch (InvalidProtocolBufferException exception) {
- builder.append(ERROR_MESSAGE).append(" : ").append(exception);
- }
- return builder.append(")");
- }
-
- /** Appends a description of any known extra or appends 'UNKNOWN' if none are recognized. */
- private static boolean tryParseExtra(TextBuilder builder, Intent intent)
- throws InvalidProtocolBufferException {
- byte[] data;
-
- data = intent.getByteArrayExtra(ProtocolIntents.SCHEDULER_KEY);
- if (data != null) {
- AndroidSchedulerEvent schedulerEvent = AndroidSchedulerEvent.parseFrom(data);
- toCompactString(builder, schedulerEvent);
- return true;
- }
-
- data = intent.getByteArrayExtra(ProtocolIntents.OUTBOUND_MESSAGE_KEY);
- if (data != null) {
- AndroidNetworkSendRequest outboundMessage = AndroidNetworkSendRequest.parseFrom(data);
- toCompactString(builder, outboundMessage);
- return true;
- }
-
- data = intent.getByteArrayExtra(ProtocolIntents.LISTENER_UPCALL_KEY);
- if (data != null) {
- ListenerUpcall upcall = ListenerUpcall.parseFrom(data);
- toCompactString(builder, upcall);
- return true;
- }
-
- data = intent.getByteArrayExtra(ProtocolIntents.INTERNAL_DOWNCALL_KEY);
- if (data != null) {
- InternalDowncall internalDowncall = InternalDowncall.parseFrom(data);
- toCompactString(builder, internalDowncall);
- return true;
- }
-
- data = intent.getByteArrayExtra(ProtocolIntents.CLIENT_DOWNCALL_KEY);
- if (data != null) {
- ClientDowncall clientDowncall = ClientDowncall.parseFrom(data);
- toCompactString(builder, clientDowncall);
- return true;
- }
-
- // Didn't recognize any intents.
- return false;
- }
-
- /** Given serialized form of an ack handle, appends description to {@code builder}. */
- private static TextBuilder serializedAckHandleToCompactString(
- TextBuilder builder, ByteString serialized) {
- if (serialized == null) {
- return builder;
- }
- // The ack handle is supposed by an AckHandleP!
- try {
- AckHandleP ackHandle = AckHandleP.parseFrom(serialized);
- return toCompactString(builder, ackHandle);
- } catch (InvalidProtocolBufferException exception) {
- // But it wasn't... Just log the raw bytes.
- return builder.append(serialized);
- }
- }
-
- private AndroidStrings() {
- // Avoid instantiation.
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidTiclManifest.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidTiclManifest.java
deleted file mode 100644
index 09d69ca5ae9..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidTiclManifest.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2;
-
-import com.google.common.base.Preconditions;
-
-import android.content.Context;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.PackageManager.NameNotFoundException;
-
-import java.util.HashMap;
-import java.util.Map;
-
-
-/**
- * Interface to the {@code AndroidManifest.xml} that provides access to the configuration data
- * required by the Android Ticl.
- *
- */
-public class AndroidTiclManifest {
- /**
- * Name of the {@code <application>} metadata element whose value gives the Java class that
- * implements the application {@code InvalidationListener}. Must be set if
- * {@link #LISTENER_SERVICE_NAME_KEY} is not set.
- */
- private static final String LISTENER_NAME_KEY = "ipc.invalidation.ticl.listener_class";
-
- /**
- * Name of the {@code <application>} metadata element whose value gives the Java class that
- * implements the Ticl service. Should only be set in tests.
- */
- private static final String TICL_SERVICE_NAME_KEY = "ipc.invalidation.ticl.service_class";
-
- /**
- * Name of the {@code <application>} metadata element whose value gives the Java class that
- * implements the application's invalidation listener intent service.
- */
- private static final String LISTENER_SERVICE_NAME_KEY =
- "ipc.invalidation.ticl.listener_service_class";
-
- /** Default values returned if not overriden by the manifest file. */
- private static final Map<String, String> DEFAULTS = new HashMap<String, String>();
- static {
- DEFAULTS.put(TICL_SERVICE_NAME_KEY,
- "com.google.ipc.invalidation.ticl.android2.TiclService");
- DEFAULTS.put(LISTENER_NAME_KEY, "");
- DEFAULTS.put(LISTENER_SERVICE_NAME_KEY,
- "com.google.ipc.invalidation.ticl.android2.AndroidInvalidationListenerStub");
- }
-
- private final Context context;
-
- public AndroidTiclManifest(Context context) {
- this.context = Preconditions.checkNotNull(context);
- }
-
- /** Returns the name of the class implementing the Ticl service. */
- public String getTiclServiceClass() {
- return Preconditions.checkNotNull(readApplicationMetadata(TICL_SERVICE_NAME_KEY));
- }
-
- /** Returns the name of the class on which listener events will be invoked. */
- String getListenerClass() {
- return Preconditions.checkNotNull(readApplicationMetadata(LISTENER_NAME_KEY));
- }
-
- /** Returns the name of the class implementing the invalidation listener intent service. */
- public String getListenerServiceClass() {
- return Preconditions.checkNotNull(readApplicationMetadata(LISTENER_SERVICE_NAME_KEY));
- }
-
- /**
- * Returns the metadata-provided value for {@code key} in {@code AndroidManifest.xml} if one
- * exists, or the value from {@link #DEFAULTS} if one does not.
- */
- private String readApplicationMetadata(String key) {
- ApplicationInfo appInfo;
- try {
- // Read the manifest-provided value.
- appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(),
- PackageManager.GET_META_DATA);
- String value = null;
- if (appInfo.metaData != null) {
- value = appInfo.metaData.getString(key);
- }
- // Return the manifest value if present or the default value if not.
- return (value != null) ?
- value : Preconditions.checkNotNull(DEFAULTS.get(key), "No default value for %s", key);
- } catch (NameNotFoundException exception) {
- throw new RuntimeException("Cannot read own application info", exception);
- }
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/ProtocolIntents.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/ProtocolIntents.java
deleted file mode 100644
index c6852d88ec5..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/ProtocolIntents.java
+++ /dev/null
@@ -1,288 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2;
-
-import com.google.ipc.invalidation.common.CommonProtos2;
-import com.google.ipc.invalidation.external.client.types.ErrorInfo;
-import com.google.protobuf.ByteString;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidNetworkSendRequest;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidSchedulerEvent;
-import com.google.protos.ipc.invalidation.AndroidService.ClientDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.ClientDowncall.AckDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.ClientDowncall.RegistrationDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.ClientDowncall.StartDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.ClientDowncall.StopDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.InternalDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.InternalDowncall.CreateClient;
-import com.google.protos.ipc.invalidation.AndroidService.InternalDowncall.NetworkStatus;
-import com.google.protos.ipc.invalidation.AndroidService.InternalDowncall.ServerMessage;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.ErrorUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.InvalidateUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.ReadyUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.RegistrationFailureUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.RegistrationStatusUpcall;
-import com.google.protos.ipc.invalidation.AndroidService.ListenerUpcall.ReissueRegistrationsUpcall;
-import com.google.protos.ipc.invalidation.Client.AckHandleP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientConfigP;
-import com.google.protos.ipc.invalidation.ClientProtocol.InvalidationP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ObjectIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.Version;
-
-import android.content.Intent;
-
-/**
- * Factory class for {@link Intent}s used between the application, Ticl, and listener in the
- * Android Ticl.
- *
- */
-public class ProtocolIntents {
- /** Version of the on-device protocol. */
- static final Version ANDROID_PROTOCOL_VERSION_VALUE = CommonProtos2.newVersion(1, 0);
-
- /** Key of Intent byte[] extra holding a client downcall protocol buffer. */
- public static final String CLIENT_DOWNCALL_KEY = "ipcinv-downcall";
-
- /** Key of Intent byte[] extra holding an internal downcall protocol buffer. */
- public static final String INTERNAL_DOWNCALL_KEY = "ipcinv-internal-downcall";
-
- /** Key of Intent byte[] extra holding a listener upcall protocol buffer. */
- public static final String LISTENER_UPCALL_KEY = "ipcinv-upcall";
-
- /** Key of Intent byte[] extra holding a schedule event protocol buffer. */
- public static final String SCHEDULER_KEY = "ipcinv-scheduler";
-
- /** Key of Intent byte[] extra holding an outbound message protocol buffer. */
- public static final String OUTBOUND_MESSAGE_KEY = "ipcinv-outbound-message";
-
- /** Intents corresponding to calls on {@code InvalidationClient}. */
- public static class ClientDowncalls {
- public static Intent newStartIntent() {
- Intent intent = new Intent();
- intent.putExtra(CLIENT_DOWNCALL_KEY, newBuilder()
- .setStart(StartDowncall.getDefaultInstance())
- .build().toByteArray());
- return intent;
- }
-
- public static Intent newStopIntent() {
- Intent intent = new Intent();
- intent.putExtra(CLIENT_DOWNCALL_KEY, newBuilder()
- .setStop(StopDowncall.getDefaultInstance())
- .build().toByteArray());
- return intent;
- }
-
- public static Intent newAcknowledgeIntent(AckHandleP ackHandle) {
- AckDowncall ackDowncall = AckDowncall.newBuilder()
- .setAckHandle(ackHandle.toByteString()).build();
- Intent intent = new Intent();
- intent.putExtra(CLIENT_DOWNCALL_KEY,
- newBuilder().setAck(ackDowncall).build().toByteArray());
- return intent;
- }
-
- public static Intent newRegistrationIntent(Iterable<ObjectIdP> registrations) {
- RegistrationDowncall regDowncall = RegistrationDowncall.newBuilder()
- .addAllRegistrations(registrations).build();
- Intent intent = new Intent();
- intent.putExtra(CLIENT_DOWNCALL_KEY,
- newBuilder().setRegistrations(regDowncall).build().toByteArray());
- return intent;
- }
-
- public static Intent newUnregistrationIntent(Iterable<ObjectIdP> unregistrations) {
- RegistrationDowncall unregDowncall = RegistrationDowncall.newBuilder()
- .addAllUnregistrations(unregistrations).build();
- Intent intent = new Intent();
- intent.putExtra(CLIENT_DOWNCALL_KEY,
- newBuilder().setRegistrations(unregDowncall).build().toByteArray());
- return intent;
- }
-
- private static ClientDowncall.Builder newBuilder() {
- return ClientDowncall.newBuilder().setVersion(ANDROID_PROTOCOL_VERSION_VALUE);
- }
-
- private ClientDowncalls() {
- // Disallow instantiation.
- }
- }
-
- /** Intents for non-public calls on the Ticl (currently, network-related calls. */
- public static class InternalDowncalls {
- public static Intent newServerMessageIntent(ByteString serverMessage) {
- Intent intent = new Intent();
- intent.putExtra(INTERNAL_DOWNCALL_KEY,
- newBuilder()
- .setServerMessage(ServerMessage.newBuilder().setData(serverMessage))
- .build().toByteArray());
- return intent;
- }
-
- public static Intent newNetworkStatusIntent(Boolean status) {
- Intent intent = new Intent();
- intent.putExtra(INTERNAL_DOWNCALL_KEY,
- newBuilder()
- .setNetworkStatus(NetworkStatus.newBuilder().setIsOnline(status))
- .build().toByteArray());
- return intent;
- }
-
- public static Intent newNetworkAddrChangeIntent() {
- Intent intent = new Intent();
- intent.putExtra(INTERNAL_DOWNCALL_KEY,
- newBuilder().setNetworkAddrChange(true).build().toByteArray());
- return intent;
- }
-
- public static Intent newCreateClientIntent(int clientType, byte[] clientName,
- ClientConfigP config, boolean skipStartForTest) {
- CreateClient createClient = CreateClient.newBuilder()
- .setClientType(clientType)
- .setClientName(ByteString.copyFrom(clientName))
- .setClientConfig(config)
- .setSkipStartForTest(skipStartForTest)
- .build();
- Intent intent = new Intent();
- intent.putExtra(INTERNAL_DOWNCALL_KEY,
- newBuilder().setCreateClient(createClient).build().toByteArray());
- return intent;
- }
-
- private static InternalDowncall.Builder newBuilder() {
- return InternalDowncall.newBuilder().setVersion(ANDROID_PROTOCOL_VERSION_VALUE);
- }
-
- private InternalDowncalls() {
- // Disallow instantiation.
- }
- }
-
- /** Intents corresponding to calls on {@code InvalidationListener}. */
- public static class ListenerUpcalls {
- public static Intent newReadyIntent() {
- Intent intent = new Intent();
- intent.putExtra(LISTENER_UPCALL_KEY,
- newBuilder().setReady(ReadyUpcall.getDefaultInstance()).build().toByteArray());
- return intent;
- }
-
- public static Intent newInvalidateIntent(InvalidationP invalidation, AckHandleP ackHandle) {
- Intent intent = new Intent();
- InvalidateUpcall invUpcall = InvalidateUpcall.newBuilder()
- .setAckHandle(ackHandle.toByteString())
- .setInvalidation(invalidation).build();
- intent.putExtra(LISTENER_UPCALL_KEY,
- newBuilder().setInvalidate(invUpcall).build().toByteArray());
- return intent;
- }
-
- public static Intent newInvalidateUnknownIntent(ObjectIdP object, AckHandleP ackHandle) {
- Intent intent = new Intent();
- InvalidateUpcall invUpcall = InvalidateUpcall.newBuilder()
- .setAckHandle(ackHandle.toByteString())
- .setInvalidateUnknown(object).build();
- intent.putExtra(LISTENER_UPCALL_KEY,
- newBuilder().setInvalidate(invUpcall).build().toByteArray());
- return intent;
- }
-
- public static Intent newInvalidateAllIntent(AckHandleP ackHandle) {
- Intent intent = new Intent();
- InvalidateUpcall invUpcall = InvalidateUpcall.newBuilder()
- .setAckHandle(ackHandle.toByteString())
- .setInvalidateAll(true).build();
- intent.putExtra(LISTENER_UPCALL_KEY,
- newBuilder().setInvalidate(invUpcall).build().toByteArray());
- return intent;
- }
-
- public static Intent newRegistrationStatusIntent(ObjectIdP object, boolean isRegistered) {
- Intent intent = new Intent();
- RegistrationStatusUpcall regUpcall = RegistrationStatusUpcall.newBuilder()
- .setObjectId(object)
- .setIsRegistered(isRegistered).build();
- intent.putExtra(LISTENER_UPCALL_KEY,
- newBuilder().setRegistrationStatus(regUpcall).build().toByteArray());
- return intent;
- }
-
- public static Intent newRegistrationFailureIntent(ObjectIdP object, boolean isTransient,
- String message) {
- Intent intent = new Intent();
- RegistrationFailureUpcall regUpcall = RegistrationFailureUpcall.newBuilder()
- .setObjectId(object)
- .setTransient(isTransient)
- .setMessage(message).build();
- intent.putExtra(LISTENER_UPCALL_KEY,
- newBuilder().setRegistrationFailure(regUpcall).build().toByteArray());
- return intent;
- }
-
- public static Intent newReissueRegistrationsIntent(byte[] prefix, int length) {
- Intent intent = new Intent();
- ReissueRegistrationsUpcall reissueRegistrations = ReissueRegistrationsUpcall.newBuilder()
- .setPrefix(ByteString.copyFrom(prefix))
- .setLength(length).build();
- intent.putExtra(LISTENER_UPCALL_KEY,
- newBuilder().setReissueRegistrations(reissueRegistrations).build().toByteArray());
- return intent;
- }
-
- public static Intent newErrorIntent(ErrorInfo errorInfo) {
- Intent intent = new Intent();
- ErrorUpcall errorUpcall = ErrorUpcall.newBuilder()
- .setErrorCode(errorInfo.getErrorReason())
- .setErrorMessage(errorInfo.getErrorMessage())
- .setIsTransient(errorInfo.isTransient())
- .build();
- intent.putExtra(LISTENER_UPCALL_KEY,
- newBuilder().setError(errorUpcall).build().toByteArray());
- return intent;
- }
-
- private static ListenerUpcall.Builder newBuilder() {
- return ListenerUpcall.newBuilder().setVersion(ANDROID_PROTOCOL_VERSION_VALUE);
- }
-
- private ListenerUpcalls() {
- // Disallow instantiation.
- }
- }
-
- /** Returns a new intent encoding a request to execute the scheduled action {@code eventName}. */
- public static Intent newSchedulerIntent(String eventName, long ticlId) {
- byte[] eventBytes =
- AndroidSchedulerEvent.newBuilder()
- .setVersion(ANDROID_PROTOCOL_VERSION_VALUE)
- .setEventName(eventName)
- .setTiclId(ticlId).build().toByteArray();
- return new Intent().putExtra(SCHEDULER_KEY, eventBytes);
- }
-
- /** Returns a new intent encoding a message to send to the data center. */
- public static Intent newOutboundMessageIntent(byte[] message) {
- byte[] payloadBytes = AndroidNetworkSendRequest.newBuilder()
- .setVersion(ANDROID_PROTOCOL_VERSION_VALUE)
- .setMessage(ByteString.copyFrom(message)).build().toByteArray();
- return new Intent().putExtra(OUTBOUND_MESSAGE_KEY, payloadBytes);
- }
-
- private ProtocolIntents() {
- // Disallow instantiation.
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/ResourcesFactory.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/ResourcesFactory.java
deleted file mode 100644
index 45e9232ace8..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/ResourcesFactory.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.ipc.invalidation.external.client.SystemResources.NetworkChannel;
-import com.google.ipc.invalidation.external.client.SystemResources.Scheduler;
-import com.google.ipc.invalidation.external.client.SystemResources.Storage;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.ticl.BasicSystemResources;
-import com.google.ipc.invalidation.ticl.android2.channel.AndroidNetworkChannel;
-
-import android.content.Context;
-
-/**
- * Factory class for Android system resources.
- *
- */
-public class ResourcesFactory {
- /**
- * A scheduler that supports no operations. Used as the listener scheduler, which should never be
- * called in Android.
- */
- private static class InvalidScheduler implements Scheduler {
- @Override
- public void setSystemResources(SystemResources resources) {
- }
-
- @Override
- public void schedule(int delayMs, Runnable runnable) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isRunningOnThread() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public long getCurrentTimeMs() {
- throw new UnsupportedOperationException();
- }
-
- }
-
- /** Implementation of {@link SystemResources} for the Android Ticl. */
- public static class AndroidResources extends BasicSystemResources {
- /** Android system context. */
- private final Context context;
-
- /** Ticl-provided receiver for network events. */
- private NetworkChannel.NetworkListener networkListener;
-
- /**
- * Creates an instance of resources for production code.
- *
- * @param context Android system context
- * @param clock source of time for the internal scheduler
- * @param logPrefix log prefix
- */
- private AndroidResources(Context context, AndroidClock clock, String logPrefix) {
- super(AndroidLogger.forPrefix(logPrefix), new AndroidInternalScheduler(context, clock),
- new InvalidScheduler(), new AndroidNetworkChannel(context), new AndroidStorage(context),
- getPlatformString());
- this.context = Preconditions.checkNotNull(context);
- }
-
- /** Creates an instance for test from the provided resources and context. */
-
- AndroidResources(Logger logger, AndroidInternalScheduler internalScheduler,
- NetworkChannel network, Storage storage, Context context) {
- super(logger, internalScheduler, new InvalidScheduler(), network, storage,
- getPlatformString());
- this.context = Preconditions.checkNotNull(context);
- }
-
- /** Returns the Android system context. */
- Context getContext() {
- return context;
- }
-
- /**
- * Sets the network message listener provided by the Ticl. The network calls this method when
- * the Ticl provides it with a listener; the Ticl service later retrieves the listener when
- * it has a network event to communicate to the Ticl.
- */
- public void setNetworkListener(NetworkChannel.NetworkListener networkListener) {
- Preconditions.checkState(this.networkListener == null, "Listener already set: %s",
- networkListener);
- this.networkListener = Preconditions.checkNotNull(networkListener);
- }
-
- /** Clears the network listener. */
- void clearNetworkListener() {
- this.networkListener = null;
- }
-
- /** Returns the network listener provided by the Ticl. */
- NetworkChannel.NetworkListener getNetworkListener() {
- return Preconditions.checkNotNull(networkListener, "network listener not yet set");
- }
-
- /** Returns the platform string to use when constructing the resources. */
- private static String getPlatformString() {
- return "Android-" + android.os.Build.VERSION.RELEASE;
- }
- }
-
- /**
- * Creates a production instance.
- *
- * @param context Android system context
- * @param clock source of time for the internal scheduler
- * @param prefix log prefix
- */
- static AndroidResources createResources(Context context, AndroidClock clock, String prefix) {
- return new AndroidResources(context, clock, prefix);
- }
-
- private ResourcesFactory() {
- // Prevent instantiation.
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/TiclService.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/TiclService.java
deleted file mode 100644
index d81cac95dca..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/TiclService.java
+++ /dev/null
@@ -1,371 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2;
-
-import com.google.ipc.invalidation.common.DigestFunction;
-import com.google.ipc.invalidation.common.ObjectIdDigestUtils;
-import com.google.ipc.invalidation.external.client.types.AckHandle;
-import com.google.ipc.invalidation.external.client.types.Callback;
-import com.google.ipc.invalidation.external.client.types.ErrorInfo;
-import com.google.ipc.invalidation.external.client.types.ObjectId;
-import com.google.ipc.invalidation.external.client.types.SimplePair;
-import com.google.ipc.invalidation.external.client.types.Status;
-import com.google.ipc.invalidation.ticl.InvalidationClientCore;
-import com.google.ipc.invalidation.ticl.PersistenceUtils;
-import com.google.ipc.invalidation.ticl.ProtoConverter;
-import com.google.ipc.invalidation.ticl.android2.AndroidInvalidationClientImpl.IntentForwardingListener;
-import com.google.ipc.invalidation.ticl.android2.ResourcesFactory.AndroidResources;
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidSchedulerEvent;
-import com.google.protos.ipc.invalidation.AndroidService.ClientDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.ClientDowncall.RegistrationDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.InternalDowncall;
-import com.google.protos.ipc.invalidation.AndroidService.InternalDowncall.CreateClient;
-import com.google.protos.ipc.invalidation.Client.PersistentTiclState;
-
-import android.app.IntentService;
-import android.content.Intent;
-
-import java.util.List;
-
-
-/**
- * An {@link IntentService} that manages a single Ticl.
- * <p>
- * Concurrency model: {@link IntentService} guarantees that calls to {@link #onHandleIntent} will
- * be executed serially on a dedicated thread. They may perform blocking work without blocking
- * the application calling the service.
- * <p>
- * This thread will be used as the internal-scheduler thread for the Ticl.
- *
- */
-public class TiclService extends IntentService {
- /** This class must be public so that Android can instantiate it as a service. */
-
- /** Resources for the created Ticls. */
- private AndroidResources resources;
-
- /** Validator for received messages. */
- private AndroidIntentProtocolValidator validator;
-
- /** The function for computing persistence state digests when rewriting them. */
- private final DigestFunction digestFn = new ObjectIdDigestUtils.Sha1DigestFunction();
-
- public TiclService() {
- super("TiclService");
-
- // If the process dies during a call to onHandleIntent, redeliver the intent when the service
- // restarts.
- setIntentRedelivery(true);
- }
-
- /**
- * Returns the resources to use for a Ticl. Normally, we use a new resources instance
- * for every call, but for existing tests, we need to be able to override this function
- * and return the same instance each time.
- */
- AndroidResources createResources() {
- return ResourcesFactory.createResources(this, new AndroidClock.SystemClock(), "TiclService");
- }
-
- @Override
- protected void onHandleIntent(Intent intent) {
- // TODO: We may want to use wakelocks to prevent the phone from sleeping
- // before we have finished handling the Intent.
-
- // We create resources anew each time.
- resources = createResources();
- resources.start();
- resources.getLogger().fine("onHandleIntent(%s)", AndroidStrings.toLazyCompactString(intent));
- validator = new AndroidIntentProtocolValidator(resources.getLogger());
-
- try {
- if (intent == null) {
- resources.getLogger().fine("Ignoring null intent");
- return;
- }
-
- // Dispatch the appropriate handler function based on which extra key is set.
- if (intent.hasExtra(ProtocolIntents.CLIENT_DOWNCALL_KEY)) {
- handleClientDowncall(intent.getByteArrayExtra(ProtocolIntents.CLIENT_DOWNCALL_KEY));
- } else if (intent.hasExtra(ProtocolIntents.INTERNAL_DOWNCALL_KEY)) {
- handleInternalDowncall(intent.getByteArrayExtra(ProtocolIntents.INTERNAL_DOWNCALL_KEY));
- } else if (intent.hasExtra(ProtocolIntents.SCHEDULER_KEY)) {
- handleSchedulerEvent(intent.getByteArrayExtra(ProtocolIntents.SCHEDULER_KEY));
- } else {
- resources.getLogger().warning("Received Intent without any recognized extras: %s", intent);
- }
- } finally {
- // Null out resources and validator to prevent accidentally using them in the future before
- // they have been properly re-created.
- resources.stop();
- resources = null;
- validator = null;
- }
- }
-
- /** Handles a request to call a function on the ticl. */
- private void handleClientDowncall(byte[] clientDowncallBytes) {
- // Parse the request.
- final ClientDowncall downcall;
- try {
- downcall = ClientDowncall.parseFrom(clientDowncallBytes);
- } catch (InvalidProtocolBufferException exception) {
- resources.getLogger().warning("Failed parsing ClientDowncall from %s: %s",
- clientDowncallBytes, exception.getMessage());
- return;
- }
- // Validate the request.
- if (!validator.isDowncallValid(downcall)) {
- resources.getLogger().warning("Ignoring invalid downcall message: %s", downcall);
- return;
- }
- resources.getLogger().fine("Handle client downcall: %s", downcall);
-
- // Restore the appropriate Ticl.
- // TODO: what if this is the "wrong" Ticl?
- AndroidInvalidationClientImpl ticl = loadExistingTicl();
- if (ticl == null) {
- resources.getLogger().warning("Dropping client downcall since no Ticl: %s", downcall);
- return;
- }
-
- // Call the appropriate method.
- if (downcall.hasAck()) {
- ticl.acknowledge(AckHandle.newInstance(downcall.getAck().getAckHandle().toByteArray()));
- } else if (downcall.hasStart()) {
- ticl.start();
- } else if (downcall.hasStop()) {
- ticl.stop();
- } else if (downcall.hasRegistrations()) {
- RegistrationDowncall regDowncall = downcall.getRegistrations();
- if (regDowncall.getRegistrationsCount() > 0) {
- List<ObjectId> objects = ProtoConverter.convertToObjectIdList(
- regDowncall.getRegistrationsList());
- ticl.register(objects);
- }
- if (regDowncall.getUnregistrationsCount() > 0) {
- List<ObjectId> objects = ProtoConverter.convertToObjectIdList(
- regDowncall.getUnregistrationsList());
- ticl.unregister(objects);
- }
- } else {
- throw new RuntimeException("Invalid downcall passed validation: " + downcall);
- }
- // If we are stopping the Ticl, then just delete its persisted in-memory state, since no
- // operations on a stopped Ticl are valid. Otherwise, save the Ticl in-memory state to
- // stable storage.
- if (downcall.hasStop()) {
- TiclStateManager.deleteStateFile(this);
- } else {
- TiclStateManager.saveTicl(this, resources.getLogger(), ticl);
- }
- }
-
- /** Handles an internal downcall on the Ticl. */
- private void handleInternalDowncall(byte[] internalDowncallBytes) {
- // Parse the request.
- final InternalDowncall downcall;
- try {
- downcall = InternalDowncall.parseFrom(internalDowncallBytes);
- } catch (InvalidProtocolBufferException exception) {
- resources.getLogger().warning("Failed parsing InternalDowncall from %s: %s",
- internalDowncallBytes, exception.getMessage());
- return;
- }
- // Validate the request.
- if (!validator.isInternalDowncallValid(downcall)) {
- resources.getLogger().warning("Ignoring invalid internal downcall message: %s", downcall);
- return;
- }
- resources.getLogger().fine("Handle internal downcall: %s", downcall);
-
- // Message from the data center; just forward it to the Ticl.
- if (downcall.hasServerMessage()) {
- // We deliver the message regardless of whether the Ticl existed, since we'll want to
- // rewrite persistent state in the case where it did not.
- // TODO: what if this is the "wrong" Ticl?
- AndroidInvalidationClientImpl ticl = TiclStateManager.restoreTicl(this, resources);
- handleServerMessage((ticl != null), downcall.getServerMessage().getData().toByteArray());
- if (ticl != null) {
- TiclStateManager.saveTicl(this, resources.getLogger(), ticl);
- }
- return;
- }
-
- // Network online/offline status change; just forward it to the Ticl.
- if (downcall.hasNetworkStatus()) {
- // Network status changes only make sense for Ticls that do exist.
- // TODO: what if this is the "wrong" Ticl?
- AndroidInvalidationClientImpl ticl = TiclStateManager.restoreTicl(this, resources);
- if (ticl != null) {
- resources.getNetworkListener().onOnlineStatusChange(
- downcall.getNetworkStatus().getIsOnline());
- TiclStateManager.saveTicl(this, resources.getLogger(), ticl);
- }
- return;
- }
-
- // Client network address change; just forward it to the Ticl.
- if (downcall.getNetworkAddrChange()) {
- AndroidInvalidationClientImpl ticl = TiclStateManager.restoreTicl(this, resources);
- if (ticl != null) {
- resources.getNetworkListener().onAddressChange();
- TiclStateManager.saveTicl(this, resources.getLogger(), ticl);
- }
- return;
- }
-
- // Client creation request (meta operation).
- if (downcall.hasCreateClient()) {
- handleCreateClient(downcall.getCreateClient());
- return;
- }
- throw new RuntimeException("Invalid internal downcall passed validation: " + downcall);
- }
-
- /** Handles a {@code createClient} request. */
- private void handleCreateClient(CreateClient createClient) {
- // Ensure no Ticl currently exists.
- TiclStateManager.deleteStateFile(this);
-
- // Create the requested Ticl.
- resources.getLogger().fine("Create client: creating");
- TiclStateManager.createTicl(this, resources, createClient.getClientType(),
- createClient.getClientName().toByteArray(), createClient.getClientConfig(),
- createClient.getSkipStartForTest());
- }
-
- /**
- * Handles a {@code message} for a {@code ticl}. If the {@code ticl} is started, delivers the
- * message. If the {@code ticl} is not started, drops the message and clears the last message send
- * time in the Ticl persistent storage so that the Ticl will send a heartbeat the next time it
- * starts.
- */
- private void handleServerMessage(boolean isTiclStarted, byte[] message) {
- if (isTiclStarted) {
- // Normal case -- message for a started Ticl. Deliver the message.
- resources.getNetworkListener().onMessageReceived(message);
- return;
- }
- // The Ticl isn't started. Rewrite persistent storage so that the last-send-time is a long
- // time ago. The next time the Ticl starts, it will send a message to the data center, which
- // ensures that it will be marked online and that the dropped message (or an equivalent) will
- // be delivered.
- // Android storage implementations are required to execute callbacks inline, so this code
- // all executes synchronously.
- resources.getLogger().fine("Message for unstarted Ticl; rewrite state");
- resources.getStorage().readKey(InvalidationClientCore.CLIENT_TOKEN_KEY,
- new Callback<SimplePair<Status, byte[]>>() {
- @Override
- public void accept(SimplePair<Status, byte[]> result) {
- byte[] stateBytes = result.second;
- if (stateBytes == null) {
- resources.getLogger().info("No persistent state found for client; not rewriting");
- return;
- }
- // Create new state identical to the old state except with a cleared
- // lastMessageSendTimeMs.
- PersistentTiclState state = PersistenceUtils.deserializeState(
- resources.getLogger(), stateBytes, digestFn);
- if (state == null) {
- resources.getLogger().warning("Ignoring invalid Ticl state: %s", stateBytes);
- return;
- }
- PersistentTiclState newState = PersistentTiclState.newBuilder(state)
- .setLastMessageSendTimeMs(0)
- .build();
-
- // Serialize the new state and write it to storage.
- byte[] newClientState = PersistenceUtils.serializeState(newState, digestFn);
- resources.getStorage().writeKey(InvalidationClientCore.CLIENT_TOKEN_KEY, newClientState,
- new Callback<Status>() {
- @Override
- public void accept(Status status) {
- if (status.getCode() != Status.Code.SUCCESS) {
- resources.getLogger().warning(
- "Failed saving rewritten persistent state to storage");
- }
- }
- });
- }
- });
- }
-
- /** Handles a request to call a particular recurring task on the Ticl. */
- private void handleSchedulerEvent(byte[] schedulerEventBytes) {
- // Parse the request.
- final AndroidSchedulerEvent event;
- try {
- event = AndroidSchedulerEvent.parseFrom(schedulerEventBytes);
- } catch (InvalidProtocolBufferException exception) {
- resources.getLogger().warning("Failed parsing SchedulerEvent from %s: %s",
- schedulerEventBytes, exception.getMessage());
- return;
- }
- // Validate the request.
- if (!validator.isSchedulerEventValid(event)) {
- resources.getLogger().warning("Ignoring invalid scheduler event: %s", event);
- return;
- }
- resources.getLogger().fine("Handle scheduler event: %s", event);
-
- // Restore the appropriate Ticl.
- AndroidInvalidationClientImpl ticl = TiclStateManager.restoreTicl(this, resources);
-
- // If the Ticl didn't exist, drop the event.
- if (ticl == null) {
- resources.getLogger().fine("Dropping event %s; Ticl state does not exist",
- event.getEventName());
- return;
- }
-
- // Invoke the appropriate event.
- AndroidInternalScheduler ticlScheduler =
- (AndroidInternalScheduler) resources.getInternalScheduler();
- ticlScheduler.handleSchedulerEvent(event);
-
- // Save the Ticl state to persistent storage.
- TiclStateManager.saveTicl(this, resources.getLogger(), ticl);
- }
-
- /**
- * Returns the existing Ticl from persistent storage, or {@code null} if it does not exist.
- * If it does not exist, raises an error to the listener. This function should be used
- * only when loading a Ticl in response to a client-application call, since it raises an error
- * back to the application.
- */
- private AndroidInvalidationClientImpl loadExistingTicl() {
- AndroidInvalidationClientImpl ticl = TiclStateManager.restoreTicl(this, resources);
- if (ticl == null) {
- informListenerOfPermanentError("Client does not exist on downcall");
- }
- return ticl;
- }
-
- /** Informs the listener of a non-retryable {@code error}. */
- private void informListenerOfPermanentError(final String error) {
- ErrorInfo errorInfo = ErrorInfo.newInstance(0, false, error, null);
- Intent errorIntent = ProtocolIntents.ListenerUpcalls.newErrorIntent(errorInfo);
- IntentForwardingListener.issueIntent(this, errorIntent);
- }
-
- /** Returns the resources used for the current Ticl. */
- AndroidResources getSystemResourcesForTest() {
- return resources;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/TiclStateManager.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/TiclStateManager.java
deleted file mode 100644
index d0ef9523efc..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/TiclStateManager.java
+++ /dev/null
@@ -1,264 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.common.ObjectIdDigestUtils.Sha1DigestFunction;
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.protobuf.ByteString;
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidTiclState;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidTiclState.Metadata;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidTiclStateWithDigest;
-import com.google.protos.ipc.invalidation.ClientProtocol.ApplicationClientIdP;
-import com.google.protos.ipc.invalidation.ClientProtocol.ClientConfigP;
-import com.google.protos.ipc.invalidation.JavaClient.InvalidationClientState;
-
-import android.content.Context;
-
-import java.io.DataInput;
-import java.io.DataInputStream;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.Random;
-
-
-/**
- * Class to save and restore instances of {@code InvalidationClient} to and from stable storage.
- *
- */
-
-public class TiclStateManager {
- /** Name of the file to which Ticl state will be persisted. */
- private static final String TICL_STATE_FILENAME = "android_ticl_service_state.bin";
-
- /**
- * Maximum size of a Ticl state file. Files with larger size will be ignored as invalid. We use
- * this because we allocate an array of bytes of the same size as the Ticl file and want to
- * avoid accidentally allocating huge arrays.
- */
- private static final int MAX_TICL_FILE_SIZE_BYTES = 100 * 1024; // 100 kilobytes
-
- /** Random number generator for created Ticls. */
- private static final Random random = new Random();
-
- /**
- * Restores the Ticl from persistent storage if it exists. Otherwise, returns {@code null}.
- * @param context Android system context
- * @param resources resources to use for the Ticl
- */
- static AndroidInvalidationClientImpl restoreTicl(Context context,
- SystemResources resources) {
- AndroidTiclState state = readTiclState(context, resources.getLogger());
- if (state == null) {
- return null;
- }
- AndroidInvalidationClientImpl ticl = new AndroidInvalidationClientImpl(context, resources,
- random, state);
- setSchedulerId(resources, ticl);
- return ticl;
- }
-
- /** Creates a new Ticl. Persistent stroage must not exist. */
- static void createTicl(Context context, SystemResources resources, int clientType,
- byte[] clientName, ClientConfigP config, boolean skipStartForTest) {
- Preconditions.checkState(!doesStateFileExist(context), "Ticl already exists");
- AndroidInvalidationClientImpl ticl = new AndroidInvalidationClientImpl(context, resources,
- random, clientType, clientName, config);
- if (!skipStartForTest) {
- // Ticls are started when created unless this should be skipped for tests; we allow tests
- // to skip starting Ticls because many integration tests assume that Ticls will not be
- // started when created.
- setSchedulerId(resources, ticl);
- ticl.start();
- }
- saveTicl(context, resources.getLogger(), ticl);
- }
-
- /**
- * Sets the scheduling id on the scheduler in {@code resources} to {@code ticl.getSchedulingId()}.
- */
- private static void setSchedulerId(SystemResources resources,
- AndroidInvalidationClientImpl ticl) {
- AndroidInternalScheduler scheduler =
- (AndroidInternalScheduler) resources.getInternalScheduler();
- scheduler.setTiclId(ticl.getSchedulingId());
- }
-
- /**
- * Saves a Ticl instance to persistent storage.
- *
- * @param context Android system context
- * @param logger logger
- * @param ticl the Ticl instance to save
- */
- static void saveTicl(Context context, Logger logger, AndroidInvalidationClientImpl ticl) {
- FileOutputStream outputStream = null;
- try {
-
- // Create a protobuf with the Ticl state and a digest over it.
- AndroidTiclStateWithDigest digestedState = createDigestedState(ticl);
- AndroidIntentProtocolValidator validator = new AndroidIntentProtocolValidator(logger);
- Preconditions.checkState(validator.isTiclStateValid(digestedState),
- "Produced invalid digested state: %s", digestedState);
-
- // Write the protobuf to storage.
- outputStream = openStateFileForWriting(context);
- outputStream.write(digestedState.toByteArray());
- outputStream.close();
- } catch (FileNotFoundException exception) {
- logger.warning("Could not write Ticl state: %s", exception);
- } catch (IOException exception) {
- logger.warning("Could not write Ticl state: %s", exception);
- } finally {
- try {
- if (outputStream != null) {
- outputStream.close();
- }
- } catch (IOException exception) {
- logger.warning("Exception closing Ticl state file: %s", exception);
- }
- }
- }
-
- /**
- * Reads and returns the Android Ticl state from persistent storage. If the state was missing
- * or invalid, returns {@code null}.
- */
-
- static AndroidTiclState readTiclState(Context context, Logger logger) {
- FileInputStream inputStream = null;
- try {
- inputStream = openStateFileForReading(context);
- DataInput input = new DataInputStream(inputStream);
- long fileSizeBytes = inputStream.getChannel().size();
- if (fileSizeBytes > MAX_TICL_FILE_SIZE_BYTES) {
- logger.warning("Ignoring too-large Ticl state file with size %s > %s",
- fileSizeBytes, MAX_TICL_FILE_SIZE_BYTES);
- } else {
- // Cast to int must be safe due to the above size check.
- byte[] fileData = new byte[(int) fileSizeBytes];
- input.readFully(fileData);
- AndroidTiclStateWithDigest androidState = AndroidTiclStateWithDigest.parseFrom(fileData);
- AndroidIntentProtocolValidator validator = new AndroidIntentProtocolValidator(logger);
-
- // Check the structure of the message (required fields set).
- if (!validator.isTiclStateValid(androidState)) {
- logger.warning("Read AndroidTiclStateWithDigest with invalid structure: %s",
- androidState);
- return null;
- }
- // Validate the digest in the method.
- if (isDigestValid(androidState, logger)) {
- InvalidationClientState state = androidState.getState().getTiclState();
- return androidState.getState();
- } else {
- logger.warning("Android Ticl state failed digest check: %s", androidState);
- }
- }
- } catch (FileNotFoundException exception) {
- logger.info("Ticl state file does not exist: %s", TICL_STATE_FILENAME);
- } catch (InvalidProtocolBufferException exception) {
- logger.warning("Could not read Ticl state: %s", exception);
- } catch (IOException exception) {
- logger.warning("Could not read Ticl state: %s", exception);
- } finally {
- try {
- if (inputStream != null) {
- inputStream.close();
- }
- } catch (IOException exception) {
- logger.warning("Exception closing Ticl state file: %s", exception);
- }
- }
- return null;
- }
-
- /**
- * Returns a {@link AndroidTiclStateWithDigest} containing {@code ticlState} and its computed
- * digest.
- */
- private static AndroidTiclStateWithDigest createDigestedState(
- AndroidInvalidationClientImpl ticl) {
- Sha1DigestFunction digester = new Sha1DigestFunction();
- ApplicationClientIdP ticlAppId = ticl.getApplicationClientIdP();
- Metadata metaData = Metadata.newBuilder()
- .setClientConfig(ticl.getConfig())
- .setClientName(ticlAppId.getClientName())
- .setClientType(ticlAppId.getClientType())
- .setTiclId(ticl.getSchedulingId())
- .build();
- AndroidTiclState state = AndroidTiclState.newBuilder()
- .setMetadata(metaData)
- .setTiclState(ticl.marshal())
- .setVersion(ProtocolIntents.ANDROID_PROTOCOL_VERSION_VALUE).build();
- digester.update(state.toByteArray());
- AndroidTiclStateWithDigest verifiedState = AndroidTiclStateWithDigest.newBuilder()
- .setState(state)
- .setDigest(ByteString.copyFrom(digester.getDigest()))
- .build();
- return verifiedState;
- }
-
- /** Returns whether the digest in {@code state} is correct. */
- private static boolean isDigestValid(AndroidTiclStateWithDigest state, Logger logger) {
- Sha1DigestFunction digester = new Sha1DigestFunction();
- digester.update(state.getState().toByteArray());
- ByteString computedDigest = ByteString.copyFrom(digester.getDigest());
- if (!computedDigest.equals(state.getDigest())) {
- logger.warning("Android Ticl state digest mismatch; computed %s for %s",
- computedDigest, state);
- return false;
- }
- return true;
- }
-
- /** Opens {@link #TICL_STATE_FILENAME} for writing. */
- private static FileOutputStream openStateFileForWriting(Context context)
- throws FileNotFoundException {
- return context.openFileOutput(TICL_STATE_FILENAME, Context.MODE_PRIVATE);
- }
-
- /** Opens {@link #TICL_STATE_FILENAME} for reading. */
- private static FileInputStream openStateFileForReading(Context context)
- throws FileNotFoundException {
- return context.openFileInput(TICL_STATE_FILENAME);
- }
-
- /** Deletes {@link #TICL_STATE_FILENAME}. */
-
- public static void deleteStateFile(Context context) {
- context.deleteFile(TICL_STATE_FILENAME);
- }
-
- /** Returns whether the state file exists, for tests. */
- static boolean doesStateFileExistForTest(Context context) {
- return doesStateFileExist(context);
- }
-
- /** Returns whether the state file exists. */
- private static boolean doesStateFileExist(Context context) {
- return context.getFileStreamPath(TICL_STATE_FILENAME).exists();
- }
-
- private TiclStateManager() {
- // Disallow instantiation.
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidChannelConstants.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidChannelConstants.java
deleted file mode 100644
index bb5aad39b82..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidChannelConstants.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2.channel;
-
-import com.google.ipc.invalidation.common.CommonProtos2;
-import com.google.protos.ipc.invalidation.AndroidChannel.MajorVersion;
-import com.google.protos.ipc.invalidation.ClientProtocol.Version;
-
-/**
- * Constants used by the network channel.
- *
- */
-
-public final class AndroidChannelConstants {
-
- /** Constants used in Intents sent to retrieve auth tokens from the application. */
-
- public static class AuthTokenConstants {
- /**
- * Action requesting that an auth token to send a message be provided. This is the action
- * used in the intent to the application.
- */
-
- public static final String ACTION_REQUEST_AUTH_TOKEN =
- "com.google.ipc.invalidation.AUTH_TOKEN_REQUEST";
-
- /** Extra in an auth token request response providing the pending intent. */
-
- public static final String EXTRA_PENDING_INTENT =
- "com.google.ipc.invalidation.AUTH_TOKEN_PENDING_INTENT";
-
- /**
- * Extra in an auth token request message indicating that the token provided as the value
- * was invalid when last used. This may be set on the intent to the application.
- */
-
- public static final String EXTRA_INVALIDATE_AUTH_TOKEN =
- "com.google.ipc.invalidaton.AUTH_TOKEN_INVALIDATE";
-
- /** Extra in the intent from the application that provides the auth token string. */
-
- public static final String EXTRA_AUTH_TOKEN = "com.google.ipc.invalidation.AUTH_TOKEN";
-
- /** Extra in the intent from the application that provides the auth token type. */
-
- public static final String EXTRA_AUTH_TOKEN_TYPE =
- "com.google.ipc.invalidation.AUTH_TOKEN_TYPE";
-
- /**
- * Extra in the intent from the application that provides the message to send. We store this
- * ourselves in the intent inside the pending intent that we give to the application.
- */
- static final String EXTRA_STORED_MESSAGE = "com.google.ipc.invalidation.AUTH_TOKEN_MSG";
-
- /**
- * Extra in the intent from the application that indicates whether the intent is for a retry
- * after a failed authentication. If we find that an auth token no longer works, we will tell
- * the application to invalidate it, retrieve a new one, and send us back the message and the
- * new token, but we do not want to go into an infinite loop if authentication never succeeds.
- */
- static final String EXTRA_IS_RETRY = "com.google.ipc.invalidation.AUTH_TOKEN_IS_RETRY";
- }
-
- /** Constants used in HTTP requests to the data center. */
- public static class HttpConstants {
- /** The URL of the invalidation channel service */
- public static final String CHANNEL_URL = "https://clients4.google.com/";
-
- /** The MIME content type to use for requests that contain binary protobuf */
- public static final String PROTO_CONTENT_TYPE = "application/x-protobuffer";
-
- /** The relative URL to use to send inbound client requests to the Android frontend */
- public static final String REQUEST_URL = "/invalidation/android/request/";
-
- /**
- * The name of the query parameter that contains the service name that should be used to
- * validate the authentication token provided with the request.
- */
- public static final String SERVICE_PARAMETER = "service";
-
- /**
- * The name of the header that contains the echoed token. This token is included in all C2DM
- * messages to the client and is echoed back under this header on all client HTTP requests.
- */
- public static final String ECHO_HEADER = "echo-token";
- }
-
- /** Constants used in C2DM messages. */
-
- public static class C2dmConstants {
- /**
- * Name of C2DM parameter containing message content. If not set, data is retrieved via
- * the mailbox frontend
- */
-
- public static final String CONTENT_PARAM = "content";
-
- /** Name of the C2DM parameter containing an opaque token to be echoed on HTTP requests. */
-
- public static final String ECHO_PARAM = "echo-token";
- }
-
- /** The channel version expected by this channel implementation. */
- public static final Version CHANNEL_VERSION =
- CommonProtos2.newVersion(MajorVersion.INITIAL.getNumber(), 0);
-
- /**
- * An extra set on an intent to the AndroidMessageSenderService to inform it that a GCM
- * registration id change has occurred. This is sent by the AndroidMessageReceiverService
- * to trigger the sender service to send any buffered messages when a GCM registration id first
- * becomes available.
- * <p>
- * The value associated with this extra is ignored.
- */
- static final String MESSAGE_SENDER_SVC_GCM_REGID_CHANGE =
- "com.google.ipc.invalidation.channel.sender.gcm_regid_change";
-
- private AndroidChannelConstants() {
- // Disallow instantiation.
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidChannelPreferences.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidChannelPreferences.java
deleted file mode 100644
index 2567f7e3ef3..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidChannelPreferences.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2.channel;
-
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.ticl.android2.channel.AndroidChannelConstants.C2dmConstants;
-
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.util.Base64;
-
-
-/** Accessor class for shared preference entries used by the channel. */
-
-public class AndroidChannelPreferences {
- /** Name of the preferences in which channel preferences are stored. */
- private static final String PREFERENCES_NAME = "com.google.ipc.invalidation.gcmchannel";
-
- /**
- * Preferences entry used to buffer the last message sent by the Ticl in the case where a GCM
- * registration id is not currently available.
- */
- private static final String BUFFERED_MSG_PREF = "buffered-msg";
-
- private static final Logger logger = AndroidLogger.forTag("ChannelPrefs");
-
- /** Sets the token echoed on subsequent HTTP requests. */
- static void setEchoToken(Context context, String token) {
- SharedPreferences.Editor editor = getPreferences(context).edit();
-
- // This might fail, but at worst it just means we lose an echo token; the channel
- // needs to be able to handle that anyway since it can never assume an echo token
- // makes it to the client (since the channel can drop messages).
- editor.putString(C2dmConstants.ECHO_PARAM, token);
- commitEditor(editor, "setEchoToken");
- }
-
- /** Returns the echo token that should be included on HTTP requests. */
-
- public static String getEchoToken(Context context) {
- return getPreferences(context).getString(C2dmConstants.ECHO_PARAM, null);
- }
-
- /** Buffers the last message sent by the Ticl. Overwrites any previously buffered message. */
- static void bufferMessage(Context context, byte[] message) {
- SharedPreferences.Editor editor = getPreferences(context).edit();
- String encodedMessage =
- Base64.encodeToString(message, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING);
- editor.putString(BUFFERED_MSG_PREF, encodedMessage);
-
- // This might fail, but at worst we'll just drop a message, which the Ticl must be prepared to
- // handle.
- commitEditor(editor, "bufferMessage");
- }
-
- /**
- * Removes and returns the buffered Ticl message, if any. If no message was buffered, returns
- * {@code null}.
- */
- static byte[] takeBufferedMessage(Context context) {
- SharedPreferences preferences = getPreferences(context);
- String message = preferences.getString(BUFFERED_MSG_PREF, null);
- if (message == null) {
- // No message was buffered.
- return null;
- }
- // There is a message to return. Remove the stored value from the preferences.
- SharedPreferences.Editor editor = preferences.edit();
- editor.remove(BUFFERED_MSG_PREF);
-
- // If this fails, we might send the same message twice, which is fine.
- commitEditor(editor, "takeBufferedMessage");
-
- // Return the decoded message.
- return Base64.decode(message, Base64.URL_SAFE);
- }
-
- /** Returns whether a message has been buffered, for tests. */
- public static boolean hasBufferedMessageForTest(Context context) {
- return getPreferences(context).contains(BUFFERED_MSG_PREF);
- }
-
- /** Returns a new {@link SharedPreferences} instance to access the channel preferences. */
- private static SharedPreferences getPreferences(Context context) {
- return context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
- }
-
- /**
- * Performs a best-effort write of an editor to persistent storage using {@code commit}, logging
- * a warning including {@code writeDescription} if the write fails.
- */
- private static void commitEditor(SharedPreferences.Editor editor, String writeDescription) {
- if (!editor.commit()) {
- logger.warning("Failed writing shared preferences for: %s", writeDescription);
- }
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidMessageReceiverService.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidMessageReceiverService.java
deleted file mode 100644
index e750cc2f52d..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidMessageReceiverService.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2.channel;
-
-import com.google.android.gcm.GCMRegistrar;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.external.client.contrib.MultiplexingGcmListener;
-import com.google.ipc.invalidation.ticl.android2.AndroidTiclManifest;
-import com.google.ipc.invalidation.ticl.android2.ProtocolIntents;
-import com.google.ipc.invalidation.ticl.android2.channel.AndroidChannelConstants.C2dmConstants;
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protos.ipc.invalidation.AndroidChannel.AddressedAndroidMessage;
-
-import android.content.Context;
-import android.content.Intent;
-import android.util.Base64;
-
-
-/**
- * Service that receives messages from using GCM.
- *
- */
-public class AndroidMessageReceiverService extends MultiplexingGcmListener.AbstractListener {
- /*
- * This class is public so that it can be instantiated by the Android runtime. All of the
- * {@code onYYY} methods are called holding a wakelock that will be automatically released when
- * they return, since this is a subclass of {@code AbstractListener}.
- */
-
- /**
- * Receiver for broadcasts by the multiplexed GCM service. It forwards them to
- * AndroidMessageReceiverService.
- */
- public static class Receiver extends MultiplexingGcmListener.AbstractListener.Receiver {
- /* This class is public so that it can be instantiated by the Android runtime. */
- @Override
- protected Class<?> getServiceClass() {
- return AndroidMessageReceiverService.class;
- }
- }
-
- private final Logger logger = AndroidLogger.forTag("MsgRcvrSvc");
-
- public AndroidMessageReceiverService() {
- super("AndroidMessageReceiverService");
- }
-
- @Override
- protected void onMessage(Intent intent) {
- // Forward the message to the Ticl service.
- if (intent.hasExtra(C2dmConstants.CONTENT_PARAM)) {
- String content = intent.getStringExtra(C2dmConstants.CONTENT_PARAM);
- byte[] msgBytes = Base64.decode(content, Base64.URL_SAFE);
- try {
- // Look up the name of the Ticl service class from the manifest.
- String serviceClass = new AndroidTiclManifest(this).getTiclServiceClass();
- AddressedAndroidMessage addrMessage = AddressedAndroidMessage.parseFrom(msgBytes);
- Intent msgIntent =
- ProtocolIntents.InternalDowncalls.newServerMessageIntent(addrMessage.getMessage());
- msgIntent.setClassName(this, serviceClass);
- startService(msgIntent);
- } catch (InvalidProtocolBufferException exception) {
- logger.warning("Failed parsing inbound message: %s", exception);
- }
- } else {
- logger.fine("GCM Intent has no message content: %s", intent);
- }
-
- // Store the echo token.
- String echoToken = intent.getStringExtra(C2dmConstants.ECHO_PARAM);
- if (echoToken != null) {
- AndroidChannelPreferences.setEchoToken(this, echoToken);
- }
- }
-
- @Override
- protected void onRegistered(String registrationId) {
- // Inform the sender service that the registration id has changed. If the sender service
- // had buffered a message because no registration id was previously available, this intent
- // will cause it to send that message.
- Intent sendBuffered = new Intent();
- final String ignoredData = "";
- sendBuffered.putExtra(AndroidChannelConstants.MESSAGE_SENDER_SVC_GCM_REGID_CHANGE, ignoredData);
- sendBuffered.setClass(this, AndroidMessageSenderService.class);
- startService(sendBuffered);
-
- // Inform the Ticl service that the registration id has changed. This will cause it to send
- // a message to the data center and update the GCM registration id stored at the data center.
- Intent updateServer = ProtocolIntents.InternalDowncalls.newNetworkAddrChangeIntent();
- updateServer.setClassName(this, new AndroidTiclManifest(this).getTiclServiceClass());
- startService(updateServer);
- }
-
- @Override
- protected void onUnregistered(String registrationId) {
- // Nothing to do.
- }
-
- @Override
- protected void onDeletedMessages(int total) {
- // This method must be implemented if we start using non-collapsable messages with GCM. For
- // now, there is nothing to do.
- }
-
- /**
- * Initializes GCM as a convenience method for tests. In production, applications should handle
- * this.
- */
- public static void initializeGcmForTest(Context context, Logger logger, String senderId) {
- // Initialize GCM.
- GCMRegistrar.checkDevice(context);
- GCMRegistrar.checkManifest(context);
- String regId = GCMRegistrar.getRegistrationId(context);
- if (regId.equals("")) {
- logger.info("Not registered with GCM; registering");
- GCMRegistrar.register(context, senderId);
- } else {
- logger.fine("Already registered with GCM: %s", regId);
- }
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidMessageSenderService.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidMessageSenderService.java
deleted file mode 100644
index f9e340f5cda..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidMessageSenderService.java
+++ /dev/null
@@ -1,374 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2.channel;
-
-import com.google.android.gcm.GCMRegistrar;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
-import com.google.ipc.invalidation.common.CommonProtos2;
-import com.google.ipc.invalidation.external.client.SystemResources.Logger;
-import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
-import com.google.ipc.invalidation.ticl.android2.AndroidIntentProtocolValidator;
-import com.google.ipc.invalidation.ticl.android2.ProtocolIntents;
-import com.google.ipc.invalidation.ticl.android2.channel.AndroidChannelConstants.AuthTokenConstants;
-import com.google.ipc.invalidation.ticl.android2.channel.AndroidChannelConstants.HttpConstants;
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protos.ipc.invalidation.AndroidService.AndroidNetworkSendRequest;
-import com.google.protos.ipc.invalidation.Channel.NetworkEndpointId;
-
-import android.app.IntentService;
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Build;
-import android.util.Base64;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.HttpURLConnection;
-import java.net.MalformedURLException;
-import java.net.ProtocolException;
-import java.net.URL;
-
-
-/**
- * Service that sends messages to the data center using HTTP POSTs authenticated as a Google
- * account.
- * <p>
- * Messages are sent as byte-serialized {@code ClientToServerMessage} protocol buffers.
- * Additionally, the POST requests echo the latest value of the echo token received on C2DM
- * messages from the data center.
- *
- */
-public class AndroidMessageSenderService extends IntentService {
- /* This class is public so that it can be instantiated by the Android runtime. */
-
- /**
- * Client key used in network endpoint ids. We only have one client at present, so there is no
- * need for a key.
- */
- private static final String NO_CLIENT_KEY = "";
-
- /** An override of the URL, for testing. */
- private static String channelUrlForTest = null;
-
- private final Logger logger = AndroidLogger.forTag("MsgSenderSvc");
-
- private final AndroidIntentProtocolValidator validator =
- new AndroidIntentProtocolValidator(logger);
-
- /** The last message sent, for tests. */
- public static byte[] lastTiclMessageForTest = null;
-
- public AndroidMessageSenderService() {
- super("AndroidNetworkService");
- }
-
- @Override
- public void onCreate() {
- super.onCreate();
-
- // HTTP connection reuse was buggy pre-Froyo, so disable it on those platforms.
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
- System.setProperty("http.keepAlive", "false");
- }
- }
-
- @Override
- protected void onHandleIntent(Intent intent) {
- if (intent.hasExtra(ProtocolIntents.OUTBOUND_MESSAGE_KEY)) {
- // Request from the Ticl service to send a message.
- handleOutboundMessage(intent.getByteArrayExtra(ProtocolIntents.OUTBOUND_MESSAGE_KEY));
- } else if (intent.hasExtra(AndroidChannelConstants.AuthTokenConstants.EXTRA_AUTH_TOKEN)) {
- // Reply from the app with an auth token and a message to send.
- handleAuthTokenResponse(intent);
- } else if (intent.hasExtra(AndroidChannelConstants.MESSAGE_SENDER_SVC_GCM_REGID_CHANGE)) {
- handleGcmRegIdChange();
- } else {
- logger.warning("Ignoring intent: %s", intent);
- }
- }
-
- /**
- * Handles a request to send a message to the data center. Validates the message and sends
- * an intent to the application to obtain an auth token to use on the HTTP request to the
- * data center.
- */
- private void handleOutboundMessage(byte[] sendRequestBytes) {
- // Parse and validate the send request.
- final AndroidNetworkSendRequest sendRequest;
- try {
- sendRequest = AndroidNetworkSendRequest.parseFrom(sendRequestBytes);
- } catch (InvalidProtocolBufferException exception) {
- logger.warning("Failed parsing AndroidNetworkSendRequest from %s: %s",
- sendRequestBytes, exception);
- return;
- }
- if (!validator.isNetworkSendRequestValid(sendRequest)) {
- logger.warning("Ignoring invalid send request: %s", sendRequest);
- return;
- }
-
- // Request an auth token from the application to use when sending the message.
- byte[] message = sendRequest.getMessage().toByteArray();
- requestAuthTokenForMessage(message, null);
- }
-
- /**
- * Requests an auth token from the application to use to send {@code message} to the data
- * center.
- * <p>
- * If not {@code null}, {@code invalidAuthToken} is an auth token that was previously
- * found to be invalid. The intent sent to the application to request the new token will include
- * the invalid token so that the application can invalidate it in the {@code AccountManager}.
- */
- private void requestAuthTokenForMessage(byte[] message, String invalidAuthToken) {
- /*
- * Send an intent requesting an auth token. This intent will contain a pending intent
- * that the recipient can use to send back the token (by attaching the token as a string
- * extra). That pending intent will also contain the message that we were just asked to send,
- * so that it will be echoed back to us with the token. This avoids our having to persist
- * the message while waiting for the token.
- */
-
- // This is the intent that the application will send back to us (the pending intent allows
- // it to send the intent). It contains the stored message. We require that it be delivered to
- // this class only, as a security check.
- Intent tokenResponseIntent = new Intent(this, getClass());
- tokenResponseIntent.putExtra(AuthTokenConstants.EXTRA_STORED_MESSAGE, message);
-
- // If we have an invalid auth token, set a bit in the intent that the application will send
- // back to us. This will let us know that it is a retry; if sending subsequently fails again,
- // we will not do any further retries.
- tokenResponseIntent.putExtra(AuthTokenConstants.EXTRA_IS_RETRY, invalidAuthToken != null);
-
- // The pending intent allows the application to send us the tokenResponseIntent.
- PendingIntent pendingIntent = PendingIntent.getService(
- this, message.hashCode(), tokenResponseIntent, PendingIntent.FLAG_ONE_SHOT);
-
- // We send the pending intent as an extra in a normal intent to the application. We require that
- // the intent be delivered only within this package, as a security check. The application must
- // define a service with an intent filter that matches the ACTION_REQUEST_AUTH_TOKEN in order
- // to receive this intent.
- Intent requestTokenIntent = new Intent(AuthTokenConstants.ACTION_REQUEST_AUTH_TOKEN);
- requestTokenIntent.setPackage(getPackageName());
- requestTokenIntent.putExtra(AuthTokenConstants.EXTRA_PENDING_INTENT, pendingIntent);
- if (invalidAuthToken != null) {
- requestTokenIntent.putExtra(AuthTokenConstants.EXTRA_INVALIDATE_AUTH_TOKEN, invalidAuthToken);
- }
- startService(requestTokenIntent);
- }
-
- /**
- * Handles an intent received from the application that contains both a message to send and
- * an auth token and type to use when sending it. This is called when the reply to the intent
- * sent in {@link #requestAuthTokenForMessage(byte[], String)} is received.
- */
- private void handleAuthTokenResponse(Intent intent) {
- if (!(intent.hasExtra(AuthTokenConstants.EXTRA_STORED_MESSAGE)
- && intent.hasExtra(AuthTokenConstants.EXTRA_AUTH_TOKEN)
- && intent.hasExtra(AuthTokenConstants.EXTRA_AUTH_TOKEN_TYPE)
- && intent.hasExtra(AuthTokenConstants.EXTRA_IS_RETRY))) {
- logger.warning("auth-token-response intent missing fields: %s, %s",
- intent, intent.getExtras());
- return;
- }
- boolean isRetryForInvalidAuthToken =
- intent.getBooleanExtra(AuthTokenConstants.EXTRA_IS_RETRY, false);
- deliverOutboundMessage(
- intent.getByteArrayExtra(AuthTokenConstants.EXTRA_STORED_MESSAGE),
- intent.getStringExtra(AuthTokenConstants.EXTRA_AUTH_TOKEN),
- intent.getStringExtra(AuthTokenConstants.EXTRA_AUTH_TOKEN_TYPE),
- isRetryForInvalidAuthToken);
- }
-
- /**
- * Sends {@code outgoingMessage} to the data center as a serialized ClientToServerMessage using an
- * HTTP POST.
- * <p>
- * If the HTTP POST fails due to an authentication failure and this is not a retry for an invalid
- * auth token ({@code isRetryForInvalidAuthToken} is {@code false}), then it will call
- * {@link #requestAuthTokenForMessage(byte[], String)} with {@code authToken} to invalidate the
- * token and retry.
- *
- * @param authToken the auth token to use in the HTTP POST
- * @param authTokenType the type of the auth token
- */
- private void deliverOutboundMessage(byte[] outgoingMessage, String authToken,
- String authTokenType, boolean isRetryForInvalidAuthToken) {
- NetworkEndpointId networkEndpointId = getNetworkEndpointId(this, logger);
- if (networkEndpointId == null) {
- // No GCM registration; buffer the message to send when we become registered.
- logger.info("Buffering message to the data center: no GCM registration id");
- AndroidChannelPreferences.bufferMessage(this, outgoingMessage);
- return;
- }
- logger.fine("Delivering outbound message: %s bytes", outgoingMessage.length);
- lastTiclMessageForTest = outgoingMessage;
- URL url = null;
- HttpURLConnection urlConnection = null;
- try {
- // Open the connection.
- url = buildUrl(authTokenType, networkEndpointId);
- urlConnection = createUrlConnectionForPost(this, url, authToken);
- urlConnection.setFixedLengthStreamingMode(outgoingMessage.length);
- urlConnection.connect();
-
- // Write the outgoing message.
- urlConnection.getOutputStream().write(outgoingMessage);
-
- // Consume all of the response. We do not do anything with the response (except log it for
- // non-200 response codes), and do not expect any, but certain versions of the Apache HTTP
- // library have a bug that causes connections to leak when the response is not fully consumed;
- // out of sheer paranoia, we do the same thing here.
- String response = readCompleteStream(urlConnection.getInputStream());
-
- // Retry authorization failures and log other non-200 response codes.
- final int responseCode = urlConnection.getResponseCode();
- switch (responseCode) {
- case HttpURLConnection.HTTP_OK:
- case HttpURLConnection.HTTP_NO_CONTENT:
- break;
- case HttpURLConnection.HTTP_UNAUTHORIZED:
- if (!isRetryForInvalidAuthToken) {
- // If we had an auth failure and this is not a retry of an auth failure, then ask the
- // application to invalidate authToken and give us a new one with which to retry. We
- // check that this attempt was not a retry to avoid infinite loops if authorization
- // always fails.
- requestAuthTokenForMessage(outgoingMessage, authToken);
- }
- break;
- default:
- logger.warning("Unexpected response code %s for HTTP POST to %s; response = %s",
- responseCode, url, response);
- }
- } catch (MalformedURLException exception) {
- logger.warning("Malformed URL: %s", exception);
- } catch (IOException exception) {
- logger.warning("IOException sending to the data center (%s): %s", url, exception);
- } finally {
- if (urlConnection != null) {
- urlConnection.disconnect();
- }
- }
- }
-
- /**
- * Handles a change in the GCM registration id by sending the buffered client message (if any)
- * to the data center.
- */
- private void handleGcmRegIdChange() {
- byte[] bufferedMessage = AndroidChannelPreferences.takeBufferedMessage(this);
- if (bufferedMessage != null) {
- // Rejoin the start of the code path that handles sending outbound messages.
- requestAuthTokenForMessage(bufferedMessage, null);
- }
- }
-
- /**
- * Returns a URL to use to send a message to the data center.
- *
- * @param authTokenType type of authentication token that will be used in the request
- * @param networkEndpointId network id of the client
- */
- private static URL buildUrl(String authTokenType, NetworkEndpointId networkEndpointId)
- throws MalformedURLException {
- StringBuilder urlBuilder = new StringBuilder();
-
- // Build base URL that targets the inbound request service with the encoded network endpoint
- // id.
- urlBuilder.append((channelUrlForTest != null) ? channelUrlForTest : HttpConstants.CHANNEL_URL);
- urlBuilder.append(HttpConstants.REQUEST_URL);
- urlBuilder.append(base64Encode(networkEndpointId.toByteArray()));
-
- // Add query parameter indicating the service to authenticate against
- urlBuilder.append('?');
- urlBuilder.append(HttpConstants.SERVICE_PARAMETER);
- urlBuilder.append('=');
- urlBuilder.append(authTokenType);
- return new URL(urlBuilder.toString());
- }
-
- /**
- * Returns an {@link HttpURLConnection} to use to POST a message to the data center. Sets
- * the content-type and user-agent headers; also sets the echo token header if we have an
- * echo token.
- *
- * @param context Android context
- * @param url URL to which to post
- * @param authToken auth token to provide in the request header
- */
-
- public static HttpURLConnection createUrlConnectionForPost(Context context, URL url,
- String authToken) throws IOException {
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- try {
- connection.setRequestMethod("POST");
- } catch (ProtocolException exception) {
- throw new RuntimeException("Cannot set request method to POST: " + exception);
- }
- connection.setDoOutput(true);
- connection.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
- connection.setRequestProperty("Content-Type", HttpConstants.PROTO_CONTENT_TYPE);
- connection.setRequestProperty("User-Agent",
- context.getApplicationInfo().className + "(" + Build.VERSION.RELEASE + ")");
- String echoToken = AndroidChannelPreferences.getEchoToken(context);
- if (echoToken != null) {
- // If we have a token to echo to the server, echo it.
- connection.setRequestProperty(HttpConstants.ECHO_HEADER, echoToken);
- }
- return connection;
- }
-
- /** Reads and all data from {@code in}. */
- private static String readCompleteStream(InputStream in) throws IOException {
- StringBuffer buffer = new StringBuffer();
- BufferedReader reader = new BufferedReader(new InputStreamReader(in));
- String line;
- while ((line = reader.readLine()) != null) {
- buffer.append(line);
- }
- return buffer.toString();
- }
-
- /** Returns a base-64 encoded version of {@code bytes}. */
- private static String base64Encode(byte[] bytes) {
- return Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING);
- }
-
- /** Returns the network id for this channel, or {@code null} if one cannot be determined. */
-
-
- public static NetworkEndpointId getNetworkEndpointId(Context context, Logger logger) {
- String registrationId = GCMRegistrar.getRegistrationId(context);
- if (Strings.isNullOrEmpty(registrationId)) {
- // No registration with GCM; we cannot compute a network id. The GCM documentation says the
- // string is never null, but we'll be paranoid.
- logger.warning("No GCM registration id; cannot determine our network endpoint id: %s",
- registrationId);
- return null;
- }
- return CommonProtos2.newAndroidEndpointId(registrationId,
- NO_CLIENT_KEY, context.getPackageName(), AndroidChannelConstants.CHANNEL_VERSION);
- }
-
- /** Sets the channel url to {@code url}, for tests. */
- public static void setChannelUrlForTest(String url) {
- channelUrlForTest = Preconditions.checkNotNull(url);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidNetworkChannel.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidNetworkChannel.java
deleted file mode 100644
index 963199b88d2..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/channel/AndroidNetworkChannel.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.ticl.android2.channel;
-
-import com.google.common.base.Preconditions;
-import com.google.ipc.invalidation.external.client.SystemResources;
-import com.google.ipc.invalidation.ticl.TestableNetworkChannel;
-import com.google.ipc.invalidation.ticl.android2.ProtocolIntents;
-import com.google.ipc.invalidation.ticl.android2.ResourcesFactory.AndroidResources;
-import com.google.protos.ipc.invalidation.Channel.NetworkEndpointId;
-
-import android.content.Context;
-import android.content.Intent;
-
-/**
- * A network channel for Android that receives messages by GCM and that sends messages
- * using HTTP.
- *
- */
-public class AndroidNetworkChannel implements TestableNetworkChannel {
- private final Context context;
- private AndroidResources resources;
-
- public AndroidNetworkChannel(Context context) {
- this.context = Preconditions.checkNotNull(context);
- }
-
- @Override
- public void sendMessage(byte[] outgoingMessage) {
- Intent intent = ProtocolIntents.newOutboundMessageIntent(outgoingMessage);
- intent.setClassName(context, AndroidMessageSenderService.class.getName());
- context.startService(intent);
- }
-
- @Override
- public void setListener(NetworkListener listener) {
- resources.setNetworkListener(listener);
- }
-
- @Override
- public void setSystemResources(SystemResources resources) {
- this.resources = (AndroidResources) Preconditions.checkNotNull(resources);
- }
-
- @Override
- public NetworkEndpointId getNetworkIdForTest() {
- return AndroidMessageSenderService.getNetworkEndpointId(context, resources.getLogger());
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/BaseLogger.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/BaseLogger.java
deleted file mode 100644
index 8d5fa507be6..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/BaseLogger.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.util;
-
-import java.util.logging.Level;
-
-/**
- * A basic formatting logger interface.
- *
- */
-public interface BaseLogger {
- /**
- * Logs a message.
- *
- * @param level the level at which the message should be logged (e.g., {@code INFO})
- * @param template the string to log, optionally containing %s sequences
- * @param args variables to substitute for %s sequences in {@code template}
- */
- void log(Level level, String template, Object... args);
-
- /**
- * Returns true iff statements at {@code level} are not being suppressed.
- */
- boolean isLoggable(Level level);
-
- /**
- * Logs a message at the SEVERE level.
- * See specs of {@code #log} for the parameters.
- */
- void severe(String template, Object...args);
-
- /**
- * Logs a message at the WARNING level.
- * See specs of {@code #log} for the parameters.
- */
- void warning(String template, Object...args);
-
- /**
- * Logs a message at the INFO level.
- * See specs of {@code #log} for the parameters.
- */
- void info(String template, Object...args);
-
- /**
- * Logs a message at the FINE level.
- * See specs of {@code #log} for the parameters.
- */
- void fine(String template, Object...args);
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Box.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Box.java
deleted file mode 100644
index f57c889d5c5..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Box.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.util;
-
-import com.google.common.base.Supplier;
-
-/**
- * Container for a single arbitrary value. Useful when a nested callback needs
- * to modify a primitive type, which is ordinarily not possible as variables
- * available to nested callbacks need to be declared final.
- *
- * @param <T> Type of the value being boxed.
- *
- */
-public class Box<T> implements Supplier<T> {
-
- /** Contents of the box. */
- private T value;
-
- /** Constructs a box with the given initial {@code value}. */
- public Box(T value) {
- this.value = value;
- }
-
- /**
- * Returns a supplier for the given value. Note that such a getter's internal value cannot be
- * changed (by definition).
- */
- public static <T> Supplier<T> createSupplier(final T value) {
- return Box.of(value);
- }
-
- /** Constructs a Box with {@code null} as the value. */
- public Box() {
- this.value = null;
- }
-
- /** Constructs and returns a {@code Box} that wraps {@code objectValue}. */
- public static <T> Box<T> of(T objectValue) {
- return new Box<T>(objectValue);
- }
-
- public void set(T objectValue) {
- this.value = objectValue;
- }
-
- @Override
- public T get() {
- return value;
- }
-
- @Override
- public String toString() {
- return (value == null) ? null : value.toString();
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Bytes.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Bytes.java
deleted file mode 100644
index d82bba785af..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Bytes.java
+++ /dev/null
@@ -1,332 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.util;
-
-import com.google.common.base.Preconditions;
-import com.google.protobuf.ByteString;
-
-import java.nio.ByteBuffer;
-import java.util.Arrays;
-
-
-/**
- * A class that encapsulates a (fixed size) sequence of bytes and provides a
- * equality (along with hashcode) method that considers two sequences to be
- * equal if they have the same contents. Borrowed from protobuf's ByteString
- *
- */
-public class Bytes extends InternalBase implements Comparable<Bytes> {
-
- public static final Bytes EMPTY_BYTES = new Bytes(new byte[0]);
-
- /**
- * Three arrays that store the representation of each character from 0 to 255.
- * The ith number's octal representation is: CHAR_OCTAL_STRINGS1[i],
- * CHAR_OCTAL_STRINGS2[i], CHAR_OCTAL_STRINGS3[i]
- * <p>
- * E.g., if the number 128, these arrays contain 2, 0, 0 at index 128. We use
- * 3 char arrays instead of an array of strings since the code path for a
- * character append operation is quite a bit shorter than the append operation
- * for strings.
- */
- private static final char[] CHAR_OCTAL_STRINGS1 = new char[256];
- private static final char[] CHAR_OCTAL_STRINGS2 = new char[256];
- private static final char[] CHAR_OCTAL_STRINGS3 = new char[256];
-
- /** The actual sequence. */
- private final byte[] bytes;
-
- /** Cached hash */
- private volatile int hash = 0;
-
- static {
- // Initialize the array with the Octal string values so that we do not have
- // to do String.format for every byte during runtime.
- for (int i = 0; i < CHAR_OCTAL_STRINGS1.length; i++) {
- String value = String.format("\\%03o", i);
- CHAR_OCTAL_STRINGS1[i] = value.charAt(1);
- CHAR_OCTAL_STRINGS2[i] = value.charAt(2);
- CHAR_OCTAL_STRINGS3[i] = value.charAt(3);
- }
- }
-
- public Bytes(byte[] bytes) {
- this.bytes = bytes;
- }
-
- /**
- * Creates a Bytes object with the contents of {@code array1} followed by the
- * contents of {@code array2}.
- */
- public Bytes(byte[] array1, byte[] array2) {
- Preconditions.checkNotNull(array1);
- Preconditions.checkNotNull(array2);
- ByteBuffer buffer = ByteBuffer.allocate(array1.length + array2.length);
- buffer.put(array1);
- buffer.put(array2);
- this.bytes = buffer.array();
- }
-
- /**
- * Creates a Bytes object with the contents of {@code b1} followed by the
- * contents of {@code b2}.
- */
- public Bytes(Bytes b1, Bytes b2) {
- this(b1.bytes, b2.bytes);
- }
-
- public Bytes(byte b) {
- this.bytes = new byte[1];
- bytes[0] = b;
- }
-
- public Bytes(ByteString byteString) {
- this(byteString.toByteArray());
- }
-
- /**
- * Gets the byte at the given index.
- *
- * @throws ArrayIndexOutOfBoundsException {@code index} is < 0 or >= size
- */
- public byte byteAt(final int index) {
- return bytes[index];
- }
-
- /**
- * Gets the number of bytes.
- */
- public int size() {
- return bytes.length;
- }
-
- /**
- * Returns the internal byte array.
- */
- public byte[] getByteArray() {
- return bytes;
- }
-
- /** Converts this to a byte string. */
- public ByteString toByteString() {
- return ByteString.copyFrom(getByteArray());
- }
-
- /**
- * Returns a new {@code Bytes} containing the given subrange of bytes [{@code
- * from}, {@code to}).
- */
- public Bytes subsequence(int from, int to) {
- // Identical semantics to Arrays.copyOfRange() but implemented manually
- // so runs on Froyo (JDK 1.5).
- int newLength = to - from;
- if (newLength < 0) {
- throw new IllegalArgumentException(from + " > " + to);
- }
- byte[] copy = new byte[newLength];
- System.arraycopy(bytes, from, copy, 0, Math.min(bytes.length - from, newLength));
- return new Bytes(copy);
- }
-
- @Override
- public boolean equals(final Object o) {
- if (o == this) {
- return true;
- }
-
- if (!(o instanceof Bytes)) {
- return false;
- }
-
- final Bytes other = (Bytes) o;
- return Arrays.equals(bytes, other.bytes);
- }
-
- @Override
- public int hashCode() {
- int h = hash;
-
- // If the hash has been not computed, go through each byte and compute it.
- if (h == 0) {
- final byte[] thisBytes = bytes;
- final int size = bytes.length;
-
- h = size;
- for (int i = 0; i < size; i++) {
- h = h * 31 + thisBytes[i];
- }
- if (h == 0) {
- h = 1;
- }
-
- hash = h;
- }
-
- return h;
- }
-
- /**
- * Returns whether these bytes are a prefix (either proper or improper) of
- * {@code other}.
- */
- public boolean isPrefixOf(Bytes other) {
- Preconditions.checkNotNull(other);
- if (size() > other.size()) {
- return false;
- }
- for (int i = 0; i < size(); ++i) {
- if (bytes[i] != other.bytes[i]) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Returns whether these bytes are a suffix (either proper or improper) of
- * {@code other}.
- */
- public boolean isSuffixOf(Bytes other) {
- Preconditions.checkNotNull(other);
- int diff = other.size() - size();
- if (diff < 0) {
- return false;
- }
- for (int i = 0; i < size(); ++i) {
- if (bytes[i] != other.bytes[i + diff]) {
- return false;
- }
- }
- return true;
- }
-
- @Override
- public int compareTo(Bytes other) {
- return compare(bytes, other.bytes);
- }
-
- /**
- * Same specs as Bytes.compareTo except for the byte[] type. Null arrays are ordered before
- * non-null arrays.
- */
- public static int compare(byte[] first, byte[] second) {
- // Order null arrays before non-null arrays.
- if (first == null) {
- return (second == null) ? 0 : -1;
- }
- if (second == null) {
- return 1;
- }
-
- int minLength = Math.min(first.length, second.length);
- for (int i = 0; i < minLength; i++) {
- if (first[i] != second[i]) {
- int firstByte = first[i] & 0xff;
- int secondByte = second[i] & 0xff;
- return firstByte - secondByte;
- }
- }
- // At this point, either both arrays are equal length or one of the arrays has ended.
- // * If the arrays are of equal length, they must be identical (else we would have
- // returned the correct value above
- // * If they are not of equal length, the one with the longer length is greater.
- return first.length - second.length;
- }
-
- /** Compares lexicographic order of {@code first} and {@code second}. */
- public static int compare(ByteString first, ByteString second) {
- Preconditions.checkNotNull(first);
- Preconditions.checkNotNull(second);
-
- // Note: size() is O(1) on ByteString.
- for (int i = 0; i < first.size(); ++i) {
- if (i == second.size()) {
- // 'first' is longer than 'second' (logically, think of 'second' as padded with special
- // 'blank' symbols that are smaller than any other symbol per the usual lexicographic
- // ordering convention.)
- return +1;
- }
- byte firstByte = first.byteAt(i);
- byte secondByte = second.byteAt(i);
- if (firstByte != secondByte) {
- return (firstByte & 0xff) - (secondByte & 0xff);
- }
- }
- // We ran through both strings and found no differences. If 'second' is longer than 'first',
- // then we return -1. Otherwise, it implies that both strings have been consumed and no
- // differences discovered in which case we return 0.
- return (second.size() > first.size()) ? -1 : 0;
- }
-
- /**
- * Renders the bytes as a string in standard bigtable ascii / octal mix
- * compatible with bt and returns it. Borrowed from Bigtable's
- * Util.keyToString().
- */
- public static String toString(ByteString bytes) {
- return toString(bytes.toByteArray());
- }
-
- /**
- * Renders the bytes as a string in standard bigtable ascii / octal mix
- * compatible with bt and returns it. Borrowed from Bigtable's
- * Util.keyToString().
- */
- public static String toString(byte[] bytes) {
- return toCompactString(new TextBuilder(), bytes).toString();
- }
-
- /**
- * Renders the bytes as a string in standard bigtable ascii / octal mix
- * compatible with bt and adds it to builder. Borrowed from Bigtable's
- * Util.keyToString().
- */
- @Override
- public void toCompactString(TextBuilder builder) {
- toCompactString(builder, bytes);
- }
-
- /**
- * Renders the bytes as a string in standard bigtable ascii / octal mix
- * compatible with bt and adds it to builder. Borrowed from Bigtable's
- * Util.keyToString(). Returns {@code builder}.
- */
- public static TextBuilder toCompactString(TextBuilder builder, byte[] bytes) {
- for (byte c : bytes) {
- switch(c) {
- case '\n': builder.append('\\'); builder.append('n'); break;
- case '\r': builder.append('\\'); builder.append('r'); break;
- case '\t': builder.append('\\'); builder.append('t'); break;
- case '\"': builder.append('\\'); builder.append('"'); break;
- case '\\': builder.append('\\'); builder.append('\\'); break;
- default:
- if ((c >= 32) && (c < 127) && c != '\'') {
- builder.append((char) c);
- } else {
- int byteValue = c;
- if (c < 0) {
- byteValue = c + 256;
- }
- builder.append('\\');
- builder.append(CHAR_OCTAL_STRINGS1[byteValue]);
- builder.append(CHAR_OCTAL_STRINGS2[byteValue]);
- builder.append(CHAR_OCTAL_STRINGS3[byteValue]);
- }
- }
- }
- return builder;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/ExponentialBackoffDelayGenerator.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/ExponentialBackoffDelayGenerator.java
deleted file mode 100644
index 75b86482609..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/ExponentialBackoffDelayGenerator.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.util;
-
-import com.google.common.base.Preconditions;
-
-import java.util.Random;
-
-/**
- * Class that generates successive intervals for random exponential backoff. Class tracks a
- * "high water mark" which is doubled each time {@code getNextDelay} is called; each call to
- * {@code getNextDelay} returns a value uniformly randomly distributed between 0 (inclusive) and the
- * high water mark (exclusive). Note that this class does not dictate the time units for which the
- * delay is computed.
- *
- */
-public class ExponentialBackoffDelayGenerator {
-
- /** Initial allowed delay time. */
- private final int initialMaxDelay;
-
- /** Maximum allowed delay time as a factor of {@code initialMaxDelay} */
- private final int maxExponentialFactor;
-
- /** Next delay time to use. */
- private int currentMaxDelay;
-
- /** If the first call to {@code getNextDelay} has been made after reset. */
- private boolean inRetryMode;
-
- private final Random random;
-
- /**
- * Creates a generator with the given initial delay and the maximum delay (in terms of a factor of
- * the initial delay).
- */
- public ExponentialBackoffDelayGenerator(Random random, int initialMaxDelay,
- int maxExponentialFactor) {
- Preconditions.checkArgument(maxExponentialFactor > 0, "max factor must be positive");
- this.random = Preconditions.checkNotNull(random);
- this.maxExponentialFactor = maxExponentialFactor;
- this.initialMaxDelay = initialMaxDelay;
- Preconditions.checkArgument(initialMaxDelay > 0, "initial delay must be positive");
- reset();
- }
-
- /**
- * A constructor to restore a generator from saved state. Creates a generator with the given
- * initial delay and the maximum delay (in terms of a factor of the initial delay).
- *
- * @param currentMaxDelay saved current max delay
- * @param inRetryMode saved in-retry-mode value
- */
- protected ExponentialBackoffDelayGenerator(Random random, int initialMaxDelay,
- int maxExponentialFactor, int currentMaxDelay, boolean inRetryMode) {
- this(random, initialMaxDelay, maxExponentialFactor);
- this.currentMaxDelay = currentMaxDelay;
- this.inRetryMode = inRetryMode;
- }
-
- /** Resets the exponential backoff generator to start delays at the initial delay. */
- public void reset() {
- this.currentMaxDelay = initialMaxDelay;
- this.inRetryMode = false;
- }
-
- /** Gets the next delay interval to use. */
- public int getNextDelay() {
- int delay = 0; // After a reset, the delay is 0.
- if (inRetryMode) {
-
- // Generate the delay in the range [1, currentMaxDelay].
- delay = random.nextInt(currentMaxDelay) + 1;
-
- // Adjust the max for the next run.
- int maxDelay = initialMaxDelay * maxExponentialFactor;
- if (currentMaxDelay <= maxDelay) { // Guard against overflow.
- currentMaxDelay *= 2;
- if (currentMaxDelay > maxDelay) {
- currentMaxDelay = maxDelay;
- }
- }
- }
- inRetryMode = true;
- return delay;
- }
-
- protected int getCurrentMaxDelay() {
- return currentMaxDelay;
- }
-
- protected boolean getInRetryMode() {
- return inRetryMode;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Formatter.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Formatter.java
deleted file mode 100644
index 147853dd1bc..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Formatter.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.util;
-
-/**
- * A set of utilities needed to format strings by the external class implementations.
- *
- */
-public class Formatter {
-
- /**
- * (Borrowed from the Preconditions code).
- * Substitutes each {@code %s} in {@code template} with an argument. These
- * are matched by position - the first {@code %s} gets {@code args[0]}, etc.
- * If there are more arguments than placeholders, the unmatched arguments will
- * be appended to the end of the formatted message in square braces.
- *
- * @param template a non-null string containing 0 or more {@code %s}
- * placeholders.
- * @param args the arguments to be substituted into the message
- * template. Arguments are converted to strings using
- * {@link String#valueOf(Object)}. Arguments can be null.
- */
- public static String format(String template, Object... args) {
- template = String.valueOf(template); // null -> "null"
-
- // start substituting the arguments into the '%s' placeholders
- StringBuilder builder = new StringBuilder(
- template.length() + 16 * args.length);
- int templateStart = 0;
- int i = 0;
- while (i < args.length) {
- int placeholderStart = template.indexOf("%s", templateStart);
- if (placeholderStart == -1) {
- break;
- }
- builder.append(template.substring(templateStart, placeholderStart));
- builder.append(args[i++]);
- templateStart = placeholderStart + 2;
- }
- builder.append(template.substring(templateStart));
-
- // if we run out of placeholders, append the extra args in square braces
- if (i < args.length) {
- builder.append(" [");
- builder.append(args[i++]);
- while (i < args.length) {
- builder.append(", ");
- builder.append(args[i++]);
- }
- builder.append(']');
- }
- return builder.toString();
- }
-
- private Formatter() { // To prevent instantiation.
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/InternalBase.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/InternalBase.java
deleted file mode 100644
index 66195fd3563..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/InternalBase.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.util;
-
-/**
- * {@code InternalBase} is a class from which other classes can derive that allows an efficient
- * toString implementation for logging/debugging purposes for those classes. The class is abstract
- * so that it is never instantiated explicitly.
- *
- */
-public abstract class InternalBase {
-
- /**
- * Adds a compact representation of this object to {@code builder}.
- *
- * @param builder the builder in which the string representation is added
- */
- public void toCompactString(TextBuilder builder) {
- builder.appendFormat("%s: ", getClass().getSimpleName());
- TextBuilder.outputFieldsToBuilder(builder, this);
- }
-
- /**
- * Adds a verbose representation of this object to {@code builder}. The
- * default implementation for toVerboseString is to simply call
- * toCompactString.
- *
- * @param builder the builder in which the string representation is added
- */
- public void toVerboseString(TextBuilder builder) {
- toCompactString(builder);
- }
-
- @Override
- public String toString() {
- TextBuilder builder = new TextBuilder();
- toCompactString(builder);
- return builder.toString();
- }
-
- /**
- * Creates a TextBuilder internally and returns a string based on the {@code
- * toVerboseString} method described above.
- */
- public String toVerboseString() {
- TextBuilder builder = new TextBuilder();
- toVerboseString(builder);
- return builder.toString();
- }
-
- /**
- * Given a set of {@code objects}, calls {@code toCompactString} on each of
- * them with the {@code builder} and separates each object's output in the
- * {@code builder} with a comma.
- */
- public static void toCompactStrings(TextBuilder builder,
- Iterable<? extends InternalBase> objects) {
- boolean first = true;
- for (InternalBase object : objects) {
- if (!first) {
- builder.append(", ");
- }
- object.toCompactString(builder);
- first = false;
- }
- }
-
- /**
- * Given a set of {@code objects}, calls {@code toString} on each of
- * them with the {@code builder} and separates each object's output in the
- * {@code builder} with a comma.
- */
- public static void toStrings(TextBuilder builder, Iterable<?> objects) {
- boolean first = true;
- for (Object object : objects) {
- if (!first) {
- builder.append(", ");
- }
- builder.append(object.toString());
- first = false;
- }
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/LazyString.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/LazyString.java
deleted file mode 100644
index cd10cef53fe..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/LazyString.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.util;
-
-import com.google.common.base.Receiver;
-
-
-/**
- * Utilities to enable creation of lazy strings, where the instantiation of the string is delayed
- * so that, e.g., log messages that aren't printed have reduced overhead.
- */
-public class LazyString {
-
- /**
- * Given an {@code element} to be logged lazily, returns null if the object is null. Otherwise,
- * return an object that would convert it to a string using {@code builderFunction}. I.e., this
- * method will call {@code builderFunction} with a new {@link TextBuilder} return the string
- * created with it.
- */
- public static <T> Object toLazyCompactString(final T element,
- final Receiver<TextBuilder> builderFunction) {
- if (element == null) {
- return null;
- }
- return new Object() {
- @Override
- public String toString() {
- TextBuilder builder = new TextBuilder();
- builderFunction.accept(builder);
- return builder.toString();
- }
- };
- }
-
- private LazyString() { // To prevent instantiation.
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Marshallable.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Marshallable.java
deleted file mode 100644
index 5b6a3cad0a5..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Marshallable.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.util;
-
-/**
- * Interface for classes that can marshall their state to a protocol buffer.
- *
- * @param <T> the type of protocol buffer returned by {@link #marshal}
- */
-public interface Marshallable<T> {
- /** Returns a protocol buffer containing the class state. */
- T marshal();
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/NamedRunnable.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/NamedRunnable.java
deleted file mode 100644
index 6587f940579..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/NamedRunnable.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.util;
-
-import com.google.common.base.Preconditions;
-
-/**
- * A wrapper around the {@link Runnable} interface that provides extra information (e.g., a name)
- * for logging, monitoring, debugging, etc.
- *
- */
-public abstract class NamedRunnable implements Runnable {
-
- /** The name of this runnable. */
- private final String name;
-
- /** Constructs a named runnable with the given name. */
- public NamedRunnable(String name) {
- Preconditions.checkNotNull(name, "name is null");
- this.name = name;
- }
-
- @Override
- public String toString() {
- return name + ':' + super.toString();
- }
-
- public String getName() {
- return name;
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Smearer.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Smearer.java
deleted file mode 100644
index 3a3ef06a2dc..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/Smearer.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.util;
-
-import com.google.common.base.Preconditions;
-
-import java.util.Random;
-
-/**
- * An abstraction to "smear" values by a given percent. Useful for randomizing delays a little bit
- * so that (say) processes do not get synchronized on time inadvertently, e.g., a heartbeat task
- * that sends a message every few minutes is smeared so that all clients do not end up sending a
- * message at the same time. In particular, given a {@code delay}, returns a value that is randomly
- * distributed between [delay - smearPercent * delay, delay + smearPercent * delay]
- *
- */
-public class Smearer {
-
- private final Random random;
-
- /** The percentage (0, 1.0] for smearing the delay. */
- private double smearFraction;
-
- /**
- * Creates a smearer with the given random number generator. If {@code smearPercent} is 0, uses an
- * internal default for smearing.
- * <p>
- * REQUIRES: 0 < smearPercent <= 100
- */
- public Smearer(Random random, final int smearPercent) {
- Preconditions.checkState((smearPercent >= 0) && (smearPercent <= 100));
- this.random = random;
- this.smearFraction = smearPercent / 100.0;
- }
-
- /**
- * Given a {@code delay}, returns a value that is randomly distributed between
- * [delay - smearPercent * delay, delay + smearPercent * delay]
- */
- public int getSmearedDelay(int delay) {
- // Get a random number between -1 and 1 and then multiply that by the smear
- // fraction.
- double smearFactor = (2 * random.nextDouble() - 1.0) * smearFraction;
- return (int) Math.ceil(delay + delay * smearFactor);
- }
-
- /** Changes the smear percent of this object to be {@code smearPercent}. */
- public void changeSmearPercent(int smearPercent) {
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/TextBuilder.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/TextBuilder.java
deleted file mode 100644
index ec1ffb2c6d7..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/TextBuilder.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.util;
-
-import com.google.protobuf.ByteString;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-
-/**
- * A {@link TextBuilder} is an abstraction that allows classes to efficiently
- * append their string representations and then use them later for human
- * consumption, e.g., for debugging or logging. It is currently a wrapper
- * around {@link StringBuilder} and {@link Formatter} to give us format and
- * append capabilities together. All append methods return this TextBuilder
- * so that the method calls can be chained.
- *
- */
-public class TextBuilder {
-
- private final StringBuilder builder;
- private final UtilFormatter formatter;
-
- /**
- * Given an object, outputs all its fields with names to builder
- */
- public static void outputFieldsToBuilder(TextBuilder builder, Object object) {
- // Get all the fields and print them using toCompactString if possible;
- // otherwise, via toString
- Field[] fields = object.getClass().getDeclaredFields();
- for (Field field : fields) {
- try {
- // Ignore static final fields, as they're uninteresting.
- int modifiers = field.getModifiers();
- if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
- continue;
- }
-
- field.setAccessible(true);
- builder.append(field.getName() + " = ");
- Object fieldValue = field.get(object);
- if (fieldValue instanceof InternalBase) {
- ((InternalBase) fieldValue).toCompactString(builder);
- } else {
- builder.append(fieldValue);
- }
- builder.append(", ");
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- }
- }
-
- /**
- * Returns an empty TextBuilder to which various objects' string
- * representations can be added later.
- */
- public TextBuilder() {
- builder = new StringBuilder();
- formatter = new UtilFormatter(builder);
- }
-
- /**
- * Appends the string representation of {@code c} to this builder.
- *
- * @param c the character being appended
- */
- public TextBuilder append(char c) {
- builder.append(c);
- return this;
- }
-
- /**
- * Appends the string representation of {@code i} to this builder.
- *
- * @param i the integer being appended
- */
- public TextBuilder append(int i) {
- builder.append(i);
- return this;
- }
-
- /**
- * Appends the toString representation of {@code object} to this builder.
- */
- public TextBuilder append(Object object) {
- builder.append(object);
- return this;
- }
-
- /** Appends the {@link Bytes#toString} representation of {@code bytes} to this builder. */
- public TextBuilder append(ByteString bytes) {
- builder.append(Bytes.toString(bytes));
- return this;
- }
-
- /**
- * Appends the string representation of {@code l} to this builder.
- *
- * @param l the long being appended
- */
- public TextBuilder append(long l) {
- builder.append(l);
- return this;
- }
-
- /**
- * Appends the string representation of {@code b} to this builder.
- *
- * @param b the boolean being appended
- */
- public TextBuilder append(boolean b) {
- builder.append(b);
- return this;
- }
-
- /**
- * Appends {@code s} to this builder.
- *
- * @param s the string being appended
- */
- public TextBuilder append(String s) {
- builder.append(s);
- return this;
- }
-
- /**
- * Writes a formatted string to this using the specified format string and
- * arguments.
- *
- * @param format the format as used in {@link java.util.Formatter}
- * @param args the arguments that are converted to their string form using
- * {@code format}
- */
- public TextBuilder appendFormat(String format, Object... args) {
- formatter.format(format, args);
- return this;
- }
-
- @Override
- public String toString() {
- return builder.toString();
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/TypedUtil.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/TypedUtil.java
deleted file mode 100644
index ab25c612c0b..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/TypedUtil.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.util;
-
-import com.google.common.base.Objects;
-
-import java.util.Collection;
-import java.util.Map;
-import java.util.Set;
-
-
-/**
- * Utilities for using various data structures such as {@link Map}s and {@link
- * Set}s in a type-safe manner.
- *
- */
-public class TypedUtil {
-
- private TypedUtil() { // prevent instantiation
- }
-
- /** A statically type-safe version of {@link Map#containsKey}. */
- public static <Key> boolean containsKey(Map<Key, ?> map, Key key) {
- return map.containsKey(key);
- }
-
- /** A statically type-safe version of {@link Map#get}. */
- public static <Key, Value> Value mapGet(Map<Key, Value> map, Key key) {
- return map.get(key);
- }
-
- /** A statically type-safe version of {@link Map#remove}. */
- public static <Key, Value> Value remove(Map<Key, Value> map, Key key) {
- return map.remove(key);
- }
-
- /** A statically type-safe version of {@link Set#contains}. */
- public static <ElementType> boolean contains(Set<ElementType> set, ElementType element) {
- return set.contains(element);
- }
-
- /** A statically type-safe version of {@link Set#contains}. */
- public static <ElementType> boolean contains(
- Collection<ElementType> collection, ElementType element) {
- return collection.contains(element);
- }
-
- /** A statically type-safe version of {@link Set#remove}. */
- public static <ElementType> boolean remove(Set<ElementType> set, ElementType element) {
- return set.remove(element);
- }
-
- /**
- * A wrapper around {@link Objects#equal(Object, Object)} that ensures the objects
- * have the same type.
- */
- public static <T> boolean equals(T o1, T o2) {
- return Objects.equal(o1, o2);
- }
-}
diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/UtilFormatter.java b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/UtilFormatter.java
deleted file mode 100644
index 3b5a9033915..00000000000
--- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/util/UtilFormatter.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright 2011 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.ipc.invalidation.util;
-
-import java.util.Formatter;
-
-/**
- * A formatter with a level of indirection so that GWT magic
- * can be used.
- *
- */
-public class UtilFormatter {
-
- private final Formatter formatter;
-
- UtilFormatter(StringBuilder builder) {
- formatter = new Formatter(builder);
- }
-
- public void format(String format, Object[] args) {
- formatter.format(format, args);
- }
-}