pax_global_header00006660000000000000000000000064124552167760014531gustar00rootroot0000000000000052 comment=09e9a55c94bd52bab712a546f90e6390584f209a curator-apache-curator-2.7.1/000077500000000000000000000000001245521677600161135ustar00rootroot00000000000000curator-apache-curator-2.7.1/.gitignore000066400000000000000000000013751245521677600201110ustar00rootroot00000000000000# Compiled source # ################### *.com *.class *.dll *.exe *.o *.so # Packages # ############ # it's better to unpack these files and commit the raw source # git has its own built in compression methods *.7z *.dmg *.gz *.iso *.jar *.rar *.tar *.zip # Logs and databases # ###################### *.log # OS generated files # ###################### .DS_Store* ehthumbs.db Icon? Thumbs.db # Editor Files # ################ *~ *.swp # Gradle Files # ################ .gradle # Build output directies /target */target /build */build */bin # IntelliJ specific files/directories out .idea *.ipr *.iws *.iml atlassian-ide-plugin.xml # Eclipse specific files/directories .classpath .project .settings .metadata # NetBeans specific files/directories .nbattrs curator-apache-curator-2.7.1/DEPENDENCIES000066400000000000000000000000351245521677600176620ustar00rootroot00000000000000* intentionally left blank * curator-apache-curator-2.7.1/LICENSE000066400000000000000000000261361245521677600171300ustar00rootroot00000000000000 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. curator-apache-curator-2.7.1/NOTICE000066400000000000000000000002501245521677600170140ustar00rootroot00000000000000Apache Curator Copyright 2013-2014 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). curator-apache-curator-2.7.1/README000066400000000000000000000003251245521677600167730ustar00rootroot00000000000000Apache Curator -------------- Curator is a set of Java libraries that make using Apache ZooKeeper much easier. Website: http://curator.apache.org/ Getting started: http://curator.apache.org/getting-started.html curator-apache-curator-2.7.1/curator-client/000077500000000000000000000000001245521677600210465ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/LICENSE000066400000000000000000000261361245521677600220630ustar00rootroot00000000000000 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. curator-apache-curator-2.7.1/curator-client/NOTICE000066400000000000000000000002501245521677600217470ustar00rootroot00000000000000Apache Curator Copyright 2013-2014 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). curator-apache-curator-2.7.1/curator-client/pom.xml000066400000000000000000000043241245521677600223660ustar00rootroot00000000000000 4.0.0 org.apache.curator apache-curator 2.7.1 curator-client 2.7.1 bundle Curator Client Low-level API 2011 * org.apache.curator*;version="${project.version}";-noimport:=true org.slf4j slf4j-api org.mockito mockito-core test org.apache.curator curator-test test curator-apache-curator-2.7.1/curator-client/src/000077500000000000000000000000001245521677600216355ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/000077500000000000000000000000001245521677600225615ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/000077500000000000000000000000001245521677600235025ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/000077500000000000000000000000001245521677600242715ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/000077500000000000000000000000001245521677600255125ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/000077500000000000000000000000001245521677600271715ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/ConnectionState.java000066400000000000000000000223561245521677600331440ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.drivers.TracerDriver; import org.apache.curator.ensemble.EnsembleProvider; import org.apache.curator.utils.DebugUtils; import org.apache.curator.utils.ZookeeperFactory; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; class ConnectionState implements Watcher, Closeable { private static final int MAX_BACKGROUND_EXCEPTIONS = 10; private static final boolean LOG_EVENTS = Boolean.getBoolean(DebugUtils.PROPERTY_LOG_EVENTS); private final Logger log = LoggerFactory.getLogger(getClass()); private final HandleHolder zooKeeper; private final AtomicBoolean isConnected = new AtomicBoolean(false); private final EnsembleProvider ensembleProvider; private final int sessionTimeoutMs; private final int connectionTimeoutMs; private final AtomicReference tracer; private final Queue backgroundExceptions = new ConcurrentLinkedQueue(); private final Queue parentWatchers = new ConcurrentLinkedQueue(); private final AtomicLong instanceIndex = new AtomicLong(); private volatile long connectionStartMs = 0; ConnectionState(ZookeeperFactory zookeeperFactory, EnsembleProvider ensembleProvider, int sessionTimeoutMs, int connectionTimeoutMs, Watcher parentWatcher, AtomicReference tracer, boolean canBeReadOnly) { this.ensembleProvider = ensembleProvider; this.sessionTimeoutMs = sessionTimeoutMs; this.connectionTimeoutMs = connectionTimeoutMs; this.tracer = tracer; if ( parentWatcher != null ) { parentWatchers.offer(parentWatcher); } zooKeeper = new HandleHolder(zookeeperFactory, this, ensembleProvider, sessionTimeoutMs, canBeReadOnly); } ZooKeeper getZooKeeper() throws Exception { if ( SessionFailRetryLoop.sessionForThreadHasFailed() ) { throw new SessionFailRetryLoop.SessionFailedException(); } Exception exception = backgroundExceptions.poll(); if ( exception != null ) { tracer.get().addCount("background-exceptions", 1); throw exception; } boolean localIsConnected = isConnected.get(); if ( !localIsConnected ) { checkTimeouts(); } return zooKeeper.getZooKeeper(); } boolean isConnected() { return isConnected.get(); } void start() throws Exception { log.debug("Starting"); ensembleProvider.start(); reset(); } @Override public void close() throws IOException { log.debug("Closing"); CloseableUtils.closeQuietly(ensembleProvider); try { zooKeeper.closeAndClear(); } catch ( Exception e ) { throw new IOException(e); } finally { isConnected.set(false); } } void addParentWatcher(Watcher watcher) { parentWatchers.offer(watcher); } void removeParentWatcher(Watcher watcher) { parentWatchers.remove(watcher); } long getInstanceIndex() { return instanceIndex.get(); } @Override public void process(WatchedEvent event) { if ( LOG_EVENTS ) { log.debug("ConnectState watcher: " + event); } for ( Watcher parentWatcher : parentWatchers ) { TimeTrace timeTrace = new TimeTrace("connection-state-parent-process", tracer.get()); parentWatcher.process(event); timeTrace.commit(); } boolean wasConnected = isConnected.get(); boolean newIsConnected = wasConnected; if ( event.getType() == Watcher.Event.EventType.None ) { newIsConnected = checkState(event.getState(), wasConnected); } if ( newIsConnected != wasConnected ) { isConnected.set(newIsConnected); connectionStartMs = System.currentTimeMillis(); } } EnsembleProvider getEnsembleProvider() { return ensembleProvider; } private synchronized void checkTimeouts() throws Exception { int minTimeout = Math.min(sessionTimeoutMs, connectionTimeoutMs); long elapsed = System.currentTimeMillis() - connectionStartMs; if ( elapsed >= minTimeout ) { if ( zooKeeper.hasNewConnectionString() ) { handleNewConnectionString(); } else { int maxTimeout = Math.max(sessionTimeoutMs, connectionTimeoutMs); if ( elapsed > maxTimeout ) { if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) ) { log.warn(String.format("Connection attempt unsuccessful after %d (greater than max timeout of %d). Resetting connection and trying again with a new connection.", elapsed, maxTimeout)); } reset(); } else { KeeperException.ConnectionLossException connectionLossException = new CuratorConnectionLossException(); if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) ) { log.error(String.format("Connection timed out for connection string (%s) and timeout (%d) / elapsed (%d)", zooKeeper.getConnectionString(), connectionTimeoutMs, elapsed), connectionLossException); } tracer.get().addCount("connections-timed-out", 1); throw connectionLossException; } } } } private synchronized void reset() throws Exception { log.debug("reset"); instanceIndex.incrementAndGet(); isConnected.set(false); connectionStartMs = System.currentTimeMillis(); zooKeeper.closeAndReset(); zooKeeper.getZooKeeper(); // initiate connection } private boolean checkState(Event.KeeperState state, boolean wasConnected) { boolean isConnected = wasConnected; boolean checkNewConnectionString = true; switch ( state ) { default: case Disconnected: { isConnected = false; break; } case SyncConnected: case ConnectedReadOnly: { isConnected = true; break; } case AuthFailed: { isConnected = false; log.error("Authentication failed"); break; } case Expired: { isConnected = false; checkNewConnectionString = false; handleExpiredSession(); break; } case SaslAuthenticated: { // NOP break; } } if ( checkNewConnectionString && zooKeeper.hasNewConnectionString() ) { handleNewConnectionString(); } return isConnected; } private void handleNewConnectionString() { log.info("Connection string changed"); tracer.get().addCount("connection-string-changed", 1); try { reset(); } catch ( Exception e ) { queueBackgroundException(e); } } private void handleExpiredSession() { log.warn("Session expired event received"); tracer.get().addCount("session-expired", 1); try { reset(); } catch ( Exception e ) { queueBackgroundException(e); } } @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"}) private void queueBackgroundException(Exception e) { while ( backgroundExceptions.size() >= MAX_BACKGROUND_EXCEPTIONS ) { backgroundExceptions.poll(); } backgroundExceptions.offer(e); } } CuratorConnectionLossException.java000066400000000000000000000022671245521677600361430ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator; import org.apache.zookeeper.KeeperException; /** * This is needed to differentiate between ConnectionLossException thrown by ZooKeeper * and ConnectionLossException thrown by {@link ConnectionState#checkTimeouts()} */ public class CuratorConnectionLossException extends KeeperException.ConnectionLossException { private static final long serialVersionUID = 1L; } CuratorZookeeperClient.java000066400000000000000000000250671245521677600344310ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator; import com.google.common.base.Preconditions; import org.apache.curator.drivers.TracerDriver; import org.apache.curator.ensemble.EnsembleProvider; import org.apache.curator.ensemble.fixed.FixedEnsembleProvider; import org.apache.curator.utils.DefaultTracerDriver; import org.apache.curator.utils.DefaultZookeeperFactory; import org.apache.curator.utils.ZookeeperFactory; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * A wrapper around Zookeeper that takes care of some low-level housekeeping */ @SuppressWarnings("UnusedDeclaration") public class CuratorZookeeperClient implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final ConnectionState state; private final AtomicReference retryPolicy = new AtomicReference(); private final int connectionTimeoutMs; private final AtomicBoolean started = new AtomicBoolean(false); private final AtomicReference tracer = new AtomicReference(new DefaultTracerDriver()); /** * * @param connectString list of servers to connect to * @param sessionTimeoutMs session timeout * @param connectionTimeoutMs connection timeout * @param watcher default watcher or null * @param retryPolicy the retry policy to use */ public CuratorZookeeperClient(String connectString, int sessionTimeoutMs, int connectionTimeoutMs, Watcher watcher, RetryPolicy retryPolicy) { this(new DefaultZookeeperFactory(), new FixedEnsembleProvider(connectString), sessionTimeoutMs, connectionTimeoutMs, watcher, retryPolicy, false); } /** * @param ensembleProvider the ensemble provider * @param sessionTimeoutMs session timeout * @param connectionTimeoutMs connection timeout * @param watcher default watcher or null * @param retryPolicy the retry policy to use */ public CuratorZookeeperClient(EnsembleProvider ensembleProvider, int sessionTimeoutMs, int connectionTimeoutMs, Watcher watcher, RetryPolicy retryPolicy) { this(new DefaultZookeeperFactory(), ensembleProvider, sessionTimeoutMs, connectionTimeoutMs, watcher, retryPolicy, false); } /** * @param zookeeperFactory factory for creating {@link ZooKeeper} instances * @param ensembleProvider the ensemble provider * @param sessionTimeoutMs session timeout * @param connectionTimeoutMs connection timeout * @param watcher default watcher or null * @param retryPolicy the retry policy to use * @param canBeReadOnly if true, allow ZooKeeper client to enter * read only mode in case of a network partition. See * {@link ZooKeeper#ZooKeeper(String, int, Watcher, long, byte[], boolean)} * for details */ public CuratorZookeeperClient(ZookeeperFactory zookeeperFactory, EnsembleProvider ensembleProvider, int sessionTimeoutMs, int connectionTimeoutMs, Watcher watcher, RetryPolicy retryPolicy, boolean canBeReadOnly) { if ( sessionTimeoutMs < connectionTimeoutMs ) { log.warn(String.format("session timeout [%d] is less than connection timeout [%d]", sessionTimeoutMs, connectionTimeoutMs)); } retryPolicy = Preconditions.checkNotNull(retryPolicy, "retryPolicy cannot be null"); ensembleProvider = Preconditions.checkNotNull(ensembleProvider, "ensembleProvider cannot be null"); this.connectionTimeoutMs = connectionTimeoutMs; state = new ConnectionState(zookeeperFactory, ensembleProvider, sessionTimeoutMs, connectionTimeoutMs, watcher, tracer, canBeReadOnly); setRetryPolicy(retryPolicy); } /** * Return the managed ZK instance. * * @return client the client * @throws Exception if the connection timeout has elapsed or an exception occurs in a background process */ public ZooKeeper getZooKeeper() throws Exception { Preconditions.checkState(started.get(), "Client is not started"); return state.getZooKeeper(); } /** * Return a new retry loop. All operations should be performed in a retry loop * * @return new retry loop */ public RetryLoop newRetryLoop() { return new RetryLoop(retryPolicy.get(), tracer); } /** * Return a new "session fail" retry loop. See {@link SessionFailRetryLoop} for details * on when to use it. * * @param mode failure mode * @return new retry loop */ public SessionFailRetryLoop newSessionFailRetryLoop(SessionFailRetryLoop.Mode mode) { return new SessionFailRetryLoop(this, mode); } /** * Returns true if the client is current connected * * @return true/false */ public boolean isConnected() { return state.isConnected(); } /** * This method blocks until the connection to ZK succeeds. Use with caution. The block * will timeout after the connection timeout (as passed to the constructor) has elapsed * * @return true if the connection succeeded, false if not * @throws InterruptedException interrupted while waiting */ public boolean blockUntilConnectedOrTimedOut() throws InterruptedException { Preconditions.checkState(started.get(), "Client is not started"); log.debug("blockUntilConnectedOrTimedOut() start"); TimeTrace trace = startTracer("blockUntilConnectedOrTimedOut"); internalBlockUntilConnectedOrTimedOut(); trace.commit(); boolean localIsConnected = state.isConnected(); log.debug("blockUntilConnectedOrTimedOut() end. isConnected: " + localIsConnected); return localIsConnected; } /** * Must be called after construction * * @throws IOException errors */ public void start() throws Exception { log.debug("Starting"); if ( !started.compareAndSet(false, true) ) { IllegalStateException ise = new IllegalStateException("Already started"); throw ise; } state.start(); } /** * Close the client */ public void close() { log.debug("Closing"); started.set(false); try { state.close(); } catch ( IOException e ) { log.error("", e); } } /** * Change the retry policy * * @param policy new policy */ public void setRetryPolicy(RetryPolicy policy) { Preconditions.checkNotNull(policy, "policy cannot be null"); retryPolicy.set(policy); } /** * Return the current retry policy * * @return policy */ public RetryPolicy getRetryPolicy() { return retryPolicy.get(); } /** * Start a new tracer * @param name name of the event * @return the new tracer ({@link TimeTrace#commit()} must be called) */ public TimeTrace startTracer(String name) { return new TimeTrace(name, tracer.get()); } /** * Return the current tracing driver * * @return tracing driver */ public TracerDriver getTracerDriver() { return tracer.get(); } /** * Change the tracing driver * * @param tracer new tracing driver */ public void setTracerDriver(TracerDriver tracer) { this.tracer.set(tracer); } /** * Returns the current known connection string - not guaranteed to be correct * value at any point in the future. * * @return connection string */ public String getCurrentConnectionString() { return state.getEnsembleProvider().getConnectionString(); } /** * Return the configured connection timeout * * @return timeout */ public int getConnectionTimeoutMs() { return connectionTimeoutMs; } /** * Every time a new {@link ZooKeeper} instance is allocated, the "instance index" * is incremented. * * @return the current instance index */ public long getInstanceIndex() { return state.getInstanceIndex(); } void addParentWatcher(Watcher watcher) { state.addParentWatcher(watcher); } void removeParentWatcher(Watcher watcher) { state.removeParentWatcher(watcher); } void internalBlockUntilConnectedOrTimedOut() throws InterruptedException { long waitTimeMs = connectionTimeoutMs; while ( !state.isConnected() && (waitTimeMs > 0) ) { final CountDownLatch latch = new CountDownLatch(1); Watcher tempWatcher = new Watcher() { @Override public void process(WatchedEvent event) { latch.countDown(); } }; state.addParentWatcher(tempWatcher); long startTimeMs = System.currentTimeMillis(); try { latch.await(1, TimeUnit.SECONDS); } finally { state.removeParentWatcher(tempWatcher); } long elapsed = Math.max(1, System.currentTimeMillis() - startTimeMs); waitTimeMs -= elapsed; } } } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/HandleHolder.java000066400000000000000000000112421245521677600323650ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator; import org.apache.curator.ensemble.EnsembleProvider; import org.apache.curator.utils.ZookeeperFactory; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; class HandleHolder { private final ZookeeperFactory zookeeperFactory; private final Watcher watcher; private final EnsembleProvider ensembleProvider; private final int sessionTimeout; private final boolean canBeReadOnly; private volatile Helper helper; private interface Helper { ZooKeeper getZooKeeper() throws Exception; String getConnectionString(); } HandleHolder(ZookeeperFactory zookeeperFactory, Watcher watcher, EnsembleProvider ensembleProvider, int sessionTimeout, boolean canBeReadOnly) { this.zookeeperFactory = zookeeperFactory; this.watcher = watcher; this.ensembleProvider = ensembleProvider; this.sessionTimeout = sessionTimeout; this.canBeReadOnly = canBeReadOnly; } ZooKeeper getZooKeeper() throws Exception { return (helper != null) ? helper.getZooKeeper() : null; } String getConnectionString() { return (helper != null) ? helper.getConnectionString() : null; } boolean hasNewConnectionString() { String helperConnectionString = (helper != null) ? helper.getConnectionString() : null; return (helperConnectionString != null) && !ensembleProvider.getConnectionString().equals(helperConnectionString); } void closeAndClear() throws Exception { internalClose(); helper = null; } void closeAndReset() throws Exception { internalClose(); // first helper is synchronized when getZooKeeper is called. Subsequent calls // are not synchronized. helper = new Helper() { private volatile ZooKeeper zooKeeperHandle = null; private volatile String connectionString = null; @Override public ZooKeeper getZooKeeper() throws Exception { synchronized(this) { if ( zooKeeperHandle == null ) { connectionString = ensembleProvider.getConnectionString(); zooKeeperHandle = zookeeperFactory.newZooKeeper(connectionString, sessionTimeout, watcher, canBeReadOnly); } helper = new Helper() { @Override public ZooKeeper getZooKeeper() throws Exception { return zooKeeperHandle; } @Override public String getConnectionString() { return connectionString; } }; return zooKeeperHandle; } } @Override public String getConnectionString() { return connectionString; } }; } private void internalClose() throws Exception { try { ZooKeeper zooKeeper = (helper != null) ? helper.getZooKeeper() : null; if ( zooKeeper != null ) { Watcher dummyWatcher = new Watcher() { @Override public void process(WatchedEvent event) { } }; zooKeeper.register(dummyWatcher); // clear the default watcher so that no new events get processed by mistake zooKeeper.close(); } } catch ( InterruptedException dummy ) { Thread.currentThread().interrupt(); } } } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/RetryLoop.java000066400000000000000000000145701245521677600320020ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator; import org.apache.curator.drivers.TracerDriver; import org.apache.curator.utils.DebugUtils; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; /** *

Mechanism to perform an operation on Zookeeper that is safe against * disconnections and "recoverable" errors.

* *

* If an exception occurs during the operation, the RetryLoop will process it, * check with the current retry policy and either attempt to reconnect or re-throw * the exception *

* * Canonical usage:
*
 * RetryLoop retryLoop = client.newRetryLoop();
 * while ( retryLoop.shouldContinue() )
 * {
 *     try
 *     {
 *         // do your work
 *         ZooKeeper      zk = client.getZooKeeper();    // it's important to re-get the ZK instance in case there was an error and the instance was re-created
 *
 *         retryLoop.markComplete();
 *     }
 *     catch ( Exception e )
 *     {
 *         retryLoop.takeException(e);
 *     }
 * }
 * 
*/ public class RetryLoop { private boolean isDone = false; private int retryCount = 0; private final Logger log = LoggerFactory.getLogger(getClass()); private final long startTimeMs = System.currentTimeMillis(); private final RetryPolicy retryPolicy; private final AtomicReference tracer; private static final RetrySleeper sleeper = new RetrySleeper() { @Override public void sleepFor(long time, TimeUnit unit) throws InterruptedException { unit.sleep(time); } }; /** * Returns the default retry sleeper * * @return sleeper */ public static RetrySleeper getDefaultRetrySleeper() { return sleeper; } /** * Convenience utility: creates a retry loop calling the given proc and retrying if needed * * @param client Zookeeper * @param proc procedure to call with retry * @param return type * @return procedure result * @throws Exception any non-retriable errors */ public static T callWithRetry(CuratorZookeeperClient client, Callable proc) throws Exception { T result = null; RetryLoop retryLoop = client.newRetryLoop(); while ( retryLoop.shouldContinue() ) { try { client.internalBlockUntilConnectedOrTimedOut(); result = proc.call(); retryLoop.markComplete(); } catch ( Exception e ) { retryLoop.takeException(e); } } return result; } RetryLoop(RetryPolicy retryPolicy, AtomicReference tracer) { this.retryPolicy = retryPolicy; this.tracer = tracer; } /** * If true is returned, make an attempt at the operation * * @return true/false */ public boolean shouldContinue() { return !isDone; } /** * Call this when your operation has successfully completed */ public void markComplete() { isDone = true; } /** * Utility - return true if the given Zookeeper result code is retry-able * * @param rc result code * @return true/false */ public static boolean shouldRetry(int rc) { return (rc == KeeperException.Code.CONNECTIONLOSS.intValue()) || (rc == KeeperException.Code.OPERATIONTIMEOUT.intValue()) || (rc == KeeperException.Code.SESSIONMOVED.intValue()) || (rc == KeeperException.Code.SESSIONEXPIRED.intValue()); } /** * Utility - return true if the given exception is retry-able * * @param exception exception to check * @return true/false */ public static boolean isRetryException(Throwable exception) { if ( exception instanceof KeeperException ) { KeeperException keeperException = (KeeperException)exception; return shouldRetry(keeperException.code().intValue()); } return false; } /** * Pass any caught exceptions here * * @param exception the exception * @throws Exception if not retry-able or the retry policy returned negative */ public void takeException(Exception exception) throws Exception { boolean rethrow = true; if ( isRetryException(exception) ) { if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) ) { log.debug("Retry-able exception received", exception); } if ( retryPolicy.allowRetry(retryCount++, System.currentTimeMillis() - startTimeMs, sleeper) ) { tracer.get().addCount("retries-allowed", 1); if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) ) { log.debug("Retrying operation"); } rethrow = false; } else { tracer.get().addCount("retries-disallowed", 1); if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) ) { log.debug("Retry policy not allowing retry"); } } } if ( rethrow ) { throw exception; } } } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/RetryPolicy.java000066400000000000000000000026401245521677600323230ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator; /** * Abstracts the policy to use when retrying connections */ public interface RetryPolicy { /** * Called when an operation has failed for some reason. This method should return * true to make another attempt. * * * @param retryCount the number of times retried so far (0 the first time) * @param elapsedTimeMs the elapsed time in ms since the operation was attempted * @param sleeper use this to sleep - DO NOT call Thread.sleep * @return true/false */ public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper); } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/RetrySleeper.java000066400000000000000000000023021245521677600324560ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator; import java.util.concurrent.TimeUnit; /** * Abstraction for retry policies to sleep */ public interface RetrySleeper { /** * Sleep for the given time * * @param time time * @param unit time unit * @throws InterruptedException if the sleep is interrupted */ public void sleepFor(long time, TimeUnit unit) throws InterruptedException; } SessionFailRetryLoop.java000066400000000000000000000177471245521677600340740ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import java.io.Closeable; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicBoolean; /** *

* See {@link RetryLoop} for the main details on retry loops. All Curator/ZooKeeper operations * should be done in a retry loop. *

* *

* The standard retry loop treats session failure as a type of connection failure. i.e. the fact * that it is a session failure isn't considered. This can be problematic if you are performing * a series of operations that rely on ephemeral nodes. If the session fails after the ephemeral * node has been created, future Curator/ZooKeeper operations may succeed even though the * ephemeral node has been removed by ZooKeeper. *

* *

* Here's an example: *

*
    *
  • You create an ephemeral/sequential node as a kind of lock/marker
  • *
  • You perform some other operations
  • *
  • The session fails for some reason
  • *
  • You attempt to create a node assuming that the lock/marker still exists *
      *
    • Curator will notice the session failure and try to reconnect
    • *
    • In most cases, the reconnect will succeed and, thus, the node creation will succeed * even though the ephemeral node will have been deleted by ZooKeeper.
    • *
    *
  • *
* *

* The SessionFailRetryLoop prevents this type of scenario. When a session failure is detected, * the thread is marked as failed which will cause all future Curator operations to fail. The * SessionFailRetryLoop will then either retry the entire * set of operations or fail (depending on {@link SessionFailRetryLoop.Mode}) *

* * Canonical usage:
*
 * SessionFailRetryLoop    retryLoop = client.newSessionFailRetryLoop(mode);
 * retryLoop.start();
 * try
 * {
 *     while ( retryLoop.shouldContinue() )
 *     {
 *         try
 *         {
 *             // do work
 *         }
 *         catch ( Exception e )
 *         {
 *             retryLoop.takeException(e);
 *         }
 *     }
 * }
 * finally
 * {
 *     retryLoop.close();
 * }
 * 
*/ public class SessionFailRetryLoop implements Closeable { private final CuratorZookeeperClient client; private final Mode mode; private final Thread ourThread = Thread.currentThread(); private final AtomicBoolean sessionHasFailed = new AtomicBoolean(false); private final AtomicBoolean isDone = new AtomicBoolean(false); private final RetryLoop retryLoop; private final Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { if ( event.getState() == Event.KeeperState.Expired ) { sessionHasFailed.set(true); failedSessionThreads.add(ourThread); } } }; private static final Set failedSessionThreads = Sets.newSetFromMap(Maps.newConcurrentMap()); public static class SessionFailedException extends Exception { private static final long serialVersionUID = 1L; } public enum Mode { /** * If the session fails, retry the entire set of operations when {@link SessionFailRetryLoop#shouldContinue()} * is called */ RETRY, /** * If the session fails, throw {@link KeeperException.SessionExpiredException} when * {@link SessionFailRetryLoop#shouldContinue()} is called */ FAIL } /** * Convenience utility: creates a "session fail" retry loop calling the given proc * * @param client Zookeeper * @param mode how to handle session failures * @param proc procedure to call with retry * @param return type * @return procedure result * @throws Exception any non-retriable errors */ public static T callWithRetry(CuratorZookeeperClient client, Mode mode, Callable proc) throws Exception { T result = null; SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(mode); retryLoop.start(); try { while ( retryLoop.shouldContinue() ) { try { result = proc.call(); } catch ( Exception e ) { retryLoop.takeException(e); } } } finally { retryLoop.close(); } return result; } SessionFailRetryLoop(CuratorZookeeperClient client, Mode mode) { this.client = client; this.mode = mode; retryLoop = client.newRetryLoop(); } static boolean sessionForThreadHasFailed() { return (failedSessionThreads.size() > 0) && failedSessionThreads.contains(Thread.currentThread()); } /** * SessionFailRetryLoop must be started */ public void start() { Preconditions.checkState(Thread.currentThread().equals(ourThread), "Not in the correct thread"); client.addParentWatcher(watcher); } /** * If true is returned, make an attempt at the set of operations * * @return true/false */ public boolean shouldContinue() { boolean localIsDone = isDone.getAndSet(true); return !localIsDone; } /** * Must be called in a finally handler when done with the loop */ @Override public void close() { Preconditions.checkState(Thread.currentThread().equals(ourThread), "Not in the correct thread"); failedSessionThreads.remove(ourThread); client.removeParentWatcher(watcher); } /** * Pass any caught exceptions here * * @param exception the exception * @throws Exception if not retry-able or the retry policy returned negative */ public void takeException(Exception exception) throws Exception { Preconditions.checkState(Thread.currentThread().equals(ourThread), "Not in the correct thread"); boolean passUp = true; if ( sessionHasFailed.get() ) { switch ( mode ) { case RETRY: { sessionHasFailed.set(false); failedSessionThreads.remove(ourThread); if ( exception instanceof SessionFailedException ) { isDone.set(false); passUp = false; } break; } case FAIL: { break; } } } if ( passUp ) { retryLoop.takeException(exception); } } } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/TimeTrace.java000066400000000000000000000030711245521677600317120ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator; import org.apache.curator.drivers.TracerDriver; import java.util.concurrent.TimeUnit; /** * Utility to time a method or portion of code */ public class TimeTrace { private final String name; private final TracerDriver driver; private final long startTimeNanos = System.nanoTime(); /** * Create and start a timer * * @param name name of the event * @param driver driver */ public TimeTrace(String name, TracerDriver driver) { this.name = name; this.driver = driver; } /** * Record the elapsed time */ public void commit() { long elapsed = System.nanoTime() - startTimeNanos; driver.addTrace(name, elapsed, TimeUnit.NANOSECONDS); } } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/drivers/000077500000000000000000000000001245521677600306475ustar00rootroot00000000000000TracerDriver.java000066400000000000000000000025711245521677600340340ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/drivers/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.drivers; import java.util.concurrent.TimeUnit; /** * Mechanism for timing methods and recording counters */ public interface TracerDriver { /** * Record the given trace event * * @param name of the event * @param time time event took * @param unit time unit */ public void addTrace(String name, long time, TimeUnit unit); /** * Add to a named counter * * @param name name of the counter * @param increment amount to increment */ public void addCount(String name, int increment); } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/ensemble/000077500000000000000000000000001245521677600307635ustar00rootroot00000000000000EnsembleProvider.java000066400000000000000000000035011245521677600350130ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/ensemble/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.ensemble; import org.apache.curator.CuratorZookeeperClient; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import java.io.Closeable; import java.io.IOException; /** * Abstraction that provides the ZooKeeper connection string */ public interface EnsembleProvider extends Closeable { /** * Curator will call this method when {@link CuratorZookeeperClient#start()} is * called * * @throws Exception errors */ public void start() throws Exception; /** * Return the current connection string to use. Curator will call this each * time it needs to create a ZooKeeper instance * * @return connection string (per {@link ZooKeeper#ZooKeeper(String, int, Watcher)} etc.) */ public String getConnectionString(); /** * Curator will call this method when {@link CuratorZookeeperClient#close()} is called * * @throws IOException errors */ public void close() throws IOException; } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/ensemble/exhibitor/000077500000000000000000000000001245521677600327605ustar00rootroot00000000000000DefaultExhibitorRestClient.java000066400000000000000000000043071245521677600410070ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/ensemble/exhibitor/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.ensemble.exhibitor; import org.apache.curator.utils.CloseableUtils; import java.io.BufferedInputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URI; @SuppressWarnings("UnusedDeclaration") public class DefaultExhibitorRestClient implements ExhibitorRestClient { private final boolean useSsl; public DefaultExhibitorRestClient() { this(false); } public DefaultExhibitorRestClient(boolean useSsl) { this.useSsl = useSsl; } @Override public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception { URI uri = new URI(useSsl ? "https" : "http", null, hostname, port, uriPath, null, null); HttpURLConnection connection = (HttpURLConnection)uri.toURL().openConnection(); connection.addRequestProperty("Accept", mimeType); StringBuilder str = new StringBuilder(); InputStream in = new BufferedInputStream(connection.getInputStream()); try { for(;;) { int b = in.read(); if ( b < 0 ) { break; } str.append((char)(b & 0xff)); } } finally { CloseableUtils.closeQuietly(in); } return str.toString(); } } ExhibitorEnsembleProvider.java000066400000000000000000000265141245521677600406770ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/ensemble/exhibitor/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.ensemble.exhibitor; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.curator.RetryLoop; import org.apache.curator.RetryPolicy; import org.apache.curator.ensemble.EnsembleProvider; import org.apache.curator.utils.ThreadUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; /** * Ensemble provider that polls a cluster of Exhibitor (https://github.com/Netflix/exhibitor) * instances for the connection string. * If the set of instances should change, new ZooKeeper connections will use the new connection * string. */ public class ExhibitorEnsembleProvider implements EnsembleProvider { private final Logger log = LoggerFactory.getLogger(getClass()); private final AtomicReference exhibitors = new AtomicReference(); private final AtomicReference masterExhibitors = new AtomicReference(); private final ExhibitorRestClient restClient; private final String restUriPath; private final int pollingMs; private final RetryPolicy retryPolicy; private final ScheduledExecutorService service = ThreadUtils.newSingleThreadScheduledExecutor("ExhibitorEnsembleProvider"); private final Random random = new Random(); private final AtomicReference connectionString = new AtomicReference(""); private final AtomicReference state = new AtomicReference(State.LATENT); private static final String MIME_TYPE = "application/x-www-form-urlencoded"; private static final String VALUE_PORT = "port"; private static final String VALUE_COUNT = "count"; private static final String VALUE_SERVER_PREFIX = "server"; private enum State { LATENT, STARTED, CLOSED } /** * @param exhibitors the current set of exhibitor instances (can be changed later via {@link #setExhibitors(Exhibitors)}) * @param restClient the rest client to use (use {@link DefaultExhibitorRestClient} for most cases) * @param restUriPath the path of the REST call used to get the server set. Usually: /exhibitor/v1/cluster/list * @param pollingMs how ofter to poll the exhibitors for the list * @param retryPolicy retry policy to use when connecting to the exhibitors */ public ExhibitorEnsembleProvider(Exhibitors exhibitors, ExhibitorRestClient restClient, String restUriPath, int pollingMs, RetryPolicy retryPolicy) { this.exhibitors.set(exhibitors); this.masterExhibitors.set(exhibitors); this.restClient = restClient; this.restUriPath = restUriPath; this.pollingMs = pollingMs; this.retryPolicy = retryPolicy; } /** * Change the set of exhibitors to poll * * @param newExhibitors new set */ public void setExhibitors(Exhibitors newExhibitors) { exhibitors.set(newExhibitors); masterExhibitors.set(newExhibitors); } /** * Can be called prior to starting the Curator instance to set the current connection string * * @throws Exception errors */ public void pollForInitialEnsemble() throws Exception { Preconditions.checkState(state.get() == State.LATENT, "Cannot be called after start()"); poll(); } @Override public void start() throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); service.scheduleWithFixedDelay ( new Runnable() { @Override public void run() { poll(); } }, pollingMs, pollingMs, TimeUnit.MILLISECONDS ); } @Override public void close() throws IOException { Preconditions.checkState(state.compareAndSet(State.STARTED, State.CLOSED), "Already closed or has not been started"); service.shutdownNow(); } @Override public String getConnectionString() { return connectionString.get(); } @VisibleForTesting protected void poll() { Exhibitors localExhibitors = exhibitors.get(); Map values = queryExhibitors(localExhibitors); int count = getCountFromValues(values); if ( count == 0 ) { log.warn("0 count returned from Exhibitors. Using backup connection values."); values = useBackup(localExhibitors); count = getCountFromValues(values); } if ( count > 0 ) { int port = Integer.parseInt(values.get(VALUE_PORT)); StringBuilder newConnectionString = new StringBuilder(); List newHostnames = Lists.newArrayList(); for ( int i = 0; i < count; ++i ) { if ( newConnectionString.length() > 0 ) { newConnectionString.append(","); } String server = values.get(VALUE_SERVER_PREFIX + i); newConnectionString.append(server).append(":").append(port); newHostnames.add(server); } String newConnectionStringValue = newConnectionString.toString(); if ( !newConnectionStringValue.equals(connectionString.get()) ) { log.info(String.format("Connection string has changed. Old value (%s), new value (%s)", connectionString.get(), newConnectionStringValue)); } Exhibitors newExhibitors = new Exhibitors ( newHostnames, localExhibitors.getRestPort(), new Exhibitors.BackupConnectionStringProvider() { @Override public String getBackupConnectionString() throws Exception { return masterExhibitors.get().getBackupConnectionString(); // this may be overloaded by clients. Make sure there is always a method call to get the value. } } ); connectionString.set(newConnectionStringValue); exhibitors.set(newExhibitors); } } private int getCountFromValues(Map values) { try { return Integer.parseInt(values.get(VALUE_COUNT)); } catch ( NumberFormatException e ) { // ignore } return 0; } private Map useBackup(Exhibitors localExhibitors) { Map values = newValues(); try { String backupConnectionString = localExhibitors.getBackupConnectionString(); int thePort = -1; int count = 0; for ( String spec : backupConnectionString.split(",") ) { spec = spec.trim(); String[] parts = spec.split(":"); if ( parts.length == 2 ) { String hostname = parts[0]; int port = Integer.parseInt(parts[1]); if ( thePort < 0 ) { thePort = port; } else if ( port != thePort ) { log.warn("Inconsistent port in connection component: " + spec); } values.put(VALUE_SERVER_PREFIX + count, hostname); ++count; } else { log.warn("Bad backup connection component: " + spec); } } values.put(VALUE_COUNT, Integer.toString(count)); values.put(VALUE_PORT, Integer.toString(thePort)); } catch ( Exception e ) { log.error("Couldn't get backup connection string", e); } return values; } private Map newValues() { Map values = Maps.newHashMap(); values.put(VALUE_COUNT, "0"); return values; } private static Map decodeExhibitorList(String str) throws UnsupportedEncodingException { Map values = Maps.newHashMap(); for ( String spec : str.split("&") ) { String[] parts = spec.split("="); if ( parts.length == 2 ) { values.put(parts[0], URLDecoder.decode(parts[1], "UTF-8")); } } return values; } private Map queryExhibitors(Exhibitors localExhibitors) { Map values = newValues(); long start = System.currentTimeMillis(); int retries = 0; boolean done = false; while ( !done ) { List hostnames = Lists.newArrayList(localExhibitors.getHostnames()); if ( hostnames.size() == 0 ) { done = true; } else { String hostname = hostnames.get(random.nextInt(hostnames.size())); try { String encoded = restClient.getRaw(hostname, localExhibitors.getRestPort(), restUriPath, MIME_TYPE); values.putAll(decodeExhibitorList(encoded)); done = true; } catch ( Throwable e ) { if ( retryPolicy.allowRetry(retries++, System.currentTimeMillis() - start, RetryLoop.getDefaultRetrySleeper()) ) { log.warn("Couldn't get servers from Exhibitor. Retrying.", e); } else { log.error("Couldn't get servers from Exhibitor. Giving up.", e); done = true; } } } } return values; } } ExhibitorRestClient.java000066400000000000000000000024071245521677600375010ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/ensemble/exhibitor/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.ensemble.exhibitor; public interface ExhibitorRestClient { /** * Connect to the given Exhibitor and return the raw result * * @param hostname host to connect to * @param port connect port * @param uriPath path * @param mimeType Accept mime type * @return raw result * @throws Exception errors */ public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception; } Exhibitors.java000066400000000000000000000045251245521677600356720ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/ensemble/exhibitor/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.ensemble.exhibitor; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import java.util.Collection; /** * POJO for specifying the cluster of Exhibitor instances */ public class Exhibitors { private final Collection hostnames; private final int restPort; private final BackupConnectionStringProvider backupConnectionStringProvider; public interface BackupConnectionStringProvider { public String getBackupConnectionString() throws Exception; } /** * @param hostnames set of Exhibitor instance host names * @param restPort the REST port used to connect to Exhibitor * @param backupConnectionStringProvider in case an Exhibitor instance can't be contacted, returns the fixed * connection string to use as a backup */ public Exhibitors(Collection hostnames, int restPort, BackupConnectionStringProvider backupConnectionStringProvider) { this.backupConnectionStringProvider = Preconditions.checkNotNull(backupConnectionStringProvider, "backupConnectionStringProvider cannot be null"); this.hostnames = ImmutableList.copyOf(hostnames); this.restPort = restPort; } public Collection getHostnames() { return hostnames; } public int getRestPort() { return restPort; } public String getBackupConnectionString() throws Exception { return backupConnectionStringProvider.getBackupConnectionString(); } } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/ensemble/fixed/000077500000000000000000000000001245521677600320625ustar00rootroot00000000000000FixedEnsembleProvider.java000066400000000000000000000032751245521677600371020ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/ensemble/fixed/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.ensemble.fixed; import com.google.common.base.Preconditions; import org.apache.curator.ensemble.EnsembleProvider; import java.io.IOException; /** * Standard ensemble provider that wraps a fixed connection string */ public class FixedEnsembleProvider implements EnsembleProvider { private final String connectionString; /** * The connection string to use * * @param connectionString connection string */ public FixedEnsembleProvider(String connectionString) { this.connectionString = Preconditions.checkNotNull(connectionString, "connectionString cannot be null"); } @Override public void start() throws Exception { // NOP } @Override public void close() throws IOException { // NOP } @Override public String getConnectionString() { return connectionString; } } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/retry/000077500000000000000000000000001245521677600303365ustar00rootroot00000000000000BoundedExponentialBackoffRetry.java000066400000000000000000000035101245521677600372120ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/retry/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.retry; import com.google.common.annotations.VisibleForTesting; /** * Retry policy that retries a set number of times with an increasing (up to a maximum bound) sleep time between retries */ public class BoundedExponentialBackoffRetry extends ExponentialBackoffRetry { private final int maxSleepTimeMs; /** * @param baseSleepTimeMs initial amount of time to wait between retries * @param maxSleepTimeMs maximum amount of time to wait between retries * @param maxRetries maximum number of times to retry */ public BoundedExponentialBackoffRetry(int baseSleepTimeMs, int maxSleepTimeMs, int maxRetries) { super(baseSleepTimeMs, maxRetries); this.maxSleepTimeMs = maxSleepTimeMs; } @VisibleForTesting public int getMaxSleepTimeMs() { return maxSleepTimeMs; } @Override protected int getSleepTimeMs(int retryCount, long elapsedTimeMs) { return Math.min(maxSleepTimeMs, super.getSleepTimeMs(retryCount, elapsedTimeMs)); } }ExponentialBackoffRetry.java000066400000000000000000000060561245521677600357210ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/retry/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.retry; import com.google.common.annotations.VisibleForTesting; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Random; /** * Retry policy that retries a set number of times with increasing sleep time between retries */ public class ExponentialBackoffRetry extends SleepingRetry { private static final Logger log = LoggerFactory.getLogger(ExponentialBackoffRetry.class); private static final int MAX_RETRIES_LIMIT = 29; private static final int DEFAULT_MAX_SLEEP_MS = Integer.MAX_VALUE; private final Random random = new Random(); private final int baseSleepTimeMs; private final int maxSleepMs; /** * @param baseSleepTimeMs initial amount of time to wait between retries * @param maxRetries max number of times to retry */ public ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries) { this(baseSleepTimeMs, maxRetries, DEFAULT_MAX_SLEEP_MS); } /** * @param baseSleepTimeMs initial amount of time to wait between retries * @param maxRetries max number of times to retry * @param maxSleepMs max time in ms to sleep on each retry */ public ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries, int maxSleepMs) { super(validateMaxRetries(maxRetries)); this.baseSleepTimeMs = baseSleepTimeMs; this.maxSleepMs = maxSleepMs; } @VisibleForTesting public int getBaseSleepTimeMs() { return baseSleepTimeMs; } @Override protected int getSleepTimeMs(int retryCount, long elapsedTimeMs) { // copied from Hadoop's RetryPolicies.java int sleepMs = baseSleepTimeMs * Math.max(1, random.nextInt(1 << (retryCount + 1))); if ( sleepMs > maxSleepMs ) { log.warn(String.format("Sleep extension too large (%d). Pinning to %d", sleepMs, maxSleepMs)); sleepMs = maxSleepMs; } return sleepMs; } private static int validateMaxRetries(int maxRetries) { if ( maxRetries > MAX_RETRIES_LIMIT ) { log.warn(String.format("maxRetries too large (%d). Pinning to %d", maxRetries, MAX_RETRIES_LIMIT)); maxRetries = MAX_RETRIES_LIMIT; } return maxRetries; } } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/retry/RetryNTimes.java000066400000000000000000000024011245521677600334230ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.retry; /** * Retry policy that retries a max number of times */ public class RetryNTimes extends SleepingRetry { private final int sleepMsBetweenRetries; public RetryNTimes(int n, int sleepMsBetweenRetries) { super(n); this.sleepMsBetweenRetries = sleepMsBetweenRetries; } @Override protected int getSleepTimeMs(int retryCount, long elapsedTimeMs) { return sleepMsBetweenRetries; } } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/retry/RetryOneTime.java000066400000000000000000000020231245521677600335640ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.retry; /** * A retry policy that retries only once */ public class RetryOneTime extends RetryNTimes { public RetryOneTime(int sleepMsBetweenRetry) { super(1, sleepMsBetweenRetry); } } RetryUntilElapsed.java000066400000000000000000000032371245521677600345460ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/retry/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.retry; import org.apache.curator.RetrySleeper; /** * A retry policy that retries until a given amount of time elapses */ public class RetryUntilElapsed extends SleepingRetry { private final int maxElapsedTimeMs; private final int sleepMsBetweenRetries; public RetryUntilElapsed(int maxElapsedTimeMs, int sleepMsBetweenRetries) { super(Integer.MAX_VALUE); this.maxElapsedTimeMs = maxElapsedTimeMs; this.sleepMsBetweenRetries = sleepMsBetweenRetries; } @Override public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) { return super.allowRetry(retryCount, elapsedTimeMs, sleeper) && (elapsedTimeMs < maxElapsedTimeMs); } @Override protected int getSleepTimeMs(int retryCount, long elapsedTimeMs) { return sleepMsBetweenRetries; } } SleepingRetry.java000066400000000000000000000033561245521677600337250ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/retry/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.retry; import org.apache.curator.RetryPolicy; import org.apache.curator.RetrySleeper; import java.util.concurrent.TimeUnit; abstract class SleepingRetry implements RetryPolicy { private final int n; protected SleepingRetry(int n) { this.n = n; } // made public for testing public int getN() { return n; } public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) { if ( retryCount < n ) { try { sleeper.sleepFor(getSleepTimeMs(retryCount, elapsedTimeMs), TimeUnit.MILLISECONDS); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); return false; } return true; } return false; } protected abstract int getSleepTimeMs(int retryCount, long elapsedTimeMs); } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/utils/000077500000000000000000000000001245521677600303315ustar00rootroot00000000000000CloseableExecutorService.java000066400000000000000000000135331245521677600360530ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/utils/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.utils; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.util.Iterator; import java.util.Set; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; /** * Decoration on an ExecutorService that tracks created futures and provides * a method to close futures created via this class */ public class CloseableExecutorService implements Closeable { private final Logger log = LoggerFactory.getLogger(CloseableExecutorService.class); private final Set> futures = Sets.newSetFromMap(Maps., Boolean>newConcurrentMap()); private final ExecutorService executorService; private final boolean shutdownOnClose; protected final AtomicBoolean isOpen = new AtomicBoolean(true); protected class InternalScheduledFutureTask implements Future { private final ScheduledFuture scheduledFuture; public InternalScheduledFutureTask(ScheduledFuture scheduledFuture) { this.scheduledFuture = scheduledFuture; futures.add(scheduledFuture); } @Override public boolean cancel(boolean mayInterruptIfRunning) { futures.remove(scheduledFuture); return scheduledFuture.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return scheduledFuture.isCancelled(); } @Override public boolean isDone() { return scheduledFuture.isDone(); } @Override public Void get() throws InterruptedException, ExecutionException { return null; } @Override public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return null; } } protected class InternalFutureTask extends FutureTask { private final RunnableFuture task; InternalFutureTask(RunnableFuture task) { super(task, null); this.task = task; futures.add(task); } protected void done() { futures.remove(task); } } /** * @param executorService the service to decorate */ public CloseableExecutorService(ExecutorService executorService) { this(executorService, false); } /** * @param executorService the service to decorate * @param shutdownOnClose if true, shutdown the executor service when this is closed */ public CloseableExecutorService(ExecutorService executorService, boolean shutdownOnClose) { this.executorService = Preconditions.checkNotNull(executorService, "executorService cannot be null"); this.shutdownOnClose = shutdownOnClose; } /** * Returns true if this executor has been shut down. * * @return true if this executor has been shut down */ public boolean isShutdown() { return !isOpen.get(); } @VisibleForTesting int size() { return futures.size(); } /** * Closes any tasks currently in progress */ @Override public void close() { isOpen.set(false); Iterator> iterator = futures.iterator(); while ( iterator.hasNext() ) { Future future = iterator.next(); iterator.remove(); if ( !future.isDone() && !future.isCancelled() && !future.cancel(true) ) { log.warn("Could not cancel " + future); } } if (shutdownOnClose) { executorService.shutdownNow(); } } /** * Submits a value-returning task for execution and returns a Future * representing the pending results of the task. Upon completion, * this task may be taken or polled. * * @param task the task to submit * @return a future to watch the task */ public Future submit(Callable task) { Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed"); InternalFutureTask futureTask = new InternalFutureTask(new FutureTask(task)); executorService.execute(futureTask); return futureTask; } /** * Submits a Runnable task for execution and returns a Future * representing that task. Upon completion, this task may be * taken or polled. * * @param task the task to submit * @return a future to watch the task */ public Future submit(Runnable task) { Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed"); InternalFutureTask futureTask = new InternalFutureTask(new FutureTask(task, null)); executorService.execute(futureTask); return futureTask; } } CloseableScheduledExecutorService.java000066400000000000000000000103311245521677600376650ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/utils/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.utils; import com.google.common.base.Preconditions; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * Decoration on an ScheduledExecutorService that tracks created futures and provides * a method to close futures created via this class */ public class CloseableScheduledExecutorService extends CloseableExecutorService { private final ScheduledExecutorService scheduledExecutorService; /** * @param scheduledExecutorService the service to decorate */ public CloseableScheduledExecutorService(ScheduledExecutorService scheduledExecutorService) { super(scheduledExecutorService, false); this.scheduledExecutorService = scheduledExecutorService; } /** * @param scheduledExecutorService the service to decorate * @param shutdownOnClose if true, shutdown the executor service when this is closed */ public CloseableScheduledExecutorService(ScheduledExecutorService scheduledExecutorService, boolean shutdownOnClose) { super(scheduledExecutorService, shutdownOnClose); this.scheduledExecutorService = scheduledExecutorService; } /** * Creates and executes a one-shot action that becomes enabled * after the given delay. * * @param task the task to execute * @param delay the time from now to delay execution * @param unit the time unit of the delay parameter * @return a Future representing pending completion of * the task and whose get() method will return * null upon completion */ public Future schedule(Runnable task, long delay, TimeUnit unit) { Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed"); InternalFutureTask futureTask = new InternalFutureTask(new FutureTask(task, null)); scheduledExecutorService.schedule(futureTask, delay, unit); return futureTask; } /** * Creates and executes a periodic action that becomes enabled first * after the given initial delay, and subsequently with the * given delay between the termination of one execution and the * commencement of the next. If any execution of the task * encounters an exception, subsequent executions are suppressed. * Otherwise, the task will only terminate via cancellation or * termination of the executor. * * @param task the task to execute * @param initialDelay the time to delay first execution * @param delay the delay between the termination of one * execution and the commencement of the next * @param unit the time unit of the initialDelay and delay parameters * @return a Future representing pending completion of * the task, and whose get() method will throw an * exception upon cancellation */ public Future scheduleWithFixedDelay(Runnable task, long initialDelay, long delay, TimeUnit unit) { Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed"); ScheduledFuture scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(task, initialDelay, delay, unit); return new InternalScheduledFutureTask(scheduledFuture); } } CloseableUtils.java000066400000000000000000000050001245521677600340220ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/utils/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.utils; import com.google.common.io.Closeables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; /** * This class adds back functionality that was removed in Guava v16.0. */ public class CloseableUtils { private static final Logger log = LoggerFactory.getLogger(CloseableUtils.class); /** *

* This method has been added because Guava has removed the * {@code closeQuietly()} method from {@code Closeables} in v16.0. It's * tempting simply to replace calls to {@code closeQuietly(closeable)} * with calls to {@code close(closeable, true)} to close * {@code Closeable}s while swallowing {@code IOException}s, but * {@code close()} is declared as {@code throws IOException} whereas * {@code closeQuietly()} is not, so it's not a drop-in replacement. *

*

* On the whole, Guava is very backwards compatible. By fixing this nit, * Curator can continue to support newer versions of Guava without having * to bump its own dependency version. *

*

* See https://issues.apache.org/jira/browse/CURATOR-85 *

*/ public static void closeQuietly(Closeable closeable) { try { // Here we've instructed Guava to swallow the IOException Closeables.close(closeable, true); } catch ( IOException e ) { // We instructed Guava to swallow the IOException, so this should // never happen. Since it did, log it. log.error("IOException should not have been thrown.", e); } } } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/utils/DebugUtils.java000066400000000000000000000023641245521677600332500ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.utils; public class DebugUtils { public static final String PROPERTY_LOG_EVENTS = "curator-log-events"; public static final String PROPERTY_DONT_LOG_CONNECTION_ISSUES = "curator-dont-log-connection-problems"; public static final String PROPERTY_LOG_ONLY_FIRST_CONNECTION_ISSUE_AS_ERROR_LEVEL = "curator-log-only-first-connection-issue-as-error-level"; private DebugUtils() { } } DefaultTracerDriver.java000066400000000000000000000030731245521677600350210ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/utils/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.utils; import org.apache.curator.drivers.TracerDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.TimeUnit; /** * Default tracer driver */ public class DefaultTracerDriver implements TracerDriver { private final Logger log = LoggerFactory.getLogger(getClass()); @Override public void addTrace(String name, long time, TimeUnit unit) { if ( log.isTraceEnabled() ) { log.trace("Trace: " + name + " - " + TimeUnit.MILLISECONDS.convert(time, unit) + " ms"); } } @Override public void addCount(String name, int increment) { if ( log.isTraceEnabled() ) { log.trace("Counter " + name + ": " + increment); } } } DefaultZookeeperFactory.java000066400000000000000000000023221245521677600357140ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/utils/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.utils; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; public class DefaultZookeeperFactory implements ZookeeperFactory { @Override public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly) throws Exception { return new ZooKeeper(connectString, sessionTimeout, watcher, canBeReadOnly); } } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/utils/EnsurePath.java000066400000000000000000000117621245521677600332610ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.utils; import org.apache.curator.CuratorZookeeperClient; import org.apache.curator.RetryLoop; import org.apache.zookeeper.ZooKeeper; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicReference; /** *

* Utility to ensure that a particular path is created. *

*

* The first time it is used, a synchronized call to {@link ZKPaths#mkdirs(ZooKeeper, String)} is made to * ensure that the entire path has been created (with an empty byte array if needed). Subsequent * calls with the instance are un-synchronized NOPs. *

*

* Usage:
*

*
 *         EnsurePath       ensurePath = new EnsurePath(aFullPathToEnsure);
 *         ...
 *         String           nodePath = aFullPathToEnsure + "/foo";
 *         ensurePath.ensure(zk);   // first time syncs and creates if needed
 *         zk.create(nodePath, ...);
 *         ...
 *         ensurePath.ensure(zk);   // subsequent times are NOPs
 *         zk.create(nodePath, ...);
 * 
*/ public class EnsurePath { private final String path; private final boolean makeLastNode; private final InternalACLProvider aclProvider; private final AtomicReference helper; private static final Helper doNothingHelper = new Helper() { @Override public void ensure(CuratorZookeeperClient client, String path, final boolean makeLastNode) throws Exception { // NOP } }; private interface Helper { public void ensure(CuratorZookeeperClient client, String path, final boolean makeLastNode) throws Exception; } /** * @param path the full path to ensure */ public EnsurePath(String path) { this(path, null, true, null); } /** * @param path the full path to ensure * @param aclProvider if not null, the ACL provider to use when creating parent nodes */ public EnsurePath(String path, InternalACLProvider aclProvider) { this(path, null, true, aclProvider); } /** * First time, synchronizes and makes sure all nodes in the path are created. Subsequent calls * with this instance are NOPs. * * @param client ZK client * @throws Exception ZK errors */ public void ensure(CuratorZookeeperClient client) throws Exception { Helper localHelper = helper.get(); localHelper.ensure(client, path, makeLastNode); } /** * Returns a view of this EnsurePath instance that does not make the last node. * i.e. if the path is "/a/b/c" only "/a/b" will be ensured * * @return view */ public EnsurePath excludingLast() { return new EnsurePath(path, helper, false, aclProvider); } private EnsurePath(String path, AtomicReference helper, boolean makeLastNode, InternalACLProvider aclProvider) { this.path = path; this.makeLastNode = makeLastNode; this.aclProvider = aclProvider; this.helper = (helper != null) ? helper : new AtomicReference(new InitialHelper()); } /** * Returns the path being Ensured * * @return the path being ensured */ public String getPath() { return this.path; } private class InitialHelper implements Helper { private boolean isSet = false; // guarded by synchronization @Override public synchronized void ensure(final CuratorZookeeperClient client, final String path, final boolean makeLastNode) throws Exception { if ( !isSet ) { RetryLoop.callWithRetry ( client, new Callable() { @Override public Object call() throws Exception { ZKPaths.mkdirs(client.getZooKeeper(), path, makeLastNode, aclProvider); helper.set(doNothingHelper); isSet = true; return null; } } ); } } } } InternalACLProvider.java000066400000000000000000000025351245521677600347310ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/utils/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.utils; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; import java.util.List; public interface InternalACLProvider { /** * Return the ACL list to use by default (usually {@link ZooDefs.Ids#OPEN_ACL_UNSAFE}). * * @return default ACL list */ public List getDefaultAcl(); /** * Return the ACL list to use for the given path * * @param path path (NOTE: might be null) * @return ACL list */ public List getAclForPath(String path); } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/utils/PathUtils.java000066400000000000000000000100411245521677600331050ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.utils; /** * This class is copied from Apache ZooKeeper. * The original class is not exported by ZooKeeper bundle and thus it can't be used in OSGi. * See issue: https://issues.apache.org/jira/browse/ZOOKEEPER-1627 * A temporary workaround till the issue is resolved is to keep a copy of this class locally. */ public class PathUtils { /** validate the provided znode path string * @param path znode path string * @param isSequential if the path is being created * with a sequential flag * @throws IllegalArgumentException if the path is invalid */ public static void validatePath(String path, boolean isSequential) throws IllegalArgumentException { validatePath(isSequential? path + "1": path); } /** * Validate the provided znode path string * @param path znode path string * @return The given path if it was valid, for fluent chaining * @throws IllegalArgumentException if the path is invalid */ public static String validatePath(String path) throws IllegalArgumentException { if (path == null) { throw new IllegalArgumentException("Path cannot be null"); } if (path.length() == 0) { throw new IllegalArgumentException("Path length must be > 0"); } if (path.charAt(0) != '/') { throw new IllegalArgumentException( "Path must start with / character"); } if (path.length() == 1) { // done checking - it's the root return path; } if (path.charAt(path.length() - 1) == '/') { throw new IllegalArgumentException( "Path must not end with / character"); } String reason = null; char lastc = '/'; char chars[] = path.toCharArray(); char c; for (int i = 1; i < chars.length; lastc = chars[i], i++) { c = chars[i]; if (c == 0) { reason = "null character not allowed @" + i; break; } else if (c == '/' && lastc == '/') { reason = "empty node name specified @" + i; break; } else if (c == '.' && lastc == '.') { if (chars[i-2] == '/' && ((i + 1 == chars.length) || chars[i+1] == '/')) { reason = "relative paths not allowed @" + i; break; } } else if (c == '.') { if (chars[i-1] == '/' && ((i + 1 == chars.length) || chars[i+1] == '/')) { reason = "relative paths not allowed @" + i; break; } } else if (c > '\u0000' && c < '\u001f' || c > '\u007f' && c < '\u009F' || c > '\ud800' && c < '\uf8ff' || c > '\ufff0' && c < '\uffff') { reason = "invalid charater @" + i; break; } } if (reason != null) { throw new IllegalArgumentException( "Invalid path string \"" + path + "\" caused by " + reason); } return path; } } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/utils/ThreadUtils.java000066400000000000000000000046451245521677600334350ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.utils; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; public class ThreadUtils { public static ExecutorService newSingleThreadExecutor(String processName) { return Executors.newSingleThreadExecutor(newThreadFactory(processName)); } public static ExecutorService newFixedThreadPool(int qty, String processName) { return Executors.newFixedThreadPool(qty, newThreadFactory(processName)); } public static ScheduledExecutorService newSingleThreadScheduledExecutor(String processName) { return Executors.newSingleThreadScheduledExecutor(newThreadFactory(processName)); } public static ScheduledExecutorService newFixedThreadScheduledPool(int qty, String processName) { return Executors.newScheduledThreadPool(qty, newThreadFactory(processName)); } public static ThreadFactory newThreadFactory(String processName) { return newGenericThreadFactory("Curator-" + processName); } public static ThreadFactory newGenericThreadFactory(String processName) { return new ThreadFactoryBuilder() .setNameFormat(processName + "-%d") .setDaemon(true) .build(); } public static String getProcessName(Class clazz) { if ( clazz.isAnonymousClass() ) { return getProcessName(clazz.getEnclosingClass()); } return clazz.getSimpleName(); } } curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/utils/ZKPaths.java000066400000000000000000000306261245521677600325270ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.utils; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.ACL; import java.util.Collections; import java.util.List; public class ZKPaths { /** * Zookeeper's path separator character. */ public static final String PATH_SEPARATOR = "/"; /** * Apply the namespace to the given path * * @param namespace namespace (can be null) * @param path path * @return adjusted path */ public static String fixForNamespace(String namespace, String path) { return fixForNamespace(namespace, path, false); } /** * Apply the namespace to the given path * * @param namespace namespace (can be null) * @param path path * @param isSequential if the path is being created with a sequential flag * @return adjusted path */ public static String fixForNamespace(String namespace, String path, boolean isSequential) { // Child path must be valid in and of itself. PathUtils.validatePath(path, isSequential); if ( namespace != null ) { return makePath(namespace, path); } return path; } /** * Given a full path, return the node name. i.e. "/one/two/three" will return "three" * * @param path the path * @return the node */ public static String getNodeFromPath(String path) { PathUtils.validatePath(path); int i = path.lastIndexOf(PATH_SEPARATOR); if ( i < 0 ) { return path; } if ( (i + 1) >= path.length() ) { return ""; } return path.substring(i + 1); } public static class PathAndNode { private final String path; private final String node; public PathAndNode(String path, String node) { this.path = path; this.node = node; } public String getPath() { return path; } public String getNode() { return node; } } /** * Given a full path, return the node name and its path. i.e. "/one/two/three" will return {"/one/two", "three"} * * @param path the path * @return the node */ public static PathAndNode getPathAndNode(String path) { PathUtils.validatePath(path); int i = path.lastIndexOf(PATH_SEPARATOR); if ( i < 0 ) { return new PathAndNode(path, ""); } if ( (i + 1) >= path.length() ) { return new PathAndNode(PATH_SEPARATOR, ""); } String node = path.substring(i + 1); String parentPath = (i > 0) ? path.substring(0, i) : PATH_SEPARATOR; return new PathAndNode(parentPath, node); } private static final Splitter PATH_SPLITTER = Splitter.on(PATH_SEPARATOR).omitEmptyStrings(); /** * Given a full path, return the the individual parts, without slashes. * The root path will return an empty list. * * @param path the path * @return an array of parts */ public static List split(String path) { PathUtils.validatePath(path); return PATH_SPLITTER.splitToList(path); } /** * Make sure all the nodes in the path are created. NOTE: Unlike File.mkdirs(), Zookeeper doesn't distinguish * between directories and files. So, every node in the path is created. The data for each node is an empty blob * * @param zookeeper the client * @param path path to ensure * @throws InterruptedException thread interruption * @throws org.apache.zookeeper.KeeperException Zookeeper errors */ public static void mkdirs(ZooKeeper zookeeper, String path) throws InterruptedException, KeeperException { mkdirs(zookeeper, path, true, null); } /** * Make sure all the nodes in the path are created. NOTE: Unlike File.mkdirs(), Zookeeper doesn't distinguish * between directories and files. So, every node in the path is created. The data for each node is an empty blob * * @param zookeeper the client * @param path path to ensure * @param makeLastNode if true, all nodes are created. If false, only the parent nodes are created * @throws InterruptedException thread interruption * @throws org.apache.zookeeper.KeeperException Zookeeper errors */ public static void mkdirs(ZooKeeper zookeeper, String path, boolean makeLastNode) throws InterruptedException, KeeperException { mkdirs(zookeeper, path, makeLastNode, null); } /** * Make sure all the nodes in the path are created. NOTE: Unlike File.mkdirs(), Zookeeper doesn't distinguish * between directories and files. So, every node in the path is created. The data for each node is an empty blob * * @param zookeeper the client * @param path path to ensure * @param makeLastNode if true, all nodes are created. If false, only the parent nodes are created * @param aclProvider if not null, the ACL provider to use when creating parent nodes * @throws InterruptedException thread interruption * @throws org.apache.zookeeper.KeeperException Zookeeper errors */ public static void mkdirs(ZooKeeper zookeeper, String path, boolean makeLastNode, InternalACLProvider aclProvider) throws InterruptedException, KeeperException { PathUtils.validatePath(path); int pos = 1; // skip first slash, root is guaranteed to exist do { pos = path.indexOf(PATH_SEPARATOR, pos + 1); if ( pos == -1 ) { if ( makeLastNode ) { pos = path.length(); } else { break; } } String subPath = path.substring(0, pos); if ( zookeeper.exists(subPath, false) == null ) { try { List acl = null; if ( aclProvider != null ) { acl = aclProvider.getAclForPath(path); if ( acl == null ) { acl = aclProvider.getDefaultAcl(); } } if ( acl == null ) { acl = ZooDefs.Ids.OPEN_ACL_UNSAFE; } zookeeper.create(subPath, new byte[0], acl, CreateMode.PERSISTENT); } catch ( KeeperException.NodeExistsException e ) { // ignore... someone else has created it since we checked } } } while ( pos < path.length() ); } /** * Recursively deletes children of a node. * * @param zookeeper the client * @param path path of the node to delete * @param deleteSelf flag that indicates that the node should also get deleted * @throws InterruptedException * @throws KeeperException */ public static void deleteChildren(ZooKeeper zookeeper, String path, boolean deleteSelf) throws InterruptedException, KeeperException { PathUtils.validatePath(path); List children = zookeeper.getChildren(path, null); for ( String child : children ) { String fullPath = makePath(path, child); deleteChildren(zookeeper, fullPath, true); } if ( deleteSelf ) { try { zookeeper.delete(path, -1); } catch ( KeeperException.NotEmptyException e ) { //someone has created a new child since we checked ... delete again. deleteChildren(zookeeper, path, true); } catch ( KeeperException.NoNodeException e ) { // ignore... someone else has deleted the node it since we checked } } } /** * Return the children of the given path sorted by sequence number * * @param zookeeper the client * @param path the path * @return sorted list of children * @throws InterruptedException thread interruption * @throws org.apache.zookeeper.KeeperException zookeeper errors */ public static List getSortedChildren(ZooKeeper zookeeper, String path) throws InterruptedException, KeeperException { List children = zookeeper.getChildren(path, false); List sortedList = Lists.newArrayList(children); Collections.sort(sortedList); return sortedList; } /** * Given a parent path and a child node, create a combined full path * * @param parent the parent * @param child the child * @return full path */ public static String makePath(String parent, String child) { StringBuilder path = new StringBuilder(); joinPath(path, parent, child); return path.toString(); } /** * Given a parent path and a list of children nodes, create a combined full path * * @param parent the parent * @param firstChild the first children in the path * @param restChildren the rest of the children in the path * @return full path */ public static String makePath(String parent, String firstChild, String... restChildren) { StringBuilder path = new StringBuilder(); joinPath(path, parent, firstChild); if ( restChildren == null ) { return path.toString(); } else { for ( String child : restChildren ) { joinPath(path, "", child); } return path.toString(); } } /** * Given a parent and a child node, join them in the given {@link StringBuilder path} * * @param path the {@link StringBuilder} used to make the path * @param parent the parent * @param child the child */ private static void joinPath(StringBuilder path, String parent, String child) { // Add parent piece, with no trailing slash. if ( (parent != null) && (parent.length() > 0) ) { if ( !parent.startsWith(PATH_SEPARATOR) ) { path.append(PATH_SEPARATOR); } if ( parent.endsWith(PATH_SEPARATOR) ) { path.append(parent.substring(0, parent.length() - 1)); } else { path.append(parent); } } if ( (child == null) || (child.length() == 0) || (child.equals(PATH_SEPARATOR)) ) { // Special case, empty parent and child if ( path.length() == 0 ) { path.append(PATH_SEPARATOR); } return; } // Now add the separator between parent and child. path.append(PATH_SEPARATOR); if ( child.startsWith(PATH_SEPARATOR) ) { child = child.substring(1); } if ( child.endsWith(PATH_SEPARATOR) ) { child = child.substring(0, child.length() - 1); } // Finally, add the child. path.append(child); } private ZKPaths() { } } ZookeeperFactory.java000066400000000000000000000032061245521677600344110ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/main/java/org/apache/curator/utils/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.utils; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; public interface ZookeeperFactory { /** * Allocate a new ZooKeeper instance * * * @param connectString the connection string * @param sessionTimeout session timeout in milliseconds * @param watcher optional watcher * @param canBeReadOnly if true, allow ZooKeeper client to enter * read only mode in case of a network partition. See * {@link ZooKeeper#ZooKeeper(String, int, Watcher, long, byte[], boolean)} * for details * @return the instance * @throws Exception errors */ public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly) throws Exception; } curator-apache-curator-2.7.1/curator-client/src/site/000077500000000000000000000000001245521677600226015ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/site/confluence/000077500000000000000000000000001245521677600247225ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/site/confluence/index.confluence000066400000000000000000000074651245521677600301100ustar00rootroot00000000000000h1. Client h2. IMPORTANT NOTE The Curator Client is a low\-level API. It is strongly recommended that you use the Curator [[Framework|../curator-framework/index.html]] instead of directly using CuratorZookeeperClient. h2. Background CuratorZookeeperClient is a wrapper around ZooKeeper's Java client that makes client access to ZooKeeper much simpler and less error prone. It provides the following features: * Continuous connection management \- ZooKeeper has many caveats regarding connection management (see the ZooKeeper FAQ for details). CuratorZookeeperClient takes care of most of them automatically. * Operation retry utilities \- a method for retrying operations is provided * Test ZooKeeper server \- an in\-process, self\-contained ZooKeeper test server is provided that can be used for test cases and experimentation h2. Method Documentation ||Method||Description|| |_Constructor_|Create a connection to a given ZooKeeper cluster. You can pass in an optional watcher. You must provide a Retry Policy.| |getZooKeeper()|Returns the managed ZooKeeper instance. *IMPORTANT NOTES:* a) It takes time for a connection to complete, you should validate that the connection is complete before using other methods. b) The managed ZooKeeper instance can change due to certain events. Do not hold on to the instance for long periods. Always get a fresh reference from getZooKeeper().| |isConnected()|Returns true if the ZooKeeper client is currently connected (this can always change due to errors)| |blockUntilConnectedOrTimedOut()|A convenience method that blocks until the initial connection is successful or times out| |close()|Close the connection| |setRetryPolicy()|Change the retry policy| |newRetryLoop()|Allocate a new Retry Loop \- see details below| h2. Retry Loop For a variety of reasons, operations on a ZooKeeper cluster can fail. Best practices dictate that these operations should be retried. The Retry Loop mechanism provides the means to do this. *Every operation should be wrapped in a retry loop*. Here's the canonical usage: {code} RetryLoop retryLoop = client.newRetryLoop(); while ( retryLoop.shouldContinue() ) { try { // perform your work ... // it's important to re\-get the ZK instance as there may have been an error and the instance was re\-created ZooKeeper zk = client.getZookeeper(); retryLoop.markComplete(); } catch ( Exception e ) { retryLoop.takeException(e); } } {code} The Retry Loop maintains a count of retries and determines if a given error is retry\-able. If an operation is a candidate for retrying, the Retry Policy is invoked to determine if the retry should proceed. As a convenience, RetryLoop has a static method that takes a Callable to perform a complete retry loop on. E.g. {code} RetryLoop.callWithRetry(client, new Callable() { @Override public Void call() throws Exception { // do your work here - it will get retried if needed return null; } }); {code} h2. Retry Policies A retry policy is a mechanism to alter retry behavior. It is abstracted by the RetryPolicy interface which has one method: {{public boolean allowRetry(int retryCount, long elapsedTimeMs);}} Before a retry is attempted, allowRetry() is called with the current retry count and the elapsed time of the operation. If the policy allows it, the retry is attempted. If not, an exception is thrown. Several retry policy implementations are provided (in the package {{com.netflix.curator.retry}}): ||Policy Name||Description|| |ExponentialBackoffRetry|Retry policy that retries a set number of times with increasing sleep time between retries| |RetryNTimes|Retry policy that retries a max number of times| |RetryOneTime|A retry policy that retries only once| |RetryUntilElapsed|A retry policy that retries until a given amount of time elapses| curator-apache-curator-2.7.1/curator-client/src/site/site.xml000066400000000000000000000026241245521677600242730ustar00rootroot00000000000000 curator-apache-curator-2.7.1/curator-client/src/test/000077500000000000000000000000001245521677600226145ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/test/java/000077500000000000000000000000001245521677600235355ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/test/java/org/000077500000000000000000000000001245521677600243245ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/test/java/org/apache/000077500000000000000000000000001245521677600255455ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/test/java/org/apache/curator/000077500000000000000000000000001245521677600272245ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/test/java/org/apache/curator/BasicTests.java000066400000000000000000000154241245521677600321410ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator; import org.apache.curator.ensemble.fixed.FixedEnsembleProvider; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.KillSession; import org.apache.curator.test.Timing; import org.apache.curator.utils.ZookeeperFactory; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; public class BasicTests extends BaseClassForTests { @Test public void testFactory() throws Exception { final ZooKeeper mockZookeeper = Mockito.mock(ZooKeeper.class); ZookeeperFactory zookeeperFactory = new ZookeeperFactory() { @Override public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly) throws Exception { return mockZookeeper; } }; CuratorZookeeperClient client = new CuratorZookeeperClient(zookeeperFactory, new FixedEnsembleProvider(server.getConnectString()), 10000, 10000, null, new RetryOneTime(1), false); client.start(); Assert.assertEquals(client.getZooKeeper(), mockZookeeper); } @Test public void testExpiredSession() throws Exception { // see http://wiki.apache.org/hadoop/ZooKeeper/FAQ#A4 final Timing timing = new Timing(); final CountDownLatch latch = new CountDownLatch(1); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { if ( event.getState() == Event.KeeperState.Expired ) { latch.countDown(); } } }; final CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), timing.session(), timing.connection(), watcher, new RetryOneTime(2)); client.start(); try { final AtomicBoolean firstTime = new AtomicBoolean(true); RetryLoop.callWithRetry ( client, new Callable() { @Override public Object call() throws Exception { if ( firstTime.compareAndSet(true, false) ) { try { client.getZooKeeper().create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch ( KeeperException.NodeExistsException ignore ) { // ignore } KillSession.kill(client.getZooKeeper(), server.getConnectString()); Assert.assertTrue(timing.awaitLatch(latch)); } ZooKeeper zooKeeper = client.getZooKeeper(); client.blockUntilConnectedOrTimedOut(); Assert.assertNotNull(zooKeeper.exists("/foo", false)); return null; } } ); } finally { client.close(); } } @Test public void testReconnect() throws Exception { CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), 10000, 10000, null, new RetryOneTime(1)); client.start(); try { client.blockUntilConnectedOrTimedOut(); byte[] writtenData = {1, 2, 3}; client.getZooKeeper().create("/test", writtenData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); Thread.sleep(1000); server.stop(); Thread.sleep(1000); server.restart(); Assert.assertTrue(client.blockUntilConnectedOrTimedOut()); byte[] readData = client.getZooKeeper().getData("/test", false, null); Assert.assertEquals(readData, writtenData); } finally { client.close(); } } @Test public void testSimple() throws Exception { CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), 10000, 10000, null, new RetryOneTime(1)); client.start(); try { client.blockUntilConnectedOrTimedOut(); String path = client.getZooKeeper().create("/test", new byte[]{1,2,3}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); Assert.assertEquals(path, "/test"); } finally { client.close(); } } @Test public void testBackgroundConnect() throws Exception { final int CONNECTION_TIMEOUT_MS = 4000; CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), 10000, CONNECTION_TIMEOUT_MS, null, new RetryOneTime(1)); try { Assert.assertFalse(client.isConnected()); client.start(); outer: do { for ( int i = 0; i < (CONNECTION_TIMEOUT_MS / 1000); ++i ) { if ( client.isConnected() ) { break outer; } Thread.sleep(CONNECTION_TIMEOUT_MS); } Assert.fail(); } while ( false ); } finally { client.close(); } } } curator-apache-curator-2.7.1/curator-client/src/test/java/org/apache/curator/TestEnsurePath.java000066400000000000000000000117121245521677600330070ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.utils.EnsurePath; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.testng.Assert; import org.testng.annotations.Test; public class TestEnsurePath { @Test public void testBasic() throws Exception { ZooKeeper client = mock(ZooKeeper.class, Mockito.RETURNS_MOCKS); CuratorZookeeperClient curator = mock(CuratorZookeeperClient.class); RetryPolicy retryPolicy = new RetryOneTime(1); RetryLoop retryLoop = new RetryLoop(retryPolicy, null); when(curator.getZooKeeper()).thenReturn(client); when(curator.getRetryPolicy()).thenReturn(retryPolicy); when(curator.newRetryLoop()).thenReturn(retryLoop); Stat fakeStat = mock(Stat.class); when(client.exists(Mockito.any(), anyBoolean())).thenReturn(fakeStat); EnsurePath ensurePath = new EnsurePath("/one/two/three"); ensurePath.ensure(curator); verify(client, times(3)).exists(Mockito.any(), anyBoolean()); ensurePath.ensure(curator); verifyNoMoreInteractions(client); ensurePath.ensure(curator); verifyNoMoreInteractions(client); } @Test public void testSimultaneous() throws Exception { ZooKeeper client = mock(ZooKeeper.class, Mockito.RETURNS_MOCKS); RetryPolicy retryPolicy = new RetryOneTime(1); RetryLoop retryLoop = new RetryLoop(retryPolicy, null); final CuratorZookeeperClient curator = mock(CuratorZookeeperClient.class); when(curator.getZooKeeper()).thenReturn(client); when(curator.getRetryPolicy()).thenReturn(retryPolicy); when(curator.newRetryLoop()).thenReturn(retryLoop); final Stat fakeStat = mock(Stat.class); final CountDownLatch startedLatch = new CountDownLatch(2); final CountDownLatch finishedLatch = new CountDownLatch(2); final Semaphore semaphore = new Semaphore(0); when(client.exists(Mockito.any(), anyBoolean())).thenAnswer ( new Answer() { @Override public Stat answer(InvocationOnMock invocation) throws Throwable { semaphore.acquire(); return fakeStat; } } ); final EnsurePath ensurePath = new EnsurePath("/one/two/three"); ExecutorService service = Executors.newCachedThreadPool(); for ( int i = 0; i < 2; ++i ) { service.submit ( new Callable() { @Override public Void call() throws Exception { startedLatch.countDown(); ensurePath.ensure(curator); finishedLatch.countDown(); return null; } } ); } Assert.assertTrue(startedLatch.await(10, TimeUnit.SECONDS)); semaphore.release(3); Assert.assertTrue(finishedLatch.await(10, TimeUnit.SECONDS)); verify(client, times(3)).exists(Mockito.any(), anyBoolean()); ensurePath.ensure(curator); verifyNoMoreInteractions(client); ensurePath.ensure(curator); verifyNoMoreInteractions(client); } } curator-apache-curator-2.7.1/curator-client/src/test/java/org/apache/curator/TestRetryLoop.java000066400000000000000000000106751245521677600326770ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooDefs; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; public class TestRetryLoop extends BaseClassForTests { @Test public void testExponentialBackoffRetryLimit() { RetrySleeper sleeper = new RetrySleeper() { @Override public void sleepFor(long time, TimeUnit unit) throws InterruptedException { Assert.assertTrue(unit.toMillis(time) <= 100); } }; ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1, Integer.MAX_VALUE, 100); for ( int i = 0; i >= 0; ++i ) { retry.allowRetry(i, 0, sleeper); } } @Test public void testRetryLoopWithFailure() throws Exception { CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), 5000, 5000, null, new RetryOneTime(1)); client.start(); try { int loopCount = 0; RetryLoop retryLoop = client.newRetryLoop(); outer: while ( retryLoop.shouldContinue() ) { ++loopCount; switch ( loopCount ) { case 1: { server.stop(); break; } case 2: { server.restart(); break; } case 3: case 4: { // ignore break; } default: { Assert.fail(); break outer; } } try { client.blockUntilConnectedOrTimedOut(); client.getZooKeeper().create("/test", new byte[]{1,2,3}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); retryLoop.markComplete(); } catch ( Exception e ) { retryLoop.takeException(e); } } Assert.assertTrue(loopCount >= 2); } finally { client.close(); } } @Test public void testRetryLoop() throws Exception { CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), 10000, 10000, null, new RetryOneTime(1)); client.start(); try { int loopCount = 0; RetryLoop retryLoop = client.newRetryLoop(); while ( retryLoop.shouldContinue() ) { if ( ++loopCount > 2 ) { Assert.fail(); break; } try { client.getZooKeeper().create("/test", new byte[]{1,2,3}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); retryLoop.markComplete(); } catch ( Exception e ) { retryLoop.takeException(e); } } Assert.assertTrue(loopCount > 0); } finally { client.close(); } } } TestSessionFailRetryLoop.java000066400000000000000000000261161245521677600347550ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/test/java/org/apache/curator/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.KillSession; import org.apache.curator.test.Timing; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicBoolean; public class TestSessionFailRetryLoop extends BaseClassForTests { @Test public void testRetry() throws Exception { Timing timing = new Timing(); final CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), timing.session(), timing.connection(), null, new RetryOneTime(1)); SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.RETRY); retryLoop.start(); try { client.start(); final AtomicBoolean secondWasDone = new AtomicBoolean(false); final AtomicBoolean firstTime = new AtomicBoolean(true); while ( retryLoop.shouldContinue() ) { try { RetryLoop.callWithRetry ( client, new Callable() { @Override public Void call() throws Exception { if ( firstTime.compareAndSet(true, false) ) { Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false)); KillSession.kill(client.getZooKeeper(), server.getConnectString()); client.getZooKeeper(); client.blockUntilConnectedOrTimedOut(); } Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false)); return null; } } ); RetryLoop.callWithRetry ( client, new Callable() { @Override public Void call() throws Exception { Assert.assertFalse(firstTime.get()); Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false)); secondWasDone.set(true); return null; } } ); } catch ( Exception e ) { retryLoop.takeException(e); } } Assert.assertTrue(secondWasDone.get()); } finally { retryLoop.close(); CloseableUtils.closeQuietly(client); } } @Test public void testRetryStatic() throws Exception { Timing timing = new Timing(); final CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), timing.session(), timing.connection(), null, new RetryOneTime(1)); SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.RETRY); retryLoop.start(); try { client.start(); final AtomicBoolean secondWasDone = new AtomicBoolean(false); final AtomicBoolean firstTime = new AtomicBoolean(true); SessionFailRetryLoop.callWithRetry ( client, SessionFailRetryLoop.Mode.RETRY, new Callable() { @Override public Object call() throws Exception { RetryLoop.callWithRetry ( client, new Callable() { @Override public Void call() throws Exception { if ( firstTime.compareAndSet(true, false) ) { Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false)); KillSession.kill(client.getZooKeeper(), server.getConnectString()); client.getZooKeeper(); client.blockUntilConnectedOrTimedOut(); } Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false)); return null; } } ); RetryLoop.callWithRetry ( client, new Callable() { @Override public Void call() throws Exception { Assert.assertFalse(firstTime.get()); Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false)); secondWasDone.set(true); return null; } } ); return null; } } ); Assert.assertTrue(secondWasDone.get()); } finally { retryLoop.close(); CloseableUtils.closeQuietly(client); } } @Test public void testBasic() throws Exception { Timing timing = new Timing(); final CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), timing.session(), timing.connection(), null, new RetryOneTime(1)); SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.FAIL); retryLoop.start(); try { client.start(); try { while ( retryLoop.shouldContinue() ) { try { RetryLoop.callWithRetry ( client, new Callable() { @Override public Void call() throws Exception { Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false)); KillSession.kill(client.getZooKeeper(), server.getConnectString()); client.getZooKeeper(); client.blockUntilConnectedOrTimedOut(); Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false)); return null; } } ); } catch ( Exception e ) { retryLoop.takeException(e); } } Assert.fail(); } catch ( SessionFailRetryLoop.SessionFailedException dummy ) { // correct } } finally { retryLoop.close(); CloseableUtils.closeQuietly(client); } } @Test public void testBasicStatic() throws Exception { Timing timing = new Timing(); final CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), timing.session(), timing.connection(), null, new RetryOneTime(1)); SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.FAIL); retryLoop.start(); try { client.start(); try { SessionFailRetryLoop.callWithRetry ( client, SessionFailRetryLoop.Mode.FAIL, new Callable() { @Override public Object call() throws Exception { RetryLoop.callWithRetry ( client, new Callable() { @Override public Void call() throws Exception { Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false)); KillSession.kill(client.getZooKeeper(), server.getConnectString()); client.getZooKeeper(); client.blockUntilConnectedOrTimedOut(); Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false)); return null; } } ); return null; } } ); } catch ( SessionFailRetryLoop.SessionFailedException dummy ) { // correct } } finally { retryLoop.close(); CloseableUtils.closeQuietly(client); } } } curator-apache-curator-2.7.1/curator-client/src/test/java/org/apache/curator/ensemble/000077500000000000000000000000001245521677600310165ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/test/java/org/apache/curator/ensemble/exhibitor/000077500000000000000000000000001245521677600330135ustar00rootroot00000000000000TestExhibitorEnsembleProvider.java000066400000000000000000000215471245521677600415730ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/test/java/org/apache/curator/ensemble/exhibitor/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.ensemble.exhibitor; import com.google.common.collect.Lists; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.CuratorZookeeperClient; import org.apache.curator.RetryLoop; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.TestingServer; import org.apache.curator.test.Timing; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.Stat; import org.testng.Assert; import org.testng.annotations.Test; import java.io.IOException; import java.util.concurrent.Callable; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; public class TestExhibitorEnsembleProvider extends BaseClassForTests { private static final Exhibitors.BackupConnectionStringProvider dummyConnectionStringProvider = new Exhibitors.BackupConnectionStringProvider() { @Override public String getBackupConnectionString() throws Exception { return null; } }; @Test public void testExhibitorFailures() throws Exception { final AtomicReference backupConnectionString = new AtomicReference("backup1:1"); final AtomicReference connectionString = new AtomicReference("count=1&port=2&server0=localhost"); Exhibitors exhibitors = new Exhibitors ( Lists.newArrayList("foo", "bar"), 1000, new Exhibitors.BackupConnectionStringProvider() { @Override public String getBackupConnectionString() { return backupConnectionString.get(); } } ); ExhibitorRestClient mockRestClient = new ExhibitorRestClient() { @Override public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception { String localConnectionString = connectionString.get(); if ( localConnectionString == null ) { throw new IOException(); } return localConnectionString; } }; final Semaphore semaphore = new Semaphore(0); ExhibitorEnsembleProvider provider = new ExhibitorEnsembleProvider(exhibitors, mockRestClient, "/foo", 10, new RetryOneTime(1)) { @Override protected void poll() { super.poll(); semaphore.release(); } }; provider.pollForInitialEnsemble(); try { provider.start(); Assert.assertEquals(provider.getConnectionString(), "localhost:2"); connectionString.set(null); semaphore.drainPermits(); semaphore.acquire(); // wait for next poll Assert.assertEquals(provider.getConnectionString(), "backup1:1"); backupConnectionString.set("backup2:2"); semaphore.drainPermits(); semaphore.acquire(); // wait for next poll Assert.assertEquals(provider.getConnectionString(), "backup2:2"); connectionString.set("count=1&port=3&server0=localhost3"); semaphore.drainPermits(); semaphore.acquire(); // wait for next poll Assert.assertEquals(provider.getConnectionString(), "localhost3:3"); } finally { CloseableUtils.closeQuietly(provider); } } @Test public void testChanging() throws Exception { TestingServer secondServer = new TestingServer(); try { String mainConnectionString = "count=1&port=" + server.getPort() + "&server0=localhost"; String secondConnectionString = "count=1&port=" + secondServer.getPort() + "&server0=localhost"; final Semaphore semaphore = new Semaphore(0); final AtomicReference connectionString = new AtomicReference(mainConnectionString); Exhibitors exhibitors = new Exhibitors(Lists.newArrayList("foo", "bar"), 1000, dummyConnectionStringProvider); ExhibitorRestClient mockRestClient = new ExhibitorRestClient() { @Override public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception { semaphore.release(); return connectionString.get(); } }; ExhibitorEnsembleProvider provider = new ExhibitorEnsembleProvider(exhibitors, mockRestClient, "/foo", 10, new RetryOneTime(1)); provider.pollForInitialEnsemble(); Timing timing = new Timing().multiple(4); final CuratorZookeeperClient client = new CuratorZookeeperClient(provider, timing.session(), timing.connection(), null, new RetryOneTime(2)); client.start(); try { RetryLoop.callWithRetry ( client, new Callable() { @Override public Object call() throws Exception { client.getZooKeeper().create("/test", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); return null; } } ); connectionString.set(secondConnectionString); semaphore.drainPermits(); semaphore.acquire(); server.stop(); // create situation where the current zookeeper gets a sys-disconnected Stat stat = RetryLoop.callWithRetry ( client, new Callable() { @Override public Stat call() throws Exception { return client.getZooKeeper().exists("/test", false); } } ); Assert.assertNull(stat); // it's a different server so should be null } finally { client.close(); } } finally { CloseableUtils.closeQuietly(secondServer); } } @Test public void testSimple() throws Exception { Exhibitors exhibitors = new Exhibitors(Lists.newArrayList("foo", "bar"), 1000, dummyConnectionStringProvider); ExhibitorRestClient mockRestClient = new ExhibitorRestClient() { @Override public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception { return "count=1&port=" + server.getPort() + "&server0=localhost"; } }; ExhibitorEnsembleProvider provider = new ExhibitorEnsembleProvider(exhibitors, mockRestClient, "/foo", 10, new RetryOneTime(1)); provider.pollForInitialEnsemble(); Timing timing = new Timing(); CuratorZookeeperClient client = new CuratorZookeeperClient(provider, timing.session(), timing.connection(), null, new ExponentialBackoffRetry(timing.milliseconds(), 3)); client.start(); try { client.blockUntilConnectedOrTimedOut(); client.getZooKeeper().exists("/", false); } catch ( Exception e ) { Assert.fail("provider.getConnectionString(): " + provider.getConnectionString() + " server.getPort(): " + server.getPort(), e); } finally { client.close(); } } } curator-apache-curator-2.7.1/curator-client/src/test/java/org/apache/curator/utils/000077500000000000000000000000001245521677600303645ustar00rootroot00000000000000TestCloseableExecutorService.java000066400000000000000000000205051245521677600367430ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/test/java/org/apache/curator/utils/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.utils; import com.google.common.collect.Lists; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class TestCloseableExecutorService { private static final int QTY = 10; private volatile ExecutorService executorService; @BeforeMethod public void setup() { executorService = Executors.newFixedThreadPool(QTY * 2); } @AfterMethod public void tearDown() { executorService.shutdownNow(); } @Test public void testBasicRunnable() throws InterruptedException { try { CloseableExecutorService service = new CloseableExecutorService(executorService); CountDownLatch startLatch = new CountDownLatch(QTY); CountDownLatch latch = new CountDownLatch(QTY); for ( int i = 0; i < QTY; ++i ) { submitRunnable(service, startLatch, latch); } Assert.assertTrue(startLatch.await(3, TimeUnit.SECONDS)); service.close(); Assert.assertTrue(latch.await(3, TimeUnit.SECONDS)); } catch ( AssertionError e ) { throw e; } catch ( Throwable e ) { e.printStackTrace(); } } @Test public void testBasicCallable() throws InterruptedException { CloseableExecutorService service = new CloseableExecutorService(executorService); final CountDownLatch startLatch = new CountDownLatch(QTY); final CountDownLatch latch = new CountDownLatch(QTY); for ( int i = 0; i < QTY; ++i ) { service.submit ( new Callable() { @Override public Void call() throws Exception { try { startLatch.countDown(); Thread.currentThread().join(); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } finally { latch.countDown(); } return null; } } ); } Assert.assertTrue(startLatch.await(3, TimeUnit.SECONDS)); service.close(); Assert.assertTrue(latch.await(3, TimeUnit.SECONDS)); } @Test public void testListeningRunnable() throws InterruptedException { CloseableExecutorService service = new CloseableExecutorService(executorService); List> futures = Lists.newArrayList(); final CountDownLatch startLatch = new CountDownLatch(QTY); for ( int i = 0; i < QTY; ++i ) { Future future = service.submit ( new Runnable() { @Override public void run() { try { startLatch.countDown(); Thread.currentThread().join(); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } } } ); futures.add(future); } Assert.assertTrue(startLatch.await(3, TimeUnit.SECONDS)); for ( Future future : futures ) { future.cancel(true); } Assert.assertEquals(service.size(), 0); } @Test public void testListeningCallable() throws InterruptedException { CloseableExecutorService service = new CloseableExecutorService(executorService); final CountDownLatch startLatch = new CountDownLatch(QTY); List> futures = Lists.newArrayList(); for ( int i = 0; i < QTY; ++i ) { Future future = service.submit ( new Callable() { @Override public Void call() throws Exception { try { startLatch.countDown(); Thread.currentThread().join(); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } return null; } } ); futures.add(future); } Assert.assertTrue(startLatch.await(3, TimeUnit.SECONDS)); for ( Future future : futures ) { future.cancel(true); } Assert.assertEquals(service.size(), 0); } @Test public void testPartialRunnable() throws InterruptedException { final CountDownLatch outsideLatch = new CountDownLatch(1); executorService.submit ( new Runnable() { @Override public void run() { try { Thread.currentThread().join(); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } finally { outsideLatch.countDown(); } } } ); CloseableExecutorService service = new CloseableExecutorService(executorService); CountDownLatch startLatch = new CountDownLatch(QTY); CountDownLatch latch = new CountDownLatch(QTY); for ( int i = 0; i < QTY; ++i ) { submitRunnable(service, startLatch, latch); } while ( service.size() < QTY ) { Thread.sleep(100); } Assert.assertTrue(startLatch.await(3, TimeUnit.SECONDS)); service.close(); Assert.assertTrue(latch.await(3, TimeUnit.SECONDS)); Assert.assertEquals(outsideLatch.getCount(), 1); } private void submitRunnable(CloseableExecutorService service, final CountDownLatch startLatch, final CountDownLatch latch) { service.submit ( new Runnable() { @Override public void run() { try { startLatch.countDown(); Thread.sleep(100000); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } finally { latch.countDown(); } } } ); } } TestCloseableScheduledExecutorService.java000066400000000000000000000074641245521677600405750ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/test/java/org/apache/curator/utils/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.utils; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestCloseableScheduledExecutorService { private static final int QTY = 10; private static final int DELAY_MS = 100; private volatile ScheduledExecutorService executorService; @BeforeMethod public void setup() { executorService = Executors.newScheduledThreadPool(QTY * 2); } @AfterMethod public void tearDown() { executorService.shutdownNow(); } @Test public void testCloseableScheduleWithFixedDelay() throws InterruptedException { CloseableScheduledExecutorService service = new CloseableScheduledExecutorService(executorService); final CountDownLatch latch = new CountDownLatch(QTY); service.scheduleWithFixedDelay( new Runnable() { @Override public void run() { latch.countDown(); } }, DELAY_MS, DELAY_MS, TimeUnit.MILLISECONDS ); Assert.assertTrue(latch.await((QTY * 2) * DELAY_MS, TimeUnit.MILLISECONDS)); } @Test public void testCloseableScheduleWithFixedDelayAndAdditionalTasks() throws InterruptedException { final AtomicInteger outerCounter = new AtomicInteger(0); Runnable command = new Runnable() { @Override public void run() { outerCounter.incrementAndGet(); } }; executorService.scheduleWithFixedDelay(command, DELAY_MS, DELAY_MS, TimeUnit.MILLISECONDS); CloseableScheduledExecutorService service = new CloseableScheduledExecutorService(executorService); final AtomicInteger innerCounter = new AtomicInteger(0); service.scheduleWithFixedDelay(new Runnable() { @Override public void run() { innerCounter.incrementAndGet(); } }, DELAY_MS, DELAY_MS, TimeUnit.MILLISECONDS); Thread.sleep(DELAY_MS * 4); service.close(); Thread.sleep(DELAY_MS * 2); int innerValue = innerCounter.get(); Assert.assertTrue(innerValue > 0); int value = outerCounter.get(); Thread.sleep(DELAY_MS * 2); int newValue = outerCounter.get(); Assert.assertTrue(newValue > value); Assert.assertEquals(innerValue, innerCounter.get()); value = newValue; Thread.sleep(DELAY_MS * 2); newValue = outerCounter.get(); Assert.assertTrue(newValue > value); Assert.assertEquals(innerValue, innerCounter.get()); } } curator-apache-curator-2.7.1/curator-client/src/test/java/org/apache/curator/utils/TestZKPaths.java000066400000000000000000000100331245521677600334100ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.utils; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Arrays; import java.util.Collections; public class TestZKPaths { @SuppressWarnings("NullArgumentToVariableArgMethod") @Test public void testMakePath() { Assert.assertEquals(ZKPaths.makePath(null, "/"), "/"); Assert.assertEquals(ZKPaths.makePath("", null), "/"); Assert.assertEquals(ZKPaths.makePath("/", null), "/"); Assert.assertEquals(ZKPaths.makePath(null, null), "/"); Assert.assertEquals(ZKPaths.makePath("/", "/"), "/"); Assert.assertEquals(ZKPaths.makePath("", "/"), "/"); Assert.assertEquals(ZKPaths.makePath("/", ""), "/"); Assert.assertEquals(ZKPaths.makePath("", ""), "/"); Assert.assertEquals(ZKPaths.makePath("foo", ""), "/foo"); Assert.assertEquals(ZKPaths.makePath("foo", "/"), "/foo"); Assert.assertEquals(ZKPaths.makePath("/foo", ""), "/foo"); Assert.assertEquals(ZKPaths.makePath("/foo", "/"), "/foo"); Assert.assertEquals(ZKPaths.makePath("foo", null), "/foo"); Assert.assertEquals(ZKPaths.makePath("foo", null), "/foo"); Assert.assertEquals(ZKPaths.makePath("/foo", null), "/foo"); Assert.assertEquals(ZKPaths.makePath("/foo", null), "/foo"); Assert.assertEquals(ZKPaths.makePath("", "bar"), "/bar"); Assert.assertEquals(ZKPaths.makePath("/", "bar"), "/bar"); Assert.assertEquals(ZKPaths.makePath("", "/bar"), "/bar"); Assert.assertEquals(ZKPaths.makePath("/", "/bar"), "/bar"); Assert.assertEquals(ZKPaths.makePath(null, "bar"), "/bar"); Assert.assertEquals(ZKPaths.makePath(null, "bar"), "/bar"); Assert.assertEquals(ZKPaths.makePath(null, "/bar"), "/bar"); Assert.assertEquals(ZKPaths.makePath(null, "/bar"), "/bar"); Assert.assertEquals(ZKPaths.makePath("foo", "bar"), "/foo/bar"); Assert.assertEquals(ZKPaths.makePath("/foo", "bar"), "/foo/bar"); Assert.assertEquals(ZKPaths.makePath("foo", "/bar"), "/foo/bar"); Assert.assertEquals(ZKPaths.makePath("/foo", "/bar"), "/foo/bar"); Assert.assertEquals(ZKPaths.makePath("/foo", "bar/"), "/foo/bar"); Assert.assertEquals(ZKPaths.makePath("/foo/", "/bar/"), "/foo/bar"); Assert.assertEquals(ZKPaths.makePath("foo", "bar", "baz"), "/foo/bar/baz"); Assert.assertEquals(ZKPaths.makePath("foo", "bar", "baz", "qux"), "/foo/bar/baz/qux"); Assert.assertEquals(ZKPaths.makePath("/foo", "/bar", "/baz"), "/foo/bar/baz"); Assert.assertEquals(ZKPaths.makePath("/foo/", "/bar/", "/baz/"), "/foo/bar/baz"); Assert.assertEquals(ZKPaths.makePath("foo", null, null), "/foo"); Assert.assertEquals(ZKPaths.makePath("foo", "bar", null), "/foo/bar"); Assert.assertEquals(ZKPaths.makePath("foo", null, "baz"), "/foo/baz"); } @Test public void testSplit() { Assert.assertEquals(ZKPaths.split("/"), Collections.emptyList()); Assert.assertEquals(ZKPaths.split("/test"), Collections.singletonList("test")); Assert.assertEquals(ZKPaths.split("/test/one"), Arrays.asList("test", "one")); Assert.assertEquals(ZKPaths.split("/test/one/two"), Arrays.asList("test", "one", "two")); } } curator-apache-curator-2.7.1/curator-client/src/test/resources/000077500000000000000000000000001245521677600246265ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-client/src/test/resources/log4j.properties000066400000000000000000000021131245521677600277600ustar00rootroot00000000000000# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # log4j.rootLogger=ERROR, console log4j.logger.org.apache.curator=DEBUG, console log4j.additivity.org.apache.curator=false log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%-5p %c %x %m [%t]%n curator-apache-curator-2.7.1/curator-examples/000077500000000000000000000000001245521677600214065ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-examples/LICENSE000066400000000000000000000261361245521677600224230ustar00rootroot00000000000000 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. curator-apache-curator-2.7.1/curator-examples/NOTICE000066400000000000000000000002501245521677600223070ustar00rootroot00000000000000Apache Curator Copyright 2013-2014 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). curator-apache-curator-2.7.1/curator-examples/pom.xml000066400000000000000000000036331245521677600227300ustar00rootroot00000000000000 4.0.0 org.apache.curator apache-curator 2.7.1 curator-examples Curator Examples Example usages of various Curator features. 2011 org.apache.curator curator-recipes org.apache.curator curator-test org.apache.curator curator-x-discovery curator-apache-curator-2.7.1/curator-examples/src/000077500000000000000000000000001245521677600221755ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-examples/src/main/000077500000000000000000000000001245521677600231215ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-examples/src/main/java/000077500000000000000000000000001245521677600240425ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-examples/src/main/java/cache/000077500000000000000000000000001245521677600251055ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-examples/src/main/java/cache/PathCacheExample.java000066400000000000000000000203471245521677600311120ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package cache; import com.google.common.collect.Lists; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.PathChildrenCache; import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent; import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.test.TestingServer; import org.apache.curator.utils.ZKPaths; import discovery.ExampleServer; import org.apache.zookeeper.KeeperException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.List; /** * An example of the PathChildrenCache. The example "harness" is a command processor * that allows adding/updating/removed nodes in a path. A PathChildrenCache keeps a * cache of these changes and outputs when updates occurs. */ public class PathCacheExample { private static final String PATH = "/example/cache"; public static void main(String[] args) throws Exception { TestingServer server = new TestingServer(); CuratorFramework client = null; PathChildrenCache cache = null; try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); client.start(); // in this example we will cache data. Notice that this is optional. cache = new PathChildrenCache(client, PATH, true); cache.start(); processCommands(client, cache); } finally { CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(server); } } private static void addListener(PathChildrenCache cache) { // a PathChildrenCacheListener is optional. Here, it's used just to log changes PathChildrenCacheListener listener = new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { switch ( event.getType() ) { case CHILD_ADDED: { System.out.println("Node added: " + ZKPaths.getNodeFromPath(event.getData().getPath())); break; } case CHILD_UPDATED: { System.out.println("Node changed: " + ZKPaths.getNodeFromPath(event.getData().getPath())); break; } case CHILD_REMOVED: { System.out.println("Node removed: " + ZKPaths.getNodeFromPath(event.getData().getPath())); break; } } } }; cache.getListenable().addListener(listener); } private static void processCommands(CuratorFramework client, PathChildrenCache cache) throws Exception { // More scaffolding that does a simple command line processor printHelp(); List servers = Lists.newArrayList(); try { addListener(cache); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); boolean done = false; while ( !done ) { System.out.print("> "); String line = in.readLine(); if ( line == null ) { break; } String command = line.trim(); String[] parts = command.split("\\s"); if ( parts.length == 0 ) { continue; } String operation = parts[0]; String args[] = Arrays.copyOfRange(parts, 1, parts.length); if ( operation.equalsIgnoreCase("help") || operation.equalsIgnoreCase("?") ) { printHelp(); } else if ( operation.equalsIgnoreCase("q") || operation.equalsIgnoreCase("quit") ) { done = true; } else if ( operation.equals("set") ) { setValue(client, command, args); } else if ( operation.equals("remove") ) { remove(client, command, args); } else if ( operation.equals("list") ) { list(cache); } Thread.sleep(1000); // just to allow the console output to catch up } } finally { for ( ExampleServer server : servers ) { CloseableUtils.closeQuietly(server); } } } private static void list(PathChildrenCache cache) { if ( cache.getCurrentData().size() == 0 ) { System.out.println("* empty *"); } else { for ( ChildData data : cache.getCurrentData() ) { System.out.println(data.getPath() + " = " + new String(data.getData())); } } } private static void remove(CuratorFramework client, String command, String[] args) throws Exception { if ( args.length != 1 ) { System.err.println("syntax error (expected remove ): " + command); return; } String name = args[0]; if ( name.contains("/") ) { System.err.println("Invalid node name" + name); return; } String path = ZKPaths.makePath(PATH, name); try { client.delete().forPath(path); } catch ( KeeperException.NoNodeException e ) { // ignore } } private static void setValue(CuratorFramework client, String command, String[] args) throws Exception { if ( args.length != 2 ) { System.err.println("syntax error (expected set ): " + command); return; } String name = args[0]; if ( name.contains("/") ) { System.err.println("Invalid node name" + name); return; } String path = ZKPaths.makePath(PATH, name); byte[] bytes = args[1].getBytes(); try { client.setData().forPath(path, bytes); } catch ( KeeperException.NoNodeException e ) { client.create().creatingParentsIfNeeded().forPath(path, bytes); } } private static void printHelp() { System.out.println("An example of using PathChildrenCache. This example is driven by entering commands at the prompt:\n"); System.out.println("set : Adds or updates a node with the given name"); System.out.println("remove : Deletes the node with the given name"); System.out.println("list: List the nodes/values in the cache"); System.out.println("quit: Quit the example"); System.out.println(); } } curator-apache-curator-2.7.1/curator-examples/src/main/java/discovery/000077500000000000000000000000001245521677600260515ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-examples/src/main/java/discovery/DiscoveryExample.java000066400000000000000000000250061245521677600322020ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package discovery; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.test.TestingServer; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceProvider; import org.apache.curator.x.discovery.details.JsonInstanceSerializer; import org.apache.curator.x.discovery.strategies.RandomStrategy; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; public class DiscoveryExample { private static final String PATH = "/discovery/example"; public static void main(String[] args) throws Exception { // This method is scaffolding to get the example up and running TestingServer server = new TestingServer(); CuratorFramework client = null; ServiceDiscovery serviceDiscovery = null; Map> providers = Maps.newHashMap(); try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); client.start(); JsonInstanceSerializer serializer = new JsonInstanceSerializer(InstanceDetails.class); serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class).client(client).basePath(PATH).serializer(serializer).build(); serviceDiscovery.start(); processCommands(serviceDiscovery, providers, client); } finally { for ( ServiceProvider cache : providers.values() ) { CloseableUtils.closeQuietly(cache); } CloseableUtils.closeQuietly(serviceDiscovery); CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(server); } } private static void processCommands(ServiceDiscovery serviceDiscovery, Map> providers, CuratorFramework client) throws Exception { // More scaffolding that does a simple command line processor printHelp(); List servers = Lists.newArrayList(); try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); boolean done = false; while ( !done ) { System.out.print("> "); String line = in.readLine(); if ( line == null ) { break; } String command = line.trim(); String[] parts = command.split("\\s"); if ( parts.length == 0 ) { continue; } String operation = parts[0]; String args[] = Arrays.copyOfRange(parts, 1, parts.length); if ( operation.equalsIgnoreCase("help") || operation.equalsIgnoreCase("?") ) { printHelp(); } else if ( operation.equalsIgnoreCase("q") || operation.equalsIgnoreCase("quit") ) { done = true; } else if ( operation.equals("add") ) { addInstance(args, client, command, servers); } else if ( operation.equals("delete") ) { deleteInstance(args, command, servers); } else if ( operation.equals("random") ) { listRandomInstance(args, serviceDiscovery, providers, command); } else if ( operation.equals("list") ) { listInstances(serviceDiscovery); } } } finally { for ( ExampleServer server : servers ) { CloseableUtils.closeQuietly(server); } } } private static void listRandomInstance(String[] args, ServiceDiscovery serviceDiscovery, Map> providers, String command) throws Exception { // this shows how to use a ServiceProvider // in a real application you'd create the ServiceProvider early for the service(s) you're interested in if ( args.length != 1 ) { System.err.println("syntax error (expected random ): " + command); return; } String serviceName = args[0]; ServiceProvider provider = providers.get(serviceName); if ( provider == null ) { provider = serviceDiscovery.serviceProviderBuilder().serviceName(serviceName).providerStrategy(new RandomStrategy()).build(); providers.put(serviceName, provider); provider.start(); Thread.sleep(2500); // give the provider time to warm up - in a real application you wouldn't need to do this } ServiceInstance instance = provider.getInstance(); if ( instance == null ) { System.err.println("No instances named: " + serviceName); } else { outputInstance(instance); } } private static void listInstances(ServiceDiscovery serviceDiscovery) throws Exception { // This shows how to query all the instances in service discovery try { Collection serviceNames = serviceDiscovery.queryForNames(); System.out.println(serviceNames.size() + " type(s)"); for ( String serviceName : serviceNames ) { Collection> instances = serviceDiscovery.queryForInstances(serviceName); System.out.println(serviceName); for ( ServiceInstance instance : instances ) { outputInstance(instance); } } } finally { CloseableUtils.closeQuietly(serviceDiscovery); } } private static void outputInstance(ServiceInstance instance) { System.out.println("\t" + instance.getPayload().getDescription() + ": " + instance.buildUriSpec()); } private static void deleteInstance(String[] args, String command, List servers) { // simulate a random instance going down // in a real application, this would occur due to normal operation, a crash, maintenance, etc. if ( args.length != 1 ) { System.err.println("syntax error (expected delete ): " + command); return; } final String serviceName = args[0]; ExampleServer server = Iterables.find ( servers, new Predicate() { @Override public boolean apply(ExampleServer server) { return server.getThisInstance().getName().endsWith(serviceName); } }, null ); if ( server == null ) { System.err.println("No servers found named: " + serviceName); return; } servers.remove(server); CloseableUtils.closeQuietly(server); System.out.println("Removed a random instance of: " + serviceName); } private static void addInstance(String[] args, CuratorFramework client, String command, List servers) throws Exception { // simulate a new instance coming up // in a real application, this would be a separate process if ( args.length < 2 ) { System.err.println("syntax error (expected add ): " + command); return; } StringBuilder description = new StringBuilder(); for ( int i = 1; i < args.length; ++i ) { if ( i > 1 ) { description.append(' '); } description.append(args[i]); } String serviceName = args[0]; ExampleServer server = new ExampleServer(client, PATH, serviceName, description.toString()); servers.add(server); server.start(); System.out.println(serviceName + " added"); } private static void printHelp() { System.out.println("An example of using the ServiceDiscovery APIs. This example is driven by entering commands at the prompt:\n"); System.out.println("add : Adds a mock service with the given name and description"); System.out.println("delete : Deletes one of the mock services with the given name"); System.out.println("list: Lists all the currently registered services"); System.out.println("random : Lists a random instance of the service with the given name"); System.out.println("quit: Quit the example"); System.out.println(); } } curator-apache-curator-2.7.1/curator-examples/src/main/java/discovery/ExampleServer.java000066400000000000000000000061471245521677600315060ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package discovery; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.UriSpec; import org.apache.curator.x.discovery.details.JsonInstanceSerializer; import java.io.Closeable; import java.io.IOException; /** * This shows a very simplified method of registering an instance with the service discovery. Each individual * instance in your distributed set of applications would create an instance of something similar to ExampleServer, * start it when the application comes up and close it when the application shuts down. */ public class ExampleServer implements Closeable { private final ServiceDiscovery serviceDiscovery; private final ServiceInstance thisInstance; public ExampleServer(CuratorFramework client, String path, String serviceName, String description) throws Exception { // in a real application, you'd have a convention of some kind for the URI layout UriSpec uriSpec = new UriSpec("{scheme}://foo.com:{port}"); thisInstance = ServiceInstance.builder() .name(serviceName) .payload(new InstanceDetails(description)) .port((int)(65535 * Math.random())) // in a real application, you'd use a common port .uriSpec(uriSpec) .build(); // if you mark your payload class with @JsonRootName the provided JsonInstanceSerializer will work JsonInstanceSerializer serializer = new JsonInstanceSerializer(InstanceDetails.class); serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class) .client(client) .basePath(path) .serializer(serializer) .thisInstance(thisInstance) .build(); } public ServiceInstance getThisInstance() { return thisInstance; } public void start() throws Exception { serviceDiscovery.start(); } @Override public void close() throws IOException { CloseableUtils.closeQuietly(serviceDiscovery); } } curator-apache-curator-2.7.1/curator-examples/src/main/java/discovery/InstanceDetails.java000066400000000000000000000026601245521677600317720ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package discovery; import org.codehaus.jackson.map.annotate.JsonRootName; /** * In a real application, the Service payload will most likely * be more detailed than this. But, this gives a good example. */ @JsonRootName("details") public class InstanceDetails { private String description; public InstanceDetails() { this(""); } public InstanceDetails(String description) { this.description = description; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } } curator-apache-curator-2.7.1/curator-examples/src/main/java/framework/000077500000000000000000000000001245521677600260375ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-examples/src/main/java/framework/CreateClientExamples.java000066400000000000000000000044541245521677600327520ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package framework; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; public class CreateClientExamples { public static CuratorFramework createSimple(String connectionString) { // these are reasonable arguments for the ExponentialBackoffRetry. The first // retry will wait 1 second - the second will wait up to 2 seconds - the // third will wait up to 4 seconds. ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3); // The simplest way to get a CuratorFramework instance. This will use default values. // The only required arguments are the connection string and the retry policy return CuratorFrameworkFactory.newClient(connectionString, retryPolicy); } public static CuratorFramework createWithOptions(String connectionString, RetryPolicy retryPolicy, int connectionTimeoutMs, int sessionTimeoutMs) { // using the CuratorFrameworkFactory.builder() gives fine grained control // over creation options. See the CuratorFrameworkFactory.Builder javadoc // details return CuratorFrameworkFactory.builder() .connectString(connectionString) .retryPolicy(retryPolicy) .connectionTimeoutMs(connectionTimeoutMs) .sessionTimeoutMs(sessionTimeoutMs) // etc. etc. .build(); } } curator-apache-curator-2.7.1/curator-examples/src/main/java/framework/CrudExamples.java000066400000000000000000000137631245521677600313100ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package framework; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorListener; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.Watcher; import java.util.List; public class CrudExamples { public static void create(CuratorFramework client, String path, byte[] payload) throws Exception { // this will create the given ZNode with the given data client.create().forPath(path, payload); } public static void createEphemeral(CuratorFramework client, String path, byte[] payload) throws Exception { // this will create the given EPHEMERAL ZNode with the given data client.create().withMode(CreateMode.EPHEMERAL).forPath(path, payload); } public static String createEphemeralSequential(CuratorFramework client, String path, byte[] payload) throws Exception { // this will create the given EPHEMERAL-SEQUENTIAL ZNode with the given data using Curator protection. /* Protection Mode: It turns out there is an edge case that exists when creating sequential-ephemeral nodes. The creation can succeed on the server, but the server can crash before the created node name is returned to the client. However, the ZK session is still valid so the ephemeral node is not deleted. Thus, there is no way for the client to determine what node was created for them. Even without sequential-ephemeral, however, the create can succeed on the sever but the client (for various reasons) will not know it. Putting the create builder into protection mode works around this. The name of the node that is created is prefixed with a GUID. If node creation fails the normal retry mechanism will occur. On the retry, the parent path is first searched for a node that has the GUID in it. If that node is found, it is assumed to be the lost node that was successfully created on the first try and is returned to the caller. */ return client.create().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(path, payload); } public static void setData(CuratorFramework client, String path, byte[] payload) throws Exception { // set data for the given node client.setData().forPath(path, payload); } public static void setDataAsync(CuratorFramework client, String path, byte[] payload) throws Exception { // this is one method of getting event/async notifications CuratorListener listener = new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { // examine event for details } }; client.getCuratorListenable().addListener(listener); // set data for the given node asynchronously. The completion notification // is done via the CuratorListener. client.setData().inBackground().forPath(path, payload); } public static void setDataAsyncWithCallback(CuratorFramework client, BackgroundCallback callback, String path, byte[] payload) throws Exception { // this is another method of getting notification of an async completion client.setData().inBackground(callback).forPath(path, payload); } public static void delete(CuratorFramework client, String path) throws Exception { // delete the given node client.delete().forPath(path); } public static void guaranteedDelete(CuratorFramework client, String path) throws Exception { // delete the given node and guarantee that it completes /* Guaranteed Delete Solves this edge case: deleting a node can fail due to connection issues. Further, if the node was ephemeral, the node will not get auto-deleted as the session is still valid. This can wreak havoc with lock implementations. When guaranteed is set, Curator will record failed node deletions and attempt to delete them in the background until successful. NOTE: you will still get an exception when the deletion fails. But, you can be assured that as long as the CuratorFramework instance is open attempts will be made to delete the node. */ client.delete().guaranteed().forPath(path); } public static List watchedGetChildren(CuratorFramework client, String path) throws Exception { /** * Get children and set a watcher on the node. The watcher notification will come through the * CuratorListener (see setDataAsync() above). */ return client.getChildren().watched().forPath(path); } public static List watchedGetChildren(CuratorFramework client, String path, Watcher watcher) throws Exception { /** * Get children and set the given watcher on the node. */ return client.getChildren().usingWatcher(watcher).forPath(path); } } curator-apache-curator-2.7.1/curator-examples/src/main/java/framework/TransactionExamples.java000066400000000000000000000056731245521677600327010ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package framework; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.transaction.CuratorTransaction; import org.apache.curator.framework.api.transaction.CuratorTransactionFinal; import org.apache.curator.framework.api.transaction.CuratorTransactionResult; import java.util.Collection; public class TransactionExamples { public static Collection transaction(CuratorFramework client) throws Exception { // this example shows how to use ZooKeeper's new transactions Collection results = client.inTransaction() .create().forPath("/a/path", "some data".getBytes()) .and() .setData().forPath("/another/path", "other data".getBytes()) .and() .delete().forPath("/yet/another/path") .and() .commit(); // IMPORTANT! The transaction is not submitted until commit() is called for ( CuratorTransactionResult result : results ) { System.out.println(result.getForPath() + " - " + result.getType()); } return results; } /* These next four methods show how to use Curator's transaction APIs in a more traditional - one-at-a-time - manner */ public static CuratorTransaction startTransaction(CuratorFramework client) { // start the transaction builder return client.inTransaction(); } public static CuratorTransactionFinal addCreateToTransaction(CuratorTransaction transaction) throws Exception { // add a create operation return transaction.create().forPath("/a/path", "some data".getBytes()).and(); } public static CuratorTransactionFinal addDeleteToTransaction(CuratorTransaction transaction) throws Exception { // add a delete operation return transaction.delete().forPath("/another/path").and(); } public static void commitTransaction(CuratorTransactionFinal transaction) throws Exception { // commit the transaction transaction.commit(); } } curator-apache-curator-2.7.1/curator-examples/src/main/java/leader/000077500000000000000000000000001245521677600252765ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-examples/src/main/java/leader/ExampleClient.java000066400000000000000000000064601245521677600307010ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package leader; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter; import org.apache.curator.framework.recipes.leader.LeaderSelector; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * An example leader selector client. Note that {@link LeaderSelectorListenerAdapter} which * has the recommended handling for connection state issues */ public class ExampleClient extends LeaderSelectorListenerAdapter implements Closeable { private final String name; private final LeaderSelector leaderSelector; private final AtomicInteger leaderCount = new AtomicInteger(); public ExampleClient(CuratorFramework client, String path, String name) { this.name = name; // create a leader selector using the given path for management // all participants in a given leader selection must use the same path // ExampleClient here is also a LeaderSelectorListener but this isn't required leaderSelector = new LeaderSelector(client, path, this); // for most cases you will want your instance to requeue when it relinquishes leadership leaderSelector.autoRequeue(); } public void start() throws IOException { // the selection for this instance doesn't start until the leader selector is started // leader selection is done in the background so this call to leaderSelector.start() returns immediately leaderSelector.start(); } @Override public void close() throws IOException { leaderSelector.close(); } @Override public void takeLeadership(CuratorFramework client) throws Exception { // we are now the leader. This method should not return until we want to relinquish leadership final int waitSeconds = (int)(5 * Math.random()) + 1; System.out.println(name + " is now the leader. Waiting " + waitSeconds + " seconds..."); System.out.println(name + " has been leader " + leaderCount.getAndIncrement() + " time(s) before."); try { Thread.sleep(TimeUnit.SECONDS.toMillis(waitSeconds)); } catch ( InterruptedException e ) { System.err.println(name + " was interrupted."); Thread.currentThread().interrupt(); } finally { System.out.println(name + " relinquishing leadership.\n"); } } } curator-apache-curator-2.7.1/curator-examples/src/main/java/leader/LeaderSelectorExample.java000066400000000000000000000060261245521677600323560ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package leader; import com.google.common.collect.Lists; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.test.TestingServer; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.List; public class LeaderSelectorExample { private static final int CLIENT_QTY = 10; private static final String PATH = "/examples/leader"; public static void main(String[] args) throws Exception { // all of the useful sample code is in ExampleClient.java System.out.println("Create " + CLIENT_QTY + " clients, have each negotiate for leadership and then wait a random number of seconds before letting another leader election occur."); System.out.println("Notice that leader election is fair: all clients will become leader and will do so the same number of times."); List clients = Lists.newArrayList(); List examples = Lists.newArrayList(); TestingServer server = new TestingServer(); try { for ( int i = 0; i < CLIENT_QTY; ++i ) { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); clients.add(client); ExampleClient example = new ExampleClient(client, PATH, "Client #" + i); examples.add(example); client.start(); example.start(); } System.out.println("Press enter/return to quit\n"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } finally { System.out.println("Shutting down..."); for ( ExampleClient exampleClient : examples ) { CloseableUtils.closeQuietly(exampleClient); } for ( CuratorFramework client : clients ) { CloseableUtils.closeQuietly(client); } CloseableUtils.closeQuietly(server); } } } curator-apache-curator-2.7.1/curator-examples/src/main/java/locking/000077500000000000000000000000001245521677600254705ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-examples/src/main/java/locking/ExampleClientThatLocks.java000066400000000000000000000036431245521677600327100ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package locking; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import java.util.concurrent.TimeUnit; public class ExampleClientThatLocks { private final InterProcessMutex lock; private final FakeLimitedResource resource; private final String clientName; public ExampleClientThatLocks(CuratorFramework client, String lockPath, FakeLimitedResource resource, String clientName) { this.resource = resource; this.clientName = clientName; lock = new InterProcessMutex(client, lockPath); } public void doWork(long time, TimeUnit unit) throws Exception { if ( !lock.acquire(time, unit) ) { throw new IllegalStateException(clientName + " could not acquire the lock"); } try { System.out.println(clientName + " has the lock"); resource.use(); } finally { System.out.println(clientName + " releasing the lock"); lock.release(); // always release the lock in a finally block } } } curator-apache-curator-2.7.1/curator-examples/src/main/java/locking/FakeLimitedResource.java000066400000000000000000000030101245521677600322130ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package locking; import java.util.concurrent.atomic.AtomicBoolean; /** * Simulates some external resource that can only be access by one process at a time */ public class FakeLimitedResource { private final AtomicBoolean inUse = new AtomicBoolean(false); public void use() throws InterruptedException { // in a real application this would be accessing/manipulating a shared resource if ( !inUse.compareAndSet(false, true) ) { throw new IllegalStateException("Needs to be used by one client at a time"); } try { Thread.sleep((long)(3 * Math.random())); } finally { inUse.set(false); } } } curator-apache-curator-2.7.1/curator-examples/src/main/java/locking/LockingExample.java000066400000000000000000000066261245521677600312470ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package locking; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.test.TestingServer; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class LockingExample { private static final int QTY = 5; private static final int REPETITIONS = QTY * 10; private static final String PATH = "/examples/locks"; public static void main(String[] args) throws Exception { // all of the useful sample code is in ExampleClientThatLocks.java // FakeLimitedResource simulates some external resource that can only be access by one process at a time final FakeLimitedResource resource = new FakeLimitedResource(); ExecutorService service = Executors.newFixedThreadPool(QTY); final TestingServer server = new TestingServer(); try { for ( int i = 0; i < QTY; ++i ) { final int index = i; Callable task = new Callable() { @Override public Void call() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); try { client.start(); ExampleClientThatLocks example = new ExampleClientThatLocks(client, PATH, resource, "Client " + index); for ( int j = 0; j < REPETITIONS; ++j ) { example.doWork(10, TimeUnit.SECONDS); } } catch ( Throwable e ) { e.printStackTrace(); } finally { CloseableUtils.closeQuietly(client); } return null; } }; service.submit(task); } service.shutdown(); service.awaitTermination(10, TimeUnit.MINUTES); } finally { CloseableUtils.closeQuietly(server); } } } curator-apache-curator-2.7.1/curator-examples/src/site/000077500000000000000000000000001245521677600231415ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-examples/src/site/confluence/000077500000000000000000000000001245521677600252625ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-examples/src/site/confluence/index.confluence000066400000000000000000000010251245521677600304320ustar00rootroot00000000000000h1. Examples This module contains example usages of various Curator features. Each directory in the module is a separate example. |/leader|Example leader selector code| |/cache|Example PathChildrenCache usage| |/locking|Example of using InterProcessMutex| |/discovery|Example usage of the Curator's ServiceDiscovery| |/framework|A few examples of how to use the CuratorFramework class| See the [examples source repo|https://git-wip-us.apache.org/repos/asf?p=curator.git;a=tree;f=curator-examples/src/main/java] for each example. curator-apache-curator-2.7.1/curator-examples/src/site/site.xml000066400000000000000000000026301245521677600246300ustar00rootroot00000000000000 curator-apache-curator-2.7.1/curator-framework/000077500000000000000000000000001245521677600215655ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/LICENSE000066400000000000000000000261361245521677600226020ustar00rootroot00000000000000 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. curator-apache-curator-2.7.1/curator-framework/NOTICE000066400000000000000000000002501245521677600224660ustar00rootroot00000000000000Apache Curator Copyright 2013-2014 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). curator-apache-curator-2.7.1/curator-framework/pom.xml000066400000000000000000000041641245521677600231070ustar00rootroot00000000000000 4.0.0 org.apache.curator apache-curator 2.7.1 curator-framework 2.7.1 bundle Curator Framework High-level API that greatly simplifies using ZooKeeper. 2011 * org.apache.curator.framework*;version="${project.version}";-noimport:=true org.apache.curator curator-client org.apache.curator curator-test test curator-apache-curator-2.7.1/curator-framework/src/000077500000000000000000000000001245521677600223545ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/000077500000000000000000000000001245521677600233005ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/000077500000000000000000000000001245521677600242215ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/000077500000000000000000000000001245521677600250105ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/000077500000000000000000000000001245521677600262315ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/000077500000000000000000000000001245521677600277105ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/000077500000000000000000000000001245521677600317055ustar00rootroot00000000000000AuthInfo.java000066400000000000000000000025471245521677600342160ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework; import java.util.Arrays; public class AuthInfo { final String scheme; final byte[] auth; public AuthInfo(String scheme, byte[] auth) { this.scheme = scheme; this.auth = auth; } public String getScheme() { return scheme; } public byte[] getAuth() { return auth; } @Override public String toString() { return "AuthInfo{" + "scheme='" + scheme + '\'' + ", auth=" + Arrays.toString(auth) + '}'; } } CuratorFramework.java000066400000000000000000000150631245521677600357730ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework; import org.apache.curator.CuratorZookeeperClient; import org.apache.curator.framework.api.*; import org.apache.curator.framework.api.transaction.CuratorTransaction; import org.apache.curator.framework.imps.CuratorFrameworkState; import org.apache.curator.framework.listen.Listenable; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.utils.EnsurePath; import org.apache.zookeeper.Watcher; import java.io.Closeable; import java.util.concurrent.TimeUnit; /** * Zookeeper framework-style client */ public interface CuratorFramework extends Closeable { /** * Start the client. Most mutator methods will not work until the client is started */ public void start(); /** * Stop the client */ public void close(); /** * Returns the state of this instance * * @return state */ public CuratorFrameworkState getState(); /** * Return true if the client is started, not closed, etc. * * @return true/false * @deprecated use {@link #getState()} instead */ public boolean isStarted(); /** * Start a create builder * * @return builder object */ public CreateBuilder create(); /** * Start a delete builder * * @return builder object */ public DeleteBuilder delete(); /** * Start an exists builder *

* The builder will return a Stat object as if org.apache.zookeeper.ZooKeeper.exists() were called. Thus, a null * means that it does not exist and an actual Stat object means it does exist. * * @return builder object */ public ExistsBuilder checkExists(); /** * Start a get data builder * * @return builder object */ public GetDataBuilder getData(); /** * Start a set data builder * * @return builder object */ public SetDataBuilder setData(); /** * Start a get children builder * * @return builder object */ public GetChildrenBuilder getChildren(); /** * Start a get ACL builder * * @return builder object */ public GetACLBuilder getACL(); /** * Start a set ACL builder * * @return builder object */ public SetACLBuilder setACL(); /** * Start a transaction builder * * @return builder object */ public CuratorTransaction inTransaction(); /** * Perform a sync on the given path - syncs are always in the background * * @param path the path * @param backgroundContextObject optional context * @deprecated use {@link #sync()} instead */ public void sync(String path, Object backgroundContextObject); /** * Start a sync builder. Note: sync is ALWAYS in the background even * if you don't use one of the background() methods * * @return builder object */ public SyncBuilder sync(); /** * Returns the listenable interface for the Connect State * * @return listenable */ public Listenable getConnectionStateListenable(); /** * Returns the listenable interface for events * * @return listenable */ public Listenable getCuratorListenable(); /** * Returns the listenable interface for unhandled errors * * @return listenable */ public Listenable getUnhandledErrorListenable(); /** * Returns a facade of the current instance that does _not_ automatically * pre-pend the namespace to all paths * * @return facade * @deprecated use {@link #usingNamespace} passing null */ public CuratorFramework nonNamespaceView(); /** * Returns a facade of the current instance that uses the specified namespace * or no namespace if newNamespace is null. * * @param newNamespace the new namespace or null for none * @return facade */ public CuratorFramework usingNamespace(String newNamespace); /** * Return the current namespace or "" if none * * @return namespace */ public String getNamespace(); /** * Return the managed zookeeper client * * @return client */ public CuratorZookeeperClient getZookeeperClient(); /** * Allocates an ensure path instance that is namespace aware * * @param path path to ensure * @return new EnsurePath instance */ public EnsurePath newNamespaceAwareEnsurePath(String path); /** * Curator can hold internal references to watchers that may inhibit garbage collection. * Call this method on watchers you are no longer interested in. * * @param watcher the watcher */ public void clearWatcherReferences(Watcher watcher); /** * Block until a connection to ZooKeeper is available or the maxWaitTime has been exceeded * @param maxWaitTime The maximum wait time. Specify a value <= 0 to wait indefinitely * @param units The time units for the maximum wait time. * @return True if connection has been established, false otherwise. * @throws InterruptedException If interrupted while waiting */ public boolean blockUntilConnected(int maxWaitTime, TimeUnit units) throws InterruptedException; /** * Block until a connection to ZooKeeper is available. This method will not return until a * connection is available or it is interrupted, in which case an InterruptedException will * be thrown * @throws InterruptedException If interrupted while waiting */ public void blockUntilConnected() throws InterruptedException; } CuratorFrameworkFactory.java000066400000000000000000000354221245521677600373240ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework; import com.google.common.collect.ImmutableList; import org.apache.curator.RetryPolicy; import org.apache.curator.ensemble.EnsembleProvider; import org.apache.curator.ensemble.fixed.FixedEnsembleProvider; import org.apache.curator.framework.api.ACLProvider; import org.apache.curator.framework.api.CompressionProvider; import org.apache.curator.framework.api.PathAndBytesable; import org.apache.curator.framework.imps.CuratorFrameworkImpl; import org.apache.curator.framework.imps.CuratorTempFrameworkImpl; import org.apache.curator.framework.imps.DefaultACLProvider; import org.apache.curator.framework.imps.GzipCompressionProvider; import org.apache.curator.utils.DefaultZookeeperFactory; import org.apache.curator.utils.ZookeeperFactory; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; /** * Factory methods for creating framework-style clients */ public class CuratorFrameworkFactory { private static final int DEFAULT_SESSION_TIMEOUT_MS = Integer.getInteger("curator-default-session-timeout", 60 * 1000); private static final int DEFAULT_CONNECTION_TIMEOUT_MS = Integer.getInteger("curator-default-connection-timeout", 15 * 1000); private static final byte[] LOCAL_ADDRESS = getLocalAddress(); private static final CompressionProvider DEFAULT_COMPRESSION_PROVIDER = new GzipCompressionProvider(); private static final DefaultZookeeperFactory DEFAULT_ZOOKEEPER_FACTORY = new DefaultZookeeperFactory(); private static final DefaultACLProvider DEFAULT_ACL_PROVIDER = new DefaultACLProvider(); private static final long DEFAULT_INACTIVE_THRESHOLD_MS = (int)TimeUnit.MINUTES.toMillis(3); private static final int DEFAULT_CLOSE_WAIT_MS = (int)TimeUnit.SECONDS.toMillis(1); /** * Return a new builder that builds a CuratorFramework * * @return new builder */ public static Builder builder() { return new Builder(); } /** * Create a new client with default session timeout and default connection timeout * * @param connectString list of servers to connect to * @param retryPolicy retry policy to use * @return client */ public static CuratorFramework newClient(String connectString, RetryPolicy retryPolicy) { return newClient(connectString, DEFAULT_SESSION_TIMEOUT_MS, DEFAULT_CONNECTION_TIMEOUT_MS, retryPolicy); } /** * Create a new client * * @param connectString list of servers to connect to * @param sessionTimeoutMs session timeout * @param connectionTimeoutMs connection timeout * @param retryPolicy retry policy to use * @return client */ public static CuratorFramework newClient(String connectString, int sessionTimeoutMs, int connectionTimeoutMs, RetryPolicy retryPolicy) { return builder(). connectString(connectString). sessionTimeoutMs(sessionTimeoutMs). connectionTimeoutMs(connectionTimeoutMs). retryPolicy(retryPolicy). build(); } public static class Builder { private EnsembleProvider ensembleProvider; private int sessionTimeoutMs = DEFAULT_SESSION_TIMEOUT_MS; private int connectionTimeoutMs = DEFAULT_CONNECTION_TIMEOUT_MS; private int maxCloseWaitMs = DEFAULT_CLOSE_WAIT_MS; private RetryPolicy retryPolicy; private ThreadFactory threadFactory = null; private String namespace; private List authInfos = null; private byte[] defaultData = LOCAL_ADDRESS; private CompressionProvider compressionProvider = DEFAULT_COMPRESSION_PROVIDER; private ZookeeperFactory zookeeperFactory = DEFAULT_ZOOKEEPER_FACTORY; private ACLProvider aclProvider = DEFAULT_ACL_PROVIDER; private boolean canBeReadOnly = false; /** * Apply the current values and build a new CuratorFramework * * @return new CuratorFramework */ public CuratorFramework build() { return new CuratorFrameworkImpl(this); } /** * Apply the current values and build a new temporary CuratorFramework. Temporary * CuratorFramework instances are meant for single requests to ZooKeeper ensembles * over a failure prone network such as a WAN. The APIs available from {@link CuratorTempFramework} * are limited. Further, the connection will be closed after 3 minutes of inactivity. * * @return temp instance */ public CuratorTempFramework buildTemp() { return buildTemp(DEFAULT_INACTIVE_THRESHOLD_MS, TimeUnit.MILLISECONDS); } /** * Apply the current values and build a new temporary CuratorFramework. Temporary * CuratorFramework instances are meant for single requests to ZooKeeper ensembles * over a failure prone network such as a WAN. The APIs available from {@link CuratorTempFramework} * are limited. Further, the connection will be closed after inactiveThresholdMs milliseconds of inactivity. * * @param inactiveThreshold number of milliseconds of inactivity to cause connection close * @param unit threshold unit * @return temp instance */ public CuratorTempFramework buildTemp(long inactiveThreshold, TimeUnit unit) { return new CuratorTempFrameworkImpl(this, unit.toMillis(inactiveThreshold)); } /** * Add connection authorization * * Subsequent calls to this method overwrite the prior calls. * * @param scheme the scheme * @param auth the auth bytes * @return this */ public Builder authorization(String scheme, byte[] auth) { return authorization(ImmutableList.of(new AuthInfo(scheme, (auth != null) ? Arrays.copyOf(auth, auth.length) : null))); } /** * Add connection authorization. The supplied authInfos are appended to those added via call to * {@link #authorization(java.lang.String, byte[])} for backward compatibility. *

* Subsequent calls to this method overwrite the prior calls. * * @param authInfos list of {@link AuthInfo} objects with scheme and auth * @return this */ public Builder authorization(List authInfos) { this.authInfos = ImmutableList.copyOf(authInfos); return this; } /** * Set the list of servers to connect to. IMPORTANT: use either this or {@link #ensembleProvider(EnsembleProvider)} * but not both. * * @param connectString list of servers to connect to * @return this */ public Builder connectString(String connectString) { ensembleProvider = new FixedEnsembleProvider(connectString); return this; } /** * Set the list ensemble provider. IMPORTANT: use either this or {@link #connectString(String)} * but not both. * * @param ensembleProvider the ensemble provider to use * @return this */ public Builder ensembleProvider(EnsembleProvider ensembleProvider) { this.ensembleProvider = ensembleProvider; return this; } /** * Sets the data to use when {@link PathAndBytesable#forPath(String)} is used. * This is useful for debugging purposes. For example, you could set this to be the IP of the * client. * * @param defaultData new default data to use * @return this */ public Builder defaultData(byte[] defaultData) { this.defaultData = (defaultData != null) ? Arrays.copyOf(defaultData, defaultData.length) : null; return this; } /** * As ZooKeeper is a shared space, users of a given cluster should stay within * a pre-defined namespace. If a namespace is set here, all paths will get pre-pended * with the namespace * * @param namespace the namespace * @return this */ public Builder namespace(String namespace) { this.namespace = namespace; return this; } /** * @param sessionTimeoutMs session timeout * @return this */ public Builder sessionTimeoutMs(int sessionTimeoutMs) { this.sessionTimeoutMs = sessionTimeoutMs; return this; } /** * @param connectionTimeoutMs connection timeout * @return this */ public Builder connectionTimeoutMs(int connectionTimeoutMs) { this.connectionTimeoutMs = connectionTimeoutMs; return this; } /** * @param maxCloseWaitMs time to wait during close to join background threads * @return this */ public Builder maxCloseWaitMs(int maxCloseWaitMs) { this.maxCloseWaitMs = maxCloseWaitMs; return this; } /** * @param retryPolicy retry policy to use * @return this */ public Builder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * @param threadFactory thread factory used to create Executor Services * @return this */ public Builder threadFactory(ThreadFactory threadFactory) { this.threadFactory = threadFactory; return this; } /** * @param compressionProvider the compression provider * @return this */ public Builder compressionProvider(CompressionProvider compressionProvider) { this.compressionProvider = compressionProvider; return this; } /** * @param zookeeperFactory the zookeeper factory to use * @return this */ public Builder zookeeperFactory(ZookeeperFactory zookeeperFactory) { this.zookeeperFactory = zookeeperFactory; return this; } /** * @param aclProvider a provider for ACLs * @return this */ public Builder aclProvider(ACLProvider aclProvider) { this.aclProvider = aclProvider; return this; } /** * @param canBeReadOnly if true, allow ZooKeeper client to enter * read only mode in case of a network partition. See * {@link ZooKeeper#ZooKeeper(String, int, Watcher, long, byte[], boolean)} * for details * @return this */ public Builder canBeReadOnly(boolean canBeReadOnly) { this.canBeReadOnly = canBeReadOnly; return this; } public ACLProvider getAclProvider() { return aclProvider; } public ZookeeperFactory getZookeeperFactory() { return zookeeperFactory; } public CompressionProvider getCompressionProvider() { return compressionProvider; } public ThreadFactory getThreadFactory() { return threadFactory; } public EnsembleProvider getEnsembleProvider() { return ensembleProvider; } public int getSessionTimeoutMs() { return sessionTimeoutMs; } public int getConnectionTimeoutMs() { return connectionTimeoutMs; } public int getMaxCloseWaitMs() { return maxCloseWaitMs; } public RetryPolicy getRetryPolicy() { return retryPolicy; } public String getNamespace() { return namespace; } @Deprecated public String getAuthScheme() { int qty = (authInfos != null) ? authInfos.size() : 0; switch ( qty ) { case 0: { return null; } case 1: { return authInfos.get(0).scheme; } default: { throw new IllegalStateException("More than 1 auth has been added"); } } } @Deprecated public byte[] getAuthValue() { int qty = (authInfos != null) ? authInfos.size() : 0; switch ( qty ) { case 0: { return null; } case 1: { byte[] bytes = authInfos.get(0).getAuth(); return (bytes != null) ? Arrays.copyOf(bytes, bytes.length) : null; } default: { throw new IllegalStateException("More than 1 auth has been added"); } } } public List getAuthInfos() { return authInfos; } public byte[] getDefaultData() { return defaultData; } public boolean canBeReadOnly() { return canBeReadOnly; } private Builder() { } } private static byte[] getLocalAddress() { try { return InetAddress.getLocalHost().getHostAddress().getBytes(); } catch ( UnknownHostException ignore ) { // ignore } return new byte[0]; } private CuratorFrameworkFactory() { } } CuratorTempFramework.java000066400000000000000000000040131245521677600366120ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework; import org.apache.curator.framework.api.TempGetDataBuilder; import org.apache.curator.framework.api.transaction.CuratorTransaction; import java.io.Closeable; /** *

* Temporary CuratorFramework instances are meant for single requests to ZooKeeper ensembles * over a failure prone network such as a WAN. The APIs available from CuratorTempFramework * are limited. Further, the connection will be closed after a period of inactivity. *

* *

* Based on an idea mentioned in a post by Camille Fournier: * http://whilefalse.blogspot.com/2012/12/building-global-highly-available.html *

*/ public interface CuratorTempFramework extends Closeable { /** * Stop the client */ public void close(); /** * Start a transaction builder * * @return builder object * @throws Exception errors */ public CuratorTransaction inTransaction() throws Exception; /** * Start a get data builder * * @return builder object * @throws Exception errors */ public TempGetDataBuilder getData() throws Exception; } curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/000077500000000000000000000000001245521677600324565ustar00rootroot00000000000000ACLBackgroundPathAndBytesable.java000066400000000000000000000017401245521677600407360ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface ACLBackgroundPathAndBytesable extends ACLable>, BackgroundPathAndBytesable { } ACLBackgroundPathable.java000066400000000000000000000017101245521677600373010ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface ACLBackgroundPathable extends ACLable>, BackgroundPathable { } ACLCreateModeBackgroundPathAndBytesable.java000066400000000000000000000020311245521677600426610ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface ACLCreateModeBackgroundPathAndBytesable extends ACLBackgroundPathAndBytesable, BackgroundPathAndBytesable, CreateModable> { } ACLCreateModePathAndBytesable.java000066400000000000000000000017301245521677600406660ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface ACLCreateModePathAndBytesable extends ACLPathAndBytesable, CreateModable> { } ACLPathAndBytesable.java000066400000000000000000000017021245521677600367340ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface ACLPathAndBytesable extends ACLable>, PathAndBytesable { } ACLProvider.java000066400000000000000000000026641245521677600353640ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import org.apache.curator.utils.InternalACLProvider; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; import java.util.List; public interface ACLProvider extends InternalACLProvider { /** * Return the ACL list to use by default (usually {@link ZooDefs.Ids#OPEN_ACL_UNSAFE}). * * @return default ACL list */ public List getDefaultAcl(); /** * Return the ACL list to use for the given path * * @param path path (NOTE: might be null) * @return ACL list */ public List getAclForPath(String path); } ACLVersionBackgroundPathable.java000066400000000000000000000017511245521677600406540ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface ACLVersionBackgroundPathable extends ACLable>>, Versionable> { } ACLable.java000066400000000000000000000022351245521677600344670ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; import java.util.List; public interface ACLable { /** * Set an ACL list (default is {@link ZooDefs.Ids#OPEN_ACL_UNSAFE}) * * @param aclList the ACL list to use * @return this */ public T withACL(List aclList); } BackgroundCallback.java000066400000000000000000000024051245521677600367370ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import org.apache.curator.framework.CuratorFramework; /** * Functor for an async background operation */ public interface BackgroundCallback { /** * Called when the async background operation completes * * @param client the client * @param event operation result details * @throws Exception errors */ public void processResult(CuratorFramework client, CuratorEvent event) throws Exception; } BackgroundPathAndBytesable.java000066400000000000000000000017201245521677600404140ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface BackgroundPathAndBytesable extends Backgroundable>, PathAndBytesable { } BackgroundPathable.java000066400000000000000000000016701245521677600367660ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface BackgroundPathable extends Backgroundable>, Pathable { } BackgroundVersionable.java000066400000000000000000000017171245521677600375210ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface BackgroundVersionable extends BackgroundPathable, Versionable> { } Backgroundable.java000066400000000000000000000050201245521677600361420ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import java.util.concurrent.Executor; public interface Backgroundable { /** * Perform the action in the background * * @return this */ public T inBackground(); /** * Perform the action in the background * * @param context context object - will be available from the event sent to the listener * @return this */ public T inBackground(Object context); /** * Perform the action in the background * * @param callback a functor that will get called when the operation has completed * @return this */ public T inBackground(BackgroundCallback callback); /** * Perform the action in the background * * @param callback a functor that will get called when the operation has completed * @param context context object - will be available from the event sent to the listener * @return this */ public T inBackground(BackgroundCallback callback, Object context); /** * Perform the action in the background * * @param callback a functor that will get called when the operation has completed * @param executor executor to use for the background call * @return this */ public T inBackground(BackgroundCallback callback, Executor executor); /** * Perform the action in the background * * @param callback a functor that will get called when the operation has completed * @param context context object - will be available from the event sent to the listener * @param executor executor to use for the background call * @return this */ public T inBackground(BackgroundCallback callback, Object context, Executor executor); } ChildrenDeletable.java000066400000000000000000000021011245521677600365660ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface ChildrenDeletable extends BackgroundVersionable { /** *

* Will also delete children if they exist. *

* @return */ public BackgroundVersionable deletingChildrenIfNeeded(); } Compressible.java000066400000000000000000000020201245521677600356630ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface Compressible { /** * Cause the data to be compressed using the configured compression provider * * @return this */ public T compressed(); } CompressionProvider.java000066400000000000000000000020441245521677600372560ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface CompressionProvider { public byte[] compress(String path, byte[] data) throws Exception; public byte[] decompress(String path, byte[] compressedData) throws Exception; } CreateBackgroundModeACLable.java000066400000000000000000000046241245521677600404240ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface CreateBackgroundModeACLable extends BackgroundPathAndBytesable, CreateModable>, ACLCreateModeBackgroundPathAndBytesable { /** * Causes any parent nodes to get created if they haven't already been * * @return this */ public ACLCreateModePathAndBytesable creatingParentsIfNeeded(); /** *

* Hat-tip to https://github.com/sbridges for pointing this out *

* *

* It turns out there is an edge case that exists when creating sequential-ephemeral * nodes. The creation can succeed on the server, but the server can crash before * the created node name is returned to the client. However, the ZK session is still * valid so the ephemeral node is not deleted. Thus, there is no way for the client to * determine what node was created for them. *

* *

* Putting the create builder into protected-ephemeral-sequential mode works around this. * The name of the node that is created is prefixed with a GUID. If node creation fails * the normal retry mechanism will occur. On the retry, the parent path is first searched * for a node that has the GUID in it. If that node is found, it is assumed to be the lost * node that was successfully created on the first try and is returned to the caller. *

* * @return this */ public ACLPathAndBytesable withProtectedEphemeralSequential(); } CreateBuilder.java000066400000000000000000000056421245521677600357630ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface CreateBuilder extends BackgroundPathAndBytesable, CreateModable>, ACLCreateModeBackgroundPathAndBytesable, Compressible { /** * Causes any parent nodes to get created if they haven't already been * * @return this */ public ProtectACLCreateModePathAndBytesable creatingParentsIfNeeded(); /** * @deprecated this has been generalized to support all create modes. Instead, use: *
     *     client.create().withProtection().withMode(CreateMode.PERSISTENT_SEQUENTIAL)...
     * 
* @return this */ public ACLPathAndBytesable withProtectedEphemeralSequential(); /** *

* Hat-tip to https://github.com/sbridges for pointing this out *

* *

* It turns out there is an edge case that exists when creating sequential-ephemeral * nodes. The creation can succeed on the server, but the server can crash before * the created node name is returned to the client. However, the ZK session is still * valid so the ephemeral node is not deleted. Thus, there is no way for the client to * determine what node was created for them. *

* *

* Even without sequential-ephemeral, however, the create can succeed on the sever * but the client (for various reasons) will not know it. *

* *

* Putting the create builder into protection mode works around this. * The name of the node that is created is prefixed with a GUID. If node creation fails * the normal retry mechanism will occur. On the retry, the parent path is first searched * for a node that has the GUID in it. If that node is found, it is assumed to be the lost * node that was successfully created on the first try and is returned to the caller. *

* * @return this */ public ACLCreateModeBackgroundPathAndBytesable withProtection(); } CreateModable.java000066400000000000000000000021411245521677600357270ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import org.apache.zookeeper.CreateMode; public interface CreateModable { /** * Set a create mode - the default is {@link CreateMode#PERSISTENT} * * @param mode new create mode * @return this */ public T withMode(CreateMode mode); } CreateModalPathAndBytesable.java000066400000000000000000000017201245521677600405150ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface CreateModalPathAndBytesable extends CreateModable>, PathAndBytesable { } CuratorEvent.java000066400000000000000000000044421245521677600356670ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; import java.util.List; /** * A super set of all the various Zookeeper events/background methods. * * IMPORTANT: the methods only return values as specified by the operation that generated them. Many methods * will return null */ public interface CuratorEvent { /** * check here first - this value determines the type of event and which methods will have * valid values * * @return event type */ public CuratorEventType getType(); /** * @return "rc" from async callbacks */ public int getResultCode(); /** * @return the path */ public String getPath(); /** * @return the context object passed to {@link Backgroundable#inBackground(Object)} */ public Object getContext(); /** * @return any stat */ public Stat getStat(); /** * @return any data */ public byte[] getData(); /** * @return any name */ public String getName(); /** * @return any children */ public List getChildren(); /** * @return any ACL list or null */ public List getACLList(); /** * If {@link #getType()} returns {@link CuratorEventType#WATCHED} this will * return the WatchedEvent * * @return any WatchedEvent */ public WatchedEvent getWatchedEvent(); } CuratorEventType.java000066400000000000000000000036611245521677600365330ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.Watcher; public enum CuratorEventType { /** * Corresponds to {@link CuratorFramework#create()} */ CREATE, /** * Corresponds to {@link CuratorFramework#delete()} */ DELETE, /** * Corresponds to {@link CuratorFramework#checkExists()} */ EXISTS, /** * Corresponds to {@link CuratorFramework#getData()} */ GET_DATA, /** * Corresponds to {@link CuratorFramework#setData()} */ SET_DATA, /** * Corresponds to {@link CuratorFramework#getChildren()} */ CHILDREN, /** * Corresponds to {@link CuratorFramework#sync(String, Object)} */ SYNC, /** * Corresponds to {@link CuratorFramework#getACL()} */ GET_ACL, /** * Corresponds to {@link CuratorFramework#setACL()} */ SET_ACL, /** * Corresponds to {@link Watchable#usingWatcher(Watcher)} or {@link Watchable#watched()} */ WATCHED, /** * Event sent when client is being closed */ CLOSING } CuratorListener.java000066400000000000000000000024331245521677600363710ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import org.apache.curator.framework.CuratorFramework; /** * Receives notifications about errors and background events */ public interface CuratorListener { /** * Called when a background task has completed or a watch has triggered * * @param client client * @param event the event * @throws Exception any errors */ public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception; } CuratorWatcher.java000066400000000000000000000024321245521677600362000ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; /** * A version of {@link Watcher} that can throw an exception */ public interface CuratorWatcher { /** * Same as {@link Watcher#process(WatchedEvent)}. If an exception * is thrown, Curator will log it * * @param event the event * @throws Exception any exceptions to log */ public void process(WatchedEvent event) throws Exception; } Decompressible.java000066400000000000000000000020361245521677600362030ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface Decompressible { /** * Cause the data to be de-compressed using the configured compression provider * * @return this */ public T decompressed(); } DeleteBuilder.java000066400000000000000000000016401245521677600357540ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface DeleteBuilder extends Guaranteeable, ChildrenDeletable { } ExistsBuilder.java000066400000000000000000000017551245521677600360400ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import org.apache.zookeeper.data.Stat; public interface ExistsBuilder extends Watchable>, BackgroundPathable { } GetACLBuilder.java000066400000000000000000000020021245521677600356020ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import org.apache.zookeeper.data.ACL; import java.util.List; public interface GetACLBuilder extends BackgroundPathable>, Statable>> { } GetChildrenBuilder.java000066400000000000000000000020351245521677600367410ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import java.util.List; public interface GetChildrenBuilder extends Watchable>>, BackgroundPathable>, Statable>> { } GetDataBuilder.java000066400000000000000000000020431245521677600360610ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface GetDataBuilder extends Watchable>, BackgroundPathable, Statable>, Decompressible { } GetDataWatchBackgroundStatable.java000066400000000000000000000017771245521677600412360ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface GetDataWatchBackgroundStatable extends Watchable>, BackgroundPathable, Statable> { } Guaranteeable.java000066400000000000000000000032711245521677600360040ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface Guaranteeable extends BackgroundVersionable { /** *

* Solves this edge case: deleting a node can fail due to connection issues. Further, * if the node was ephemeral, the node will not get auto-deleted as the session is still valid. * This can wreak havoc with lock implementations. *

* *

* When guaranteed is set, Curator will record failed node deletions and * attempt to delete them in the background until successful. NOTE: you will still get an * exception when the deletion fails. But, you can be assured that as long as the * {@link org.apache.curator.framework.CuratorFramework} instance is open attempts will be made to delete the node. *

* * @return this */ public ChildrenDeletable guaranteed(); } PathAndBytesable.java000066400000000000000000000031661245521677600364220ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import org.apache.curator.framework.CuratorFrameworkFactory; public interface PathAndBytesable { /** * Commit the currently building operation using the given path and data * * @param path the path * @param data the data * @return operation result if any * @throws Exception errors */ public T forPath(String path, byte[] data) throws Exception; /** * Commit the currently building operation using the given path and the default data * for the client (usually a byte[0] unless changed via * {@link CuratorFrameworkFactory.Builder#defaultData(byte[])}). * * @param path the path * @return operation result if any * @throws Exception errors */ public T forPath(String path) throws Exception; } Pathable.java000066400000000000000000000021551245521677600347650ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface Pathable { /** * Commit the currently building operation using the given path * * @param path the path * @return operation result if any * @throws Exception errors */ public T forPath(String path) throws Exception; } ProtectACLCreateModePathAndBytesable.java000066400000000000000000000044751245521677600422400ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface ProtectACLCreateModePathAndBytesable extends ACLBackgroundPathAndBytesable, CreateModable> { /** *

* Hat-tip to https://github.com/sbridges for pointing this out *

* *

* It turns out there is an edge case that exists when creating sequential-ephemeral * nodes. The creation can succeed on the server, but the server can crash before * the created node name is returned to the client. However, the ZK session is still * valid so the ephemeral node is not deleted. Thus, there is no way for the client to * determine what node was created for them. *

* *

* Even without sequential-ephemeral, however, the create can succeed on the sever * but the client (for various reasons) will not know it. *

* *

* Putting the create builder into protection mode works around this. * The name of the node that is created is prefixed with a GUID. If node creation fails * the normal retry mechanism will occur. On the retry, the parent path is first searched * for a node that has the GUID in it. If that node is found, it is assumed to be the lost * node that was successfully created on the first try and is returned to the caller. *

* * @return this */ public ACLCreateModeBackgroundPathAndBytesable withProtection(); } SetACLBuilder.java000066400000000000000000000020011245521677600356150ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import org.apache.zookeeper.data.Stat; public interface SetACLBuilder extends ACLable>, Versionable>> { } SetDataBackgroundVersionable.java000066400000000000000000000020161245521677600407600ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import org.apache.zookeeper.data.Stat; public interface SetDataBackgroundVersionable extends BackgroundPathAndBytesable, Versionable> { } SetDataBuilder.java000066400000000000000000000020601245521677600360740ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import org.apache.zookeeper.data.Stat; public interface SetDataBuilder extends BackgroundPathAndBytesable, Versionable>, Compressible { } StatPathable.java000066400000000000000000000016541245521677600356240ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface StatPathable extends Pathable, Statable> { } Statable.java000066400000000000000000000021251245521677600350010ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import org.apache.zookeeper.data.Stat; public interface Statable { /** * Have the operation fill the provided stat object * * @param stat the stat to have filled in * @return this */ public T storingStatIn(Stat stat); } SyncBuilder.java000066400000000000000000000016321245521677600354670ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface SyncBuilder extends BackgroundPathable { } TempGetDataBuilder.java000066400000000000000000000017351245521677600367160ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface TempGetDataBuilder extends StatPathable, Decompressible>, Pathable { } UnhandledErrorListener.java000066400000000000000000000026351245521677600376720ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; public interface UnhandledErrorListener { /** * Called when an exception is caught in a background thread, handler, etc. Before this * listener is called, the error will have been logged and a {@link ConnectionState#LOST} * event will have been queued for any {@link ConnectionStateListener}s. * * @param message Source message * @param e exception */ public void unhandledError(String message, Throwable e); } Versionable.java000066400000000000000000000020441245521677600355130ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface Versionable { /** * Use the given version (the default is -1) * * @param version version to use * @return this */ public T withVersion(int version); } WatchPathable.java000066400000000000000000000016561245521677600357610ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; public interface WatchPathable extends Watchable>, Pathable { } Watchable.java000066400000000000000000000025161245521677600351400ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api; import org.apache.zookeeper.Watcher; public interface Watchable { /** * Have the operation set a watch * * @return this */ public T watched(); /** * Set a watcher for the operation * * @param watcher the watcher * @return this */ public T usingWatcher(Watcher watcher); /** * Set a watcher for the operation * * @param watcher the watcher * @return this */ public T usingWatcher(CuratorWatcher watcher); } 000077500000000000000000000000001245521677600347245ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/transactionCuratorTransaction.java000066400000000000000000000045071245521677600414220ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api.transaction; import org.apache.zookeeper.ZooKeeper; /** *

* Transactional/atomic operations. See {@link ZooKeeper#multi(Iterable)} for * details on ZooKeeper transactions. *

* *

* The general form for this interface is: *

*
 *         curator.inTransaction().operation().arguments().forPath(...).
 *             and().more-operations.
 *             and().commit();
 *     
* *

* Here's an example that creates two nodes in a transaction *

*
 *         curator.inTransaction().
 *             create().forPath("/path-one", path-one-data).
 *             and().create().forPath("/path-two", path-two-data).
 *             and().commit();
 *     
* *

* Important: the operations are not submitted until * {@link CuratorTransactionFinal#commit()} is called. *

*/ public interface CuratorTransaction { /** * Start a create builder in the transaction * * @return builder object */ public TransactionCreateBuilder create(); /** * Start a delete builder in the transaction * * @return builder object */ public TransactionDeleteBuilder delete(); /** * Start a setData builder in the transaction * * @return builder object */ public TransactionSetDataBuilder setData(); /** * Start a check builder in the transaction *ChildData * @return builder object */ public TransactionCheckBuilder check(); } CuratorTransactionBridge.java000066400000000000000000000020711245521677600425310ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api.transaction; public interface CuratorTransactionBridge { /** * Syntactic sugar to make the fluent interface more readable * * @return transaction continuation */ public CuratorTransactionFinal and(); } CuratorTransactionFinal.java000066400000000000000000000026311245521677600423700ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api.transaction; import java.util.Collection; /** * Adds commit to the transaction interface */ public interface CuratorTransactionFinal extends CuratorTransaction { /** * Commit all added operations as an atomic unit and return results * for the operations. One result is returned for each operation added. * Further, the ordering of the results matches the ordering that the * operations were added. * * @return operation results * @throws Exception errors */ public Collection commit() throws Exception; } CuratorTransactionResult.java000066400000000000000000000061251245521677600426170ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api.transaction; import com.google.common.base.Predicate; import org.apache.zookeeper.data.Stat; /** * Holds the result of one transactional operation */ public class CuratorTransactionResult { private final OperationType type; private final String forPath; private final String resultPath; private final Stat resultStat; /** * Utility that can be passed to Google Guava to find a particular result. E.g. *
     * Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, path))
     * 
* * @param type operation type * @param forPath path * @return predicate */ public static Predicate ofTypeAndPath(final OperationType type, final String forPath) { return new Predicate() { @Override public boolean apply(CuratorTransactionResult result) { return (result.getType() == type) && result.getForPath().equals(forPath); } }; } public CuratorTransactionResult(OperationType type, String forPath, String resultPath, Stat resultStat) { this.forPath = forPath; this.resultPath = resultPath; this.resultStat = resultStat; this.type = type; } /** * Returns the operation type * * @return operation type */ public OperationType getType() { return type; } /** * Returns the path that was passed to the operation when added * * @return operation input path */ public String getForPath() { return forPath; } /** * Returns the operation generated path or null. i.e. {@link CuratorTransaction#create()} * using an EPHEMERAL mode generates the created path plus its sequence number. * * @return generated path or null */ public String getResultPath() { return resultPath; } /** * Returns the operation generated stat or null. i.e. {@link CuratorTransaction#setData()} * generates a stat object. * * @return generated stat or null */ public Stat getResultStat() { return resultStat; } } OperationType.java000066400000000000000000000023041245521677600403700ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api.transaction; /** * Transaction operation types */ public enum OperationType { /** * {@link CuratorTransaction#create()} */ CREATE, /** * {@link CuratorTransaction#delete()} */ DELETE, /** * {@link CuratorTransaction#setData()} */ SET_DATA, /** * {@link CuratorTransaction#check()} */ CHECK } TransactionCheckBuilder.java000066400000000000000000000021311245521677600423160ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api.transaction; import org.apache.curator.framework.api.Pathable; import org.apache.curator.framework.api.Versionable; public interface TransactionCheckBuilder extends Pathable, Versionable> { } TransactionCreateBuilder.java000066400000000000000000000025401245521677600425100ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api.transaction; import org.apache.curator.framework.api.ACLPathAndBytesable; import org.apache.curator.framework.api.Compressible; import org.apache.curator.framework.api.CreateModable; import org.apache.curator.framework.api.PathAndBytesable; public interface TransactionCreateBuilder extends PathAndBytesable, CreateModable>, ACLPathAndBytesable, Compressible> { } TransactionDeleteBuilder.java000066400000000000000000000021321245521677600425040ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api.transaction; import org.apache.curator.framework.api.Pathable; import org.apache.curator.framework.api.Versionable; public interface TransactionDeleteBuilder extends Pathable, Versionable> { } TransactionSetDataBuilder.java000066400000000000000000000023471245521677600426370ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.api.transaction; import org.apache.curator.framework.api.Compressible; import org.apache.curator.framework.api.PathAndBytesable; import org.apache.curator.framework.api.Versionable; public interface TransactionSetDataBuilder extends PathAndBytesable, Versionable>, Compressible> { } curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/000077500000000000000000000000001245521677600326555ustar00rootroot00000000000000ACLing.java000066400000000000000000000036241245521677600345430ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import com.google.common.collect.ImmutableList; import org.apache.curator.framework.api.ACLProvider; import org.apache.zookeeper.data.ACL; import java.util.List; class ACLing { private final List aclList; private final ACLProvider aclProvider; ACLing(ACLProvider aclProvider) { this(aclProvider, null); } ACLing(ACLProvider aclProvider, List aclList) { this.aclProvider = aclProvider; this.aclList = (aclList != null) ? ImmutableList.copyOf(aclList) : null; } List getAclList(String path) { List localAclList = aclList; do { if ( localAclList != null ) { break; } if ( path != null ) { localAclList = aclProvider.getAclForPath(path); if ( localAclList != null ) { break; } } localAclList = aclProvider.getDefaultAcl(); } while ( false ); return localAclList; } } BackgroundOperation.java000066400000000000000000000017211245521677600374020ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; interface BackgroundOperation { public void performBackgroundOperation(OperationAndData data) throws Exception; } BackgroundSyncImpl.java000066400000000000000000000040731245521677600372030ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.TimeTrace; import org.apache.curator.framework.api.CuratorEventType; import org.apache.zookeeper.AsyncCallback; class BackgroundSyncImpl implements BackgroundOperation { private final CuratorFrameworkImpl client; private final Object context; BackgroundSyncImpl(CuratorFrameworkImpl client, Object context) { this.client = client; this.context = context; } @Override public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { final TimeTrace trace = client.getZookeeperClient().startTracer("BackgroundSyncImpl"); client.getZooKeeper().sync ( operationAndData.getData(), new AsyncCallback.VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { trace.commit(); CuratorEventImpl event = new CuratorEventImpl(client, CuratorEventType.SYNC, rc, path, null, ctx, null, null, null, null, null); client.processBackgroundOperation(operationAndData, event); } }, context ); } } Backgrounding.java000066400000000000000000000074341245521677600362260ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.KeeperException; import java.util.concurrent.Executor; class Backgrounding { private final boolean inBackground; private final Object context; private final BackgroundCallback callback; Backgrounding(Object context) { this.inBackground = true; this.context = context; this.callback = null; } Backgrounding(BackgroundCallback callback) { this.inBackground = true; this.context = null; this.callback = callback; } Backgrounding(boolean inBackground) { this.inBackground = inBackground; this.context = null; this.callback = null; } Backgrounding(BackgroundCallback callback, Object context) { this.inBackground = true; this.context = context; this.callback = callback; } Backgrounding(CuratorFrameworkImpl client, BackgroundCallback callback, Object context, Executor executor) { this(wrapCallback(client, callback, executor), context); } Backgrounding(CuratorFrameworkImpl client, BackgroundCallback callback, Executor executor) { this(wrapCallback(client, callback, executor)); } Backgrounding() { inBackground = false; context = null; this.callback = null; } boolean inBackground() { return inBackground; } Object getContext() { return context; } BackgroundCallback getCallback() { return callback; } private static BackgroundCallback wrapCallback(final CuratorFrameworkImpl client, final BackgroundCallback callback, final Executor executor) { return new BackgroundCallback() { @Override public void processResult(CuratorFramework dummy, final CuratorEvent event) throws Exception { executor.execute ( new Runnable() { @Override public void run() { try { callback.processResult(client, event); } catch ( Exception e ) { if ( e instanceof KeeperException ) { client.validateConnection(client.codeToState(((KeeperException)e).code())); } client.logError("Background operation result handling threw exception", e); } } } ); } }; } } CreateBuilderImpl.java000066400000000000000000000730251245521677600370040ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import org.apache.curator.RetryLoop; import org.apache.curator.TimeTrace; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.*; import org.apache.curator.framework.api.transaction.CuratorTransactionBridge; import org.apache.curator.framework.api.transaction.OperationType; import org.apache.curator.framework.api.transaction.TransactionCreateBuilder; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.AsyncCallback; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Op; import org.apache.zookeeper.data.ACL; import java.util.List; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; class CreateBuilderImpl implements CreateBuilder, BackgroundOperation { private final CuratorFrameworkImpl client; private CreateMode createMode; private Backgrounding backgrounding; private boolean createParentsIfNeeded; private boolean doProtected; private boolean compress; private String protectedId; private ACLing acling; @VisibleForTesting boolean failNextCreateForTesting = false; @VisibleForTesting static final String PROTECTED_PREFIX = "_c_"; CreateBuilderImpl(CuratorFrameworkImpl client) { this.client = client; createMode = CreateMode.PERSISTENT; backgrounding = new Backgrounding(); acling = new ACLing(client.getAclProvider()); createParentsIfNeeded = false; compress = false; doProtected = false; protectedId = null; } TransactionCreateBuilder asTransactionCreateBuilder(final CuratorTransactionImpl curatorTransaction, final CuratorMultiTransactionRecord transaction) { return new TransactionCreateBuilder() { @Override public PathAndBytesable withACL(List aclList) { CreateBuilderImpl.this.withACL(aclList); return this; } @Override public ACLPathAndBytesable withMode(CreateMode mode) { CreateBuilderImpl.this.withMode(mode); return this; } @Override public ACLPathAndBytesable compressed() { CreateBuilderImpl.this.compressed(); return this; } @Override public CuratorTransactionBridge forPath(String path) throws Exception { return forPath(path, client.getDefaultData()); } @Override public CuratorTransactionBridge forPath(String path, byte[] data) throws Exception { if ( compress ) { data = client.getCompressionProvider().compress(path, data); } String fixedPath = client.fixForNamespace(path); transaction.add(Op.create(fixedPath, data, acling.getAclList(path), createMode), OperationType.CREATE, path); return curatorTransaction; } }; } @Override public CreateBackgroundModeACLable compressed() { compress = true; return new CreateBackgroundModeACLable() { @Override public ACLCreateModePathAndBytesable creatingParentsIfNeeded() { createParentsIfNeeded = true; return asACLCreateModePathAndBytesable(); } @Override public ACLPathAndBytesable withProtectedEphemeralSequential() { return CreateBuilderImpl.this.withProtectedEphemeralSequential(); } @Override public BackgroundPathAndBytesable withACL(List aclList) { return CreateBuilderImpl.this.withACL(aclList); } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Object context) { return CreateBuilderImpl.this.inBackground(callback, context); } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Object context, Executor executor) { return CreateBuilderImpl.this.inBackground(callback, context, executor); } @Override public PathAndBytesable inBackground() { return CreateBuilderImpl.this.inBackground(); } @Override public PathAndBytesable inBackground(Object context) { return CreateBuilderImpl.this.inBackground(context); } @Override public PathAndBytesable inBackground(BackgroundCallback callback) { return CreateBuilderImpl.this.inBackground(callback); } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Executor executor) { return CreateBuilderImpl.this.inBackground(callback, executor); } @Override public ACLBackgroundPathAndBytesable withMode(CreateMode mode) { return CreateBuilderImpl.this.withMode(mode); } @Override public String forPath(String path, byte[] data) throws Exception { return CreateBuilderImpl.this.forPath(path, data); } @Override public String forPath(String path) throws Exception { return CreateBuilderImpl.this.forPath(path); } }; } @Override public ACLBackgroundPathAndBytesable withACL(List aclList) { acling = new ACLing(client.getAclProvider(), aclList); return new ACLBackgroundPathAndBytesable() { @Override public BackgroundPathAndBytesable withACL(List aclList) { return CreateBuilderImpl.this.withACL(aclList); } @Override public PathAndBytesable inBackground() { return CreateBuilderImpl.this.inBackground(); } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Object context) { return CreateBuilderImpl.this.inBackground(callback, context); } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Object context, Executor executor) { return CreateBuilderImpl.this.inBackground(callback, context, executor); } @Override public PathAndBytesable inBackground(Object context) { return CreateBuilderImpl.this.inBackground(context); } @Override public PathAndBytesable inBackground(BackgroundCallback callback) { return CreateBuilderImpl.this.inBackground(callback); } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Executor executor) { return CreateBuilderImpl.this.inBackground(callback, executor); } @Override public String forPath(String path, byte[] data) throws Exception { return CreateBuilderImpl.this.forPath(path, data); } @Override public String forPath(String path) throws Exception { return CreateBuilderImpl.this.forPath(path); } }; } @Override public ProtectACLCreateModePathAndBytesable creatingParentsIfNeeded() { createParentsIfNeeded = true; return new ProtectACLCreateModePathAndBytesable() { @Override public ACLCreateModeBackgroundPathAndBytesable withProtection() { return CreateBuilderImpl.this.withProtection(); } @Override public BackgroundPathAndBytesable withACL(List aclList) { return CreateBuilderImpl.this.withACL(aclList); } @Override public PathAndBytesable inBackground() { return CreateBuilderImpl.this.inBackground(); } @Override public PathAndBytesable inBackground(Object context) { return CreateBuilderImpl.this.inBackground(context); } @Override public PathAndBytesable inBackground(BackgroundCallback callback) { return CreateBuilderImpl.this.inBackground(callback); } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Object context) { return CreateBuilderImpl.this.inBackground(callback, context); } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Executor executor) { return CreateBuilderImpl.this.inBackground(callback, executor); } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Object context, Executor executor) { return CreateBuilderImpl.this.inBackground(callback, context, executor); } @Override public ACLBackgroundPathAndBytesable withMode(CreateMode mode) { return CreateBuilderImpl.this.withMode(mode); } @Override public String forPath(String path, byte[] data) throws Exception { return CreateBuilderImpl.this.forPath(path, data); } @Override public String forPath(String path) throws Exception { return CreateBuilderImpl.this.forPath(path); } }; } @Override public ACLCreateModeBackgroundPathAndBytesable withProtection() { setProtected(); return this; } @Override public ACLPathAndBytesable withProtectedEphemeralSequential() { setProtected(); createMode = CreateMode.EPHEMERAL_SEQUENTIAL; return new ACLPathAndBytesable() { @Override public PathAndBytesable withACL(List aclList) { return CreateBuilderImpl.this.withACL(aclList); } @Override public String forPath(String path, byte[] data) throws Exception { return CreateBuilderImpl.this.forPath(path, data); } @Override public String forPath(String path) throws Exception { return CreateBuilderImpl.this.forPath(path); } }; } @Override public ACLBackgroundPathAndBytesable withMode(CreateMode mode) { createMode = mode; return this; } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override public PathAndBytesable inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(client, callback, executor); return this; } @Override public PathAndBytesable inBackground() { backgrounding = new Backgrounding(true); return this; } @Override public PathAndBytesable inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override public String forPath(String path) throws Exception { return forPath(path, client.getDefaultData()); } @Override public String forPath(final String givenPath, byte[] data) throws Exception { if ( compress ) { data = client.getCompressionProvider().compress(givenPath, data); } final String adjustedPath = adjustPath(client.fixForNamespace(givenPath, createMode.isSequential())); String returnPath = null; if ( backgrounding.inBackground() ) { pathInBackground(adjustedPath, data, givenPath); } else { String path = protectedPathInForeground(adjustedPath, data); returnPath = client.unfixForNamespace(path); } return returnPath; } private String protectedPathInForeground(String adjustedPath, byte[] data) throws Exception { try { return pathInForeground(adjustedPath, data); } catch ( Exception e) { if ( ( e instanceof KeeperException.ConnectionLossException || !( e instanceof KeeperException )) && protectedId != null ) { /* * CURATOR-45 + CURATOR-79: we don't know if the create operation was successful or not, * register the znode to be sure it is deleted later. */ String localProtectedId = protectedId; findAndDeleteProtectedNodeInBackground(adjustedPath, localProtectedId, null); /* * The current UUID is scheduled to be deleted, it is not safe to use it again. * If this builder is used again later create a new UUID */ protectedId = UUID.randomUUID().toString(); } throw e; } } @Override public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { final TimeTrace trace = client.getZookeeperClient().startTracer("CreateBuilderImpl-Background"); client.getZooKeeper().create ( operationAndData.getData().getPath(), operationAndData.getData().getData(), acling.getAclList(operationAndData.getData().getPath()), createMode, new AsyncCallback.StringCallback() { @Override public void processResult(int rc, String path, Object ctx, String name) { trace.commit(); if ( (rc == KeeperException.Code.NONODE.intValue()) && createParentsIfNeeded ) { backgroundCreateParentsThenNode(operationAndData); } else { sendBackgroundResponse(rc, path, ctx, name, operationAndData); } } }, backgrounding.getContext() ); } private static String getProtectedPrefix(String protectedId) { return PROTECTED_PREFIX + protectedId + "-"; } private void backgroundCreateParentsThenNode(final OperationAndData mainOperationAndData) { BackgroundOperation operation = new BackgroundOperation() { @Override public void performBackgroundOperation(OperationAndData dummy) throws Exception { try { ZKPaths.mkdirs(client.getZooKeeper(), mainOperationAndData.getData().getPath(), false, client.getAclProvider()); } catch ( KeeperException e ) { // ignore } client.queueOperation(mainOperationAndData); } }; OperationAndData parentOperation = new OperationAndData(operation, mainOperationAndData.getData(), null, null, backgrounding.getContext()); client.queueOperation(parentOperation); } private void sendBackgroundResponse(int rc, String path, Object ctx, String name, OperationAndData operationAndData) { path = client.unfixForNamespace(path); name = client.unfixForNamespace(name); CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.CREATE, rc, path, name, ctx, null, null, null, null, null); client.processBackgroundOperation(operationAndData, event); } private void setProtected() { doProtected = true; protectedId = UUID.randomUUID().toString(); } private ACLCreateModePathAndBytesable asACLCreateModePathAndBytesable() { return new ACLCreateModePathAndBytesable() { @Override public PathAndBytesable withACL(List aclList) { return CreateBuilderImpl.this.withACL(aclList); } @Override public ACLPathAndBytesable withMode(CreateMode mode) { createMode = mode; return new ACLPathAndBytesable() { @Override public PathAndBytesable withACL(List aclList) { return CreateBuilderImpl.this.withACL(aclList); } @Override public String forPath(String path, byte[] data) throws Exception { return CreateBuilderImpl.this.forPath(path, data); } @Override public String forPath(String path) throws Exception { return CreateBuilderImpl.this.forPath(path); } }; } @Override public String forPath(String path, byte[] data) throws Exception { return CreateBuilderImpl.this.forPath(path, data); } @Override public String forPath(String path) throws Exception { return CreateBuilderImpl.this.forPath(path); } }; } private void pathInBackground(final String path, final byte[] data, final String givenPath) { final AtomicBoolean firstTime = new AtomicBoolean(true); OperationAndData operationAndData = new OperationAndData(this, new PathAndBytes(path, data), backgrounding.getCallback(), new OperationAndData.ErrorCallback() { public void retriesExhausted(OperationAndData operationAndData) { if ( doProtected ) { // all retries have failed, findProtectedNodeInForeground(..) included, schedule a clean up findAndDeleteProtectedNodeInBackground(path, protectedId, null); // assign a new id if this builder is used again later protectedId = UUID.randomUUID().toString(); } } }, backgrounding.getContext()) { @Override void callPerformBackgroundOperation() throws Exception { boolean callSuper = true; boolean localFirstTime = firstTime.getAndSet(false); if ( !localFirstTime && doProtected ) { String createdPath = null; try { createdPath = findProtectedNodeInForeground(path); } catch ( KeeperException.ConnectionLossException e ) { sendBackgroundResponse(KeeperException.Code.CONNECTIONLOSS.intValue(), path, backgrounding.getContext(), null, this); callSuper = false; } if ( createdPath != null ) { try { sendBackgroundResponse(KeeperException.Code.OK.intValue(), createdPath, backgrounding.getContext(), ZKPaths.getNodeFromPath(createdPath), this); } catch ( Exception e ) { client.logError("Processing protected create for path: " + givenPath, e); } callSuper = false; } } if ( failNextCreateForTesting ) { pathInForeground(path, data); // simulate success on server without notification to client failNextCreateForTesting = false; throw new KeeperException.ConnectionLossException(); } if ( callSuper ) { super.callPerformBackgroundOperation(); } } }; client.processBackgroundOperation(operationAndData, null); } private String pathInForeground(final String path, final byte[] data) throws Exception { TimeTrace trace = client.getZookeeperClient().startTracer("CreateBuilderImpl-Foreground"); final AtomicBoolean firstTime = new AtomicBoolean(true); String returnPath = RetryLoop.callWithRetry ( client.getZookeeperClient(), new Callable() { @Override public String call() throws Exception { boolean localFirstTime = firstTime.getAndSet(false); String createdPath = null; if ( !localFirstTime && doProtected ) { createdPath = findProtectedNodeInForeground(path); } if ( createdPath == null ) { try { createdPath = client.getZooKeeper().create(path, data, acling.getAclList(path), createMode); } catch ( KeeperException.NoNodeException e ) { if ( createParentsIfNeeded ) { ZKPaths.mkdirs(client.getZooKeeper(), path, false, client.getAclProvider()); createdPath = client.getZooKeeper().create(path, data, acling.getAclList(path), createMode); } else { throw e; } } } if ( failNextCreateForTesting ) { failNextCreateForTesting = false; throw new KeeperException.ConnectionLossException(); } return createdPath; } } ); trace.commit(); return returnPath; } private String findProtectedNodeInForeground(final String path) throws Exception { TimeTrace trace = client.getZookeeperClient().startTracer("CreateBuilderImpl-findProtectedNodeInForeground"); String returnPath = RetryLoop.callWithRetry ( client.getZookeeperClient(), new Callable() { @Override public String call() throws Exception { String foundNode = null; try { final ZKPaths.PathAndNode pathAndNode = ZKPaths.getPathAndNode(path); List children = client.getZooKeeper().getChildren(pathAndNode.getPath(), false); foundNode = findNode(children, pathAndNode.getPath(), protectedId); } catch ( KeeperException.NoNodeException ignore ) { // ignore } return foundNode; } } ); trace.commit(); return returnPath; } private String adjustPath(String path) throws Exception { if ( doProtected ) { ZKPaths.PathAndNode pathAndNode = ZKPaths.getPathAndNode(path); String name = getProtectedPrefix(protectedId) + pathAndNode.getNode(); path = ZKPaths.makePath(pathAndNode.getPath(), name); } return path; } /** * Attempt to delete a protected znode * * @param path the path * @param protectedId the protected id * @param callback callback to use, null to create a new one */ private void findAndDeleteProtectedNodeInBackground(String path, String protectedId, FindProtectedNodeCB callback) { if ( client.getState() == CuratorFrameworkState.STARTED ) { if ( callback == null ) { callback = new FindProtectedNodeCB(path, protectedId); } try { client.getChildren().inBackground(callback).forPath(ZKPaths.getPathAndNode(path).getPath()); } catch ( Exception e ) { findAndDeleteProtectedNodeInBackground(path, protectedId, callback); } } } private class FindProtectedNodeCB implements BackgroundCallback { final String path; final String protectedId; private FindProtectedNodeCB(String path, String protectedId) { this.path = path; this.protectedId = protectedId; } @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) { final String node = findNode(event.getChildren(), ZKPaths.getPathAndNode(path).getPath(), protectedId); if ( node != null ) { client.delete().guaranteed().inBackground().forPath(node); } } else if ( event.getResultCode() == KeeperException.Code.CONNECTIONLOSS.intValue() ) { // retry findAndDeleteProtectedNodeInBackground(path, protectedId, this); } } } /** * Attempt to find the znode that matches the given path and protected id * * @param children a list of candidates znodes * @param path the path * @param protectedId the protected id * @return the absolute path of the znode or null if it is not found */ private static String findNode(final List children, final String path, final String protectedId) { final String protectedPrefix = getProtectedPrefix(protectedId); String foundNode = Iterables.find ( children, new Predicate() { @Override public boolean apply(String node) { return node.startsWith(protectedPrefix); } }, null ); if ( foundNode != null ) { foundNode = ZKPaths.makePath(path, foundNode); } return foundNode; } } CuratorEventImpl.java000066400000000000000000000071621245521677600367120ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import com.google.common.collect.ImmutableList; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorEventType; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; import java.util.Arrays; import java.util.List; class CuratorEventImpl implements CuratorEvent { private final CuratorEventType type; private final int resultCode; private final String path; private final String name; private final List children; private final Object context; private final Stat stat; private final byte[] data; private final WatchedEvent watchedEvent; private final List aclList; @Override public CuratorEventType getType() { return type; } @Override public int getResultCode() { return resultCode; } @Override public String getPath() { return path; } @Override public Object getContext() { return context; } @Override public Stat getStat() { return stat; } @Override public byte[] getData() { return data; } @Override public String getName() { return name; } @Override public List getChildren() { return children; } @Override public WatchedEvent getWatchedEvent() { return watchedEvent; } @Override public List getACLList() { return aclList; } @Override public String toString() { return "CuratorEventImpl{" + "type=" + type + ", resultCode=" + resultCode + ", path='" + path + '\'' + ", name='" + name + '\'' + ", children=" + children + ", context=" + context + ", stat=" + stat + ", data=" + Arrays.toString(data) + ", watchedEvent=" + watchedEvent + ", aclList=" + aclList + '}'; } CuratorEventImpl(CuratorFrameworkImpl client, CuratorEventType type, int resultCode, String path, String name, Object context, Stat stat, byte[] data, List children, WatchedEvent watchedEvent, List aclList) { this.type = type; this.resultCode = resultCode; this.path = client.unfixForNamespace(path); this.name = name; this.context = context; this.stat = stat; this.data = data; this.children = children; this.watchedEvent = (watchedEvent != null) ? new NamespaceWatchedEvent(client, watchedEvent) : watchedEvent; this.aclList = (aclList != null) ? ImmutableList.copyOf(aclList) : null; } } CuratorFrameworkImpl.java000066400000000000000000000715471245521677600375760ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import org.apache.curator.CuratorConnectionLossException; import org.apache.curator.CuratorZookeeperClient; import org.apache.curator.RetryLoop; import org.apache.curator.TimeTrace; import org.apache.curator.framework.AuthInfo; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.*; import org.apache.curator.framework.api.transaction.CuratorTransaction; import org.apache.curator.framework.listen.Listenable; import org.apache.curator.framework.listen.ListenerContainer; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.framework.state.ConnectionStateManager; import org.apache.curator.utils.DebugUtils; import org.apache.curator.utils.EnsurePath; import org.apache.curator.utils.ThreadUtils; import org.apache.curator.utils.ZookeeperFactory; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.DelayQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; public class CuratorFrameworkImpl implements CuratorFramework { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorZookeeperClient client; private final ListenerContainer listeners; private final ListenerContainer unhandledErrorListeners; private final ThreadFactory threadFactory; private final int maxCloseWaitMs; private final BlockingQueue> backgroundOperations; private final NamespaceImpl namespace; private final ConnectionStateManager connectionStateManager; private final List authInfos; private final byte[] defaultData; private final FailedDeleteManager failedDeleteManager; private final CompressionProvider compressionProvider; private final ACLProvider aclProvider; private final NamespaceFacadeCache namespaceFacadeCache; private final NamespaceWatcherMap namespaceWatcherMap = new NamespaceWatcherMap(this); private volatile ExecutorService executorService; private final AtomicBoolean logAsErrorConnectionErrors = new AtomicBoolean(false); private static final boolean LOG_ALL_CONNECTION_ISSUES_AS_ERROR_LEVEL = !Boolean.getBoolean(DebugUtils.PROPERTY_LOG_ONLY_FIRST_CONNECTION_ISSUE_AS_ERROR_LEVEL); interface DebugBackgroundListener { void listen(OperationAndData data); } volatile DebugBackgroundListener debugListener = null; @VisibleForTesting public volatile UnhandledErrorListener debugUnhandledErrorListener = null; private final AtomicReference state; public CuratorFrameworkImpl(CuratorFrameworkFactory.Builder builder) { ZookeeperFactory localZookeeperFactory = makeZookeeperFactory(builder.getZookeeperFactory()); this.client = new CuratorZookeeperClient(localZookeeperFactory, builder.getEnsembleProvider(), builder.getSessionTimeoutMs(), builder.getConnectionTimeoutMs(), new Watcher() { @Override public void process(WatchedEvent watchedEvent) { CuratorEvent event = new CuratorEventImpl(CuratorFrameworkImpl.this, CuratorEventType.WATCHED, watchedEvent.getState().getIntValue(), unfixForNamespace(watchedEvent.getPath()), null, null, null, null, null, watchedEvent, null); processEvent(event); } }, builder.getRetryPolicy(), builder.canBeReadOnly()); listeners = new ListenerContainer(); unhandledErrorListeners = new ListenerContainer(); backgroundOperations = new DelayQueue>(); namespace = new NamespaceImpl(this, builder.getNamespace()); threadFactory = getThreadFactory(builder); maxCloseWaitMs = builder.getMaxCloseWaitMs(); connectionStateManager = new ConnectionStateManager(this, builder.getThreadFactory()); compressionProvider = builder.getCompressionProvider(); aclProvider = builder.getAclProvider(); state = new AtomicReference(CuratorFrameworkState.LATENT); byte[] builderDefaultData = builder.getDefaultData(); defaultData = (builderDefaultData != null) ? Arrays.copyOf(builderDefaultData, builderDefaultData.length) : new byte[0]; authInfos = buildAuths(builder); failedDeleteManager = new FailedDeleteManager(this); namespaceFacadeCache = new NamespaceFacadeCache(this); } private List buildAuths(CuratorFrameworkFactory.Builder builder) { ImmutableList.Builder builder1 = ImmutableList.builder(); if ( builder.getAuthInfos() != null ) { builder1.addAll(builder.getAuthInfos()); } return builder1.build(); } private ZookeeperFactory makeZookeeperFactory(final ZookeeperFactory actualZookeeperFactory) { return new ZookeeperFactory() { @Override public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly) throws Exception { ZooKeeper zooKeeper = actualZookeeperFactory.newZooKeeper(connectString, sessionTimeout, watcher, canBeReadOnly); for ( AuthInfo auth : authInfos ) { zooKeeper.addAuthInfo(auth.getScheme(), auth.getAuth()); } return zooKeeper; } }; } private ThreadFactory getThreadFactory(CuratorFrameworkFactory.Builder builder) { ThreadFactory threadFactory = builder.getThreadFactory(); if ( threadFactory == null ) { threadFactory = ThreadUtils.newThreadFactory("Framework"); } return threadFactory; } protected CuratorFrameworkImpl(CuratorFrameworkImpl parent) { client = parent.client; listeners = parent.listeners; unhandledErrorListeners = parent.unhandledErrorListeners; threadFactory = parent.threadFactory; maxCloseWaitMs = parent.maxCloseWaitMs; backgroundOperations = parent.backgroundOperations; connectionStateManager = parent.connectionStateManager; defaultData = parent.defaultData; failedDeleteManager = parent.failedDeleteManager; compressionProvider = parent.compressionProvider; aclProvider = parent.aclProvider; namespaceFacadeCache = parent.namespaceFacadeCache; namespace = new NamespaceImpl(this, null); state = parent.state; authInfos = parent.authInfos; } @Override public void clearWatcherReferences(Watcher watcher) { NamespaceWatcher namespaceWatcher = namespaceWatcherMap.remove(watcher); if ( namespaceWatcher != null ) { namespaceWatcher.close(); } } @Override public CuratorFrameworkState getState() { return state.get(); } @Override @Deprecated public boolean isStarted() { return state.get() == CuratorFrameworkState.STARTED; } @Override public boolean blockUntilConnected(int maxWaitTime, TimeUnit units) throws InterruptedException { return connectionStateManager.blockUntilConnected(maxWaitTime, units); } @Override public void blockUntilConnected() throws InterruptedException { blockUntilConnected(0, null); } @Override public void start() { log.info("Starting"); if ( !state.compareAndSet(CuratorFrameworkState.LATENT, CuratorFrameworkState.STARTED) ) { throw new IllegalStateException("Cannot be started more than once"); } try { connectionStateManager.start(); // ordering dependency - must be called before client.start() final ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( ConnectionState.CONNECTED == newState || ConnectionState.RECONNECTED == newState ) { logAsErrorConnectionErrors.set(true); } } }; this.getConnectionStateListenable().addListener(listener); client.start(); executorService = Executors.newFixedThreadPool(2, threadFactory); // 1 for listeners, 1 for background ops executorService.submit(new Callable() { @Override public Object call() throws Exception { backgroundOperationsLoop(); return null; } }); } catch ( Exception e ) { handleBackgroundOperationException(null, e); } } @Override public void close() { log.debug("Closing"); if ( state.compareAndSet(CuratorFrameworkState.STARTED, CuratorFrameworkState.STOPPED) ) { listeners.forEach(new Function() { @Override public Void apply(CuratorListener listener) { CuratorEvent event = new CuratorEventImpl(CuratorFrameworkImpl.this, CuratorEventType.CLOSING, 0, null, null, null, null, null, null, null, null); try { listener.eventReceived(CuratorFrameworkImpl.this, event); } catch ( Exception e ) { log.error("Exception while sending Closing event", e); } return null; } }); if ( executorService != null ) { executorService.shutdownNow(); try { executorService.awaitTermination(maxCloseWaitMs, TimeUnit.MILLISECONDS); } catch ( InterruptedException e ) { // Interrupted while interrupting; I give up. Thread.currentThread().interrupt(); } } listeners.clear(); unhandledErrorListeners.clear(); connectionStateManager.close(); client.close(); namespaceWatcherMap.close(); } } @Override @Deprecated public CuratorFramework nonNamespaceView() { return usingNamespace(null); } @Override public String getNamespace() { String str = namespace.getNamespace(); return (str != null) ? str : ""; } @Override public CuratorFramework usingNamespace(String newNamespace) { Preconditions.checkState(getState() == CuratorFrameworkState.STARTED, "instance must be started before calling this method"); return namespaceFacadeCache.get(newNamespace); } @Override public CreateBuilder create() { Preconditions.checkState(getState() == CuratorFrameworkState.STARTED, "instance must be started before calling this method"); return new CreateBuilderImpl(this); } @Override public DeleteBuilder delete() { Preconditions.checkState(getState() == CuratorFrameworkState.STARTED, "instance must be started before calling this method"); return new DeleteBuilderImpl(this); } @Override public ExistsBuilder checkExists() { Preconditions.checkState(getState() == CuratorFrameworkState.STARTED, "instance must be started before calling this method"); return new ExistsBuilderImpl(this); } @Override public GetDataBuilder getData() { Preconditions.checkState(getState() == CuratorFrameworkState.STARTED, "instance must be started before calling this method"); return new GetDataBuilderImpl(this); } @Override public SetDataBuilder setData() { Preconditions.checkState(getState() == CuratorFrameworkState.STARTED, "instance must be started before calling this method"); return new SetDataBuilderImpl(this); } @Override public GetChildrenBuilder getChildren() { Preconditions.checkState(getState() == CuratorFrameworkState.STARTED, "instance must be started before calling this method"); return new GetChildrenBuilderImpl(this); } @Override public GetACLBuilder getACL() { Preconditions.checkState(getState() == CuratorFrameworkState.STARTED, "instance must be started before calling this method"); return new GetACLBuilderImpl(this); } @Override public SetACLBuilder setACL() { Preconditions.checkState(getState() == CuratorFrameworkState.STARTED, "instance must be started before calling this method"); return new SetACLBuilderImpl(this); } @Override public CuratorTransaction inTransaction() { Preconditions.checkState(getState() == CuratorFrameworkState.STARTED, "instance must be started before calling this method"); return new CuratorTransactionImpl(this); } @Override public Listenable getConnectionStateListenable() { return connectionStateManager.getListenable(); } @Override public Listenable getCuratorListenable() { return listeners; } @Override public Listenable getUnhandledErrorListenable() { return unhandledErrorListeners; } @Override public void sync(String path, Object context) { Preconditions.checkState(getState() == CuratorFrameworkState.STARTED, "instance must be started before calling this method"); path = fixForNamespace(path); internalSync(this, path, context); } @Override public SyncBuilder sync() { return new SyncBuilderImpl(this); } protected void internalSync(CuratorFrameworkImpl impl, String path, Object context) { BackgroundOperation operation = new BackgroundSyncImpl(impl, context); performBackgroundOperation(new OperationAndData(operation, path, null, null, context)); } @Override public CuratorZookeeperClient getZookeeperClient() { return client; } @Override public EnsurePath newNamespaceAwareEnsurePath(String path) { return namespace.newNamespaceAwareEnsurePath(path); } ACLProvider getAclProvider() { return aclProvider; } FailedDeleteManager getFailedDeleteManager() { return failedDeleteManager; } RetryLoop newRetryLoop() { return client.newRetryLoop(); } ZooKeeper getZooKeeper() throws Exception { return client.getZooKeeper(); } CompressionProvider getCompressionProvider() { return compressionProvider; } void processBackgroundOperation(OperationAndData operationAndData, CuratorEvent event) { boolean isInitialExecution = (event == null); if ( isInitialExecution ) { performBackgroundOperation(operationAndData); return; } boolean doQueueOperation = false; do { if ( RetryLoop.shouldRetry(event.getResultCode()) ) { doQueueOperation = checkBackgroundRetry(operationAndData, event); break; } if ( operationAndData.getCallback() != null ) { sendToBackgroundCallback(operationAndData, event); break; } processEvent(event); } while ( false ); if ( doQueueOperation ) { queueOperation(operationAndData); } } void queueOperation(OperationAndData operationAndData) { backgroundOperations.offer(operationAndData); } void logError(String reason, final Throwable e) { if ( (reason == null) || (reason.length() == 0) ) { reason = "n/a"; } if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) || !(e instanceof KeeperException) ) { if ( e instanceof KeeperException.ConnectionLossException ) { if ( LOG_ALL_CONNECTION_ISSUES_AS_ERROR_LEVEL || logAsErrorConnectionErrors.compareAndSet(true, false) ) { log.error(reason, e); } else { log.debug(reason, e); } } else { log.error(reason, e); } } final String localReason = reason; unhandledErrorListeners.forEach(new Function() { @Override public Void apply(UnhandledErrorListener listener) { listener.unhandledError(localReason, e); return null; } }); if ( debugUnhandledErrorListener != null ) { debugUnhandledErrorListener.unhandledError(reason, e); } } String unfixForNamespace(String path) { return namespace.unfixForNamespace(path); } String fixForNamespace(String path) { return namespace.fixForNamespace(path, false); } String fixForNamespace(String path, boolean isSequential) { return namespace.fixForNamespace(path, isSequential); } byte[] getDefaultData() { return defaultData; } NamespaceFacadeCache getNamespaceFacadeCache() { return namespaceFacadeCache; } NamespaceWatcherMap getNamespaceWatcherMap() { return namespaceWatcherMap; } void validateConnection(Watcher.Event.KeeperState state) { if ( state == Watcher.Event.KeeperState.Disconnected ) { suspendConnection(); } else if ( state == Watcher.Event.KeeperState.Expired ) { connectionStateManager.addStateChange(ConnectionState.LOST); } else if ( state == Watcher.Event.KeeperState.SyncConnected ) { connectionStateManager.addStateChange(ConnectionState.RECONNECTED); } else if ( state == Watcher.Event.KeeperState.ConnectedReadOnly ) { connectionStateManager.addStateChange(ConnectionState.READ_ONLY); } } Watcher.Event.KeeperState codeToState(KeeperException.Code code) { switch ( code ) { case AUTHFAILED: case NOAUTH: { return Watcher.Event.KeeperState.AuthFailed; } case CONNECTIONLOSS: case OPERATIONTIMEOUT: { return Watcher.Event.KeeperState.Disconnected; } case SESSIONEXPIRED: { return Watcher.Event.KeeperState.Expired; } case OK: case SESSIONMOVED: { return Watcher.Event.KeeperState.SyncConnected; } } return Watcher.Event.KeeperState.fromInt(-1); } private void suspendConnection() { if ( !connectionStateManager.setToSuspended() ) { return; } doSyncForSuspendedConnection(client.getInstanceIndex()); } private void doSyncForSuspendedConnection(final long instanceIndex) { // we appear to have disconnected, force a new ZK event and see if we can connect to another server final BackgroundOperation operation = new BackgroundSyncImpl(this, null); OperationAndData.ErrorCallback errorCallback = new OperationAndData.ErrorCallback() { @Override public void retriesExhausted(OperationAndData operationAndData) { // if instanceIndex != newInstanceIndex, the ZooKeeper instance was reset/reallocated // so the pending background sync is no longer valid. // if instanceIndex is -1, this is the second try to sync - punt and mark the connection lost if ( (instanceIndex < 0) || (instanceIndex == client.getInstanceIndex()) ) { connectionStateManager.addStateChange(ConnectionState.LOST); } else { log.debug("suspendConnection() failure ignored as the ZooKeeper instance was reset. Retrying."); // send -1 to signal that if it happens again, punt and mark the connection lost doSyncForSuspendedConnection(-1); } } }; performBackgroundOperation(new OperationAndData(operation, "/", null, errorCallback, null)); } @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"}) private boolean checkBackgroundRetry(OperationAndData operationAndData, CuratorEvent event) { boolean doRetry = false; if ( client.getRetryPolicy().allowRetry(operationAndData.getThenIncrementRetryCount(), operationAndData.getElapsedTimeMs(), operationAndData) ) { doRetry = true; } else { if ( operationAndData.getErrorCallback() != null ) { operationAndData.getErrorCallback().retriesExhausted(operationAndData); } if ( operationAndData.getCallback() != null ) { sendToBackgroundCallback(operationAndData, event); } KeeperException.Code code = KeeperException.Code.get(event.getResultCode()); Exception e = null; try { e = (code != null) ? KeeperException.create(code) : null; } catch ( Throwable ignore ) { } if ( e == null ) { e = new Exception("Unknown result codegetResultCode()"); } validateConnection(codeToState(code)); logError("Background operation retry gave up", e); } return doRetry; } private void sendToBackgroundCallback(OperationAndData operationAndData, CuratorEvent event) { try { operationAndData.getCallback().processResult(this, event); } catch ( Exception e ) { handleBackgroundOperationException(operationAndData, e); } } private void handleBackgroundOperationException(OperationAndData operationAndData, Throwable e) { do { if ( (operationAndData != null) && RetryLoop.isRetryException(e) ) { if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) ) { log.debug("Retry-able exception received", e); } if ( client.getRetryPolicy().allowRetry(operationAndData.getThenIncrementRetryCount(), operationAndData.getElapsedTimeMs(), operationAndData) ) { if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) ) { log.debug("Retrying operation"); } backgroundOperations.offer(operationAndData); break; } else { if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) ) { log.debug("Retry policy did not allow retry"); } if ( operationAndData.getErrorCallback() != null ) { operationAndData.getErrorCallback().retriesExhausted(operationAndData); } } } logError("Background exception was not retry-able or retry gave up", e); } while ( false ); } private void backgroundOperationsLoop() { while ( !Thread.currentThread().isInterrupted() ) { OperationAndData operationAndData; try { operationAndData = backgroundOperations.take(); if ( debugListener != null ) { debugListener.listen(operationAndData); } } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); break; } performBackgroundOperation(operationAndData); } } private void performBackgroundOperation(OperationAndData operationAndData) { try { if ( client.isConnected() ) { operationAndData.callPerformBackgroundOperation(); } else { client.getZooKeeper(); // important - allow connection resets, timeouts, etc. to occur if ( operationAndData.getElapsedTimeMs() >= client.getConnectionTimeoutMs() ) { throw new CuratorConnectionLossException(); } operationAndData.sleepFor(1, TimeUnit.SECONDS); queueOperation(operationAndData); } } catch ( Throwable e ) { /** * Fix edge case reported as CURATOR-52. ConnectionState.checkTimeouts() throws KeeperException.ConnectionLossException * when the initial (or previously failed) connection cannot be re-established. This needs to be run through the retry policy * and callbacks need to get invoked, etc. */ if ( e instanceof CuratorConnectionLossException ) { WatchedEvent watchedEvent = new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.Disconnected, null); CuratorEvent event = new CuratorEventImpl(this, CuratorEventType.WATCHED, KeeperException.Code.CONNECTIONLOSS.intValue(), null, null, operationAndData.getContext(), null, null, null, watchedEvent, null); if ( checkBackgroundRetry(operationAndData, event) ) { queueOperation(operationAndData); } else { logError("Background retry gave up", e); } } else { handleBackgroundOperationException(operationAndData, e); } } } private void processEvent(final CuratorEvent curatorEvent) { if ( curatorEvent.getType() == CuratorEventType.WATCHED ) { validateConnection(curatorEvent.getWatchedEvent().getState()); } listeners.forEach(new Function() { @Override public Void apply(CuratorListener listener) { try { TimeTrace trace = client.startTracer("EventListener"); listener.eventReceived(CuratorFrameworkImpl.this, curatorEvent); trace.commit(); } catch ( Exception e ) { logError("Event listener threw exception", e); } return null; } }); } } CuratorFrameworkState.java000066400000000000000000000023451245521677600377430ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.framework.CuratorFramework; /** * @see CuratorFramework#getState() */ public enum CuratorFrameworkState { /** * {@link CuratorFramework#start()} has not yet been called */ LATENT, /** * {@link CuratorFramework#start()} has been called */ STARTED, /** * {@link CuratorFramework#close()} has been called */ STOPPED } CuratorMultiTransactionRecord.java000066400000000000000000000035521245521677600414450ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import com.google.common.collect.Lists; import org.apache.curator.framework.api.transaction.OperationType; import org.apache.zookeeper.MultiTransactionRecord; import org.apache.zookeeper.Op; import java.util.List; class CuratorMultiTransactionRecord extends MultiTransactionRecord { private final List metadata = Lists.newArrayList(); static class TypeAndPath { final OperationType type; final String forPath; TypeAndPath(OperationType type, String forPath) { this.type = type; this.forPath = forPath; } } @Override public final void add(Op op) { throw new UnsupportedOperationException(); } void add(Op op, OperationType type, String forPath) { super.add(op); metadata.add(new TypeAndPath(type, forPath)); } TypeAndPath getMetadata(int index) { return metadata.get(index); } int metadataSize() { return metadata.size(); } } CuratorTempFrameworkImpl.java000066400000000000000000000105001245521677600404020ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.CuratorTempFramework; import org.apache.curator.framework.api.TempGetDataBuilder; import org.apache.curator.framework.api.transaction.CuratorTransaction; import org.apache.curator.utils.ThreadUtils; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; public class CuratorTempFrameworkImpl implements CuratorTempFramework { private final CuratorFrameworkFactory.Builder factory; private final long inactiveThresholdMs; // guarded by sync private CuratorFrameworkImpl client; // guarded by sync private ScheduledExecutorService cleanup; // guarded by sync private long lastAccess; public CuratorTempFrameworkImpl(CuratorFrameworkFactory.Builder factory, long inactiveThresholdMs) { this.factory = factory; this.inactiveThresholdMs = inactiveThresholdMs; } @Override public void close() { closeClient(); } @Override public CuratorTransaction inTransaction() throws Exception { openConnectionIfNeeded(); return new CuratorTransactionImpl(client); } @Override public TempGetDataBuilder getData() throws Exception { openConnectionIfNeeded(); return new TempGetDataBuilderImpl(client); } @VisibleForTesting CuratorFrameworkImpl getClient() { return client; } @VisibleForTesting ScheduledExecutorService getCleanup() { return cleanup; } @VisibleForTesting synchronized void updateLastAccess() { lastAccess = System.currentTimeMillis(); } private synchronized void openConnectionIfNeeded() throws Exception { if ( client == null ) { client = (CuratorFrameworkImpl)factory.build(); // cast is safe - we control both sides of this client.start(); } if ( cleanup == null ) { ThreadFactory threadFactory = factory.getThreadFactory(); if (threadFactory == null) { threadFactory = ThreadUtils.newGenericThreadFactory("CuratorTempFrameworkImpl"); } cleanup = Executors.newScheduledThreadPool(1, threadFactory); Runnable command = new Runnable() { @Override public void run() { checkInactive(); } }; cleanup.scheduleAtFixedRate(command, inactiveThresholdMs, inactiveThresholdMs, TimeUnit.MILLISECONDS); } updateLastAccess(); } private synchronized void checkInactive() { long elapsed = System.currentTimeMillis() - lastAccess; if ( elapsed >= inactiveThresholdMs ) { closeClient(); } } private synchronized void closeClient() { if ( cleanup != null ) { cleanup.shutdownNow(); cleanup = null; } if ( client != null ) { CloseableUtils.closeQuietly(client); client = null; } } } CuratorTransactionImpl.java000066400000000000000000000164531245521677600401210ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import org.apache.curator.RetryLoop; import org.apache.curator.framework.api.Pathable; import org.apache.curator.framework.api.transaction.CuratorTransaction; import org.apache.curator.framework.api.transaction.CuratorTransactionBridge; import org.apache.curator.framework.api.transaction.CuratorTransactionFinal; import org.apache.curator.framework.api.transaction.CuratorTransactionResult; import org.apache.curator.framework.api.transaction.OperationType; import org.apache.curator.framework.api.transaction.TransactionCheckBuilder; import org.apache.curator.framework.api.transaction.TransactionCreateBuilder; import org.apache.curator.framework.api.transaction.TransactionDeleteBuilder; import org.apache.curator.framework.api.transaction.TransactionSetDataBuilder; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Op; import org.apache.zookeeper.OpResult; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.Stat; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicBoolean; class CuratorTransactionImpl implements CuratorTransaction, CuratorTransactionBridge, CuratorTransactionFinal { private final CuratorFrameworkImpl client; private final CuratorMultiTransactionRecord transaction; private boolean isCommitted = false; CuratorTransactionImpl(CuratorFrameworkImpl client) { this.client = client; transaction = new CuratorMultiTransactionRecord(); } @Override public CuratorTransactionFinal and() { return this; } @Override public TransactionCreateBuilder create() { Preconditions.checkState(!isCommitted, "transaction already committed"); return new CreateBuilderImpl(client).asTransactionCreateBuilder(this, transaction); } @Override public TransactionDeleteBuilder delete() { Preconditions.checkState(!isCommitted, "transaction already committed"); return new DeleteBuilderImpl(client).asTransactionDeleteBuilder(this, transaction); } @Override public TransactionSetDataBuilder setData() { Preconditions.checkState(!isCommitted, "transaction already committed"); return new SetDataBuilderImpl(client).asTransactionSetDataBuilder(this, transaction); } @Override public TransactionCheckBuilder check() { Preconditions.checkState(!isCommitted, "transaction already committed"); return new TransactionCheckBuilder() { private int version = -1; @Override public CuratorTransactionBridge forPath(String path) throws Exception { String fixedPath = client.fixForNamespace(path); transaction.add(Op.check(fixedPath, version), OperationType.CHECK, path); return CuratorTransactionImpl.this; } @Override public Pathable withVersion(int version) { this.version = version; return this; } }; } @Override public Collection commit() throws Exception { Preconditions.checkState(!isCommitted, "transaction already committed"); isCommitted = true; final AtomicBoolean firstTime = new AtomicBoolean(true); List resultList = RetryLoop.callWithRetry ( client.getZookeeperClient(), new Callable>() { @Override public List call() throws Exception { return doOperation(firstTime); } } ); if ( resultList.size() != transaction.metadataSize() ) { throw new IllegalStateException(String.format("Result size (%d) doesn't match input size (%d)", resultList.size(), transaction.metadataSize())); } ImmutableList.Builder builder = ImmutableList.builder(); for ( int i = 0; i < resultList.size(); ++i ) { OpResult opResult = resultList.get(i); CuratorMultiTransactionRecord.TypeAndPath metadata = transaction.getMetadata(i); CuratorTransactionResult curatorResult = makeCuratorResult(opResult, metadata); builder.add(curatorResult); } return builder.build(); } private List doOperation(AtomicBoolean firstTime) throws Exception { boolean localFirstTime = firstTime.getAndSet(false); if ( !localFirstTime ) { } List opResults = client.getZooKeeper().multi(transaction); if ( opResults.size() > 0 ) { OpResult firstResult = opResults.get(0); if ( firstResult.getType() == ZooDefs.OpCode.error ) { OpResult.ErrorResult error = (OpResult.ErrorResult)firstResult; KeeperException.Code code = KeeperException.Code.get(error.getErr()); if ( code == null ) { code = KeeperException.Code.UNIMPLEMENTED; } throw KeeperException.create(code); } } return opResults; } private CuratorTransactionResult makeCuratorResult(OpResult opResult, CuratorMultiTransactionRecord.TypeAndPath metadata) { String resultPath = null; Stat resultStat = null; switch ( opResult.getType() ) { default: { // NOP break; } case ZooDefs.OpCode.create: { OpResult.CreateResult createResult = (OpResult.CreateResult)opResult; resultPath = client.unfixForNamespace(createResult.getPath()); break; } case ZooDefs.OpCode.setData: { OpResult.SetDataResult setDataResult = (OpResult.SetDataResult)opResult; resultStat = setDataResult.getStat(); break; } } return new CuratorTransactionResult(metadata.type, metadata.forPath, resultPath, resultStat); } } DefaultACLProvider.java000066400000000000000000000024121245521677600370570ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.framework.api.ACLProvider; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; import java.util.List; public class DefaultACLProvider implements ACLProvider { @Override public List getDefaultAcl() { return ZooDefs.Ids.OPEN_ACL_UNSAFE; } @Override public List getAclForPath(String path) { return ZooDefs.Ids.OPEN_ACL_UNSAFE; } } DeleteBuilderImpl.java000066400000000000000000000220011245521677600367670ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.RetryLoop; import org.apache.curator.TimeTrace; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.BackgroundPathable; import org.apache.curator.framework.api.BackgroundVersionable; import org.apache.curator.framework.api.ChildrenDeletable; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.framework.api.DeleteBuilder; import org.apache.curator.framework.api.Pathable; import org.apache.curator.framework.api.transaction.CuratorTransactionBridge; import org.apache.curator.framework.api.transaction.OperationType; import org.apache.curator.framework.api.transaction.TransactionDeleteBuilder; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.AsyncCallback; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Op; import java.util.concurrent.Callable; import java.util.concurrent.Executor; class DeleteBuilderImpl implements DeleteBuilder, BackgroundOperation { private final CuratorFrameworkImpl client; private int version; private Backgrounding backgrounding; private boolean deletingChildrenIfNeeded; private boolean guaranteed; DeleteBuilderImpl(CuratorFrameworkImpl client) { this.client = client; version = -1; backgrounding = new Backgrounding(); deletingChildrenIfNeeded = false; guaranteed = false; } TransactionDeleteBuilder asTransactionDeleteBuilder(final CuratorTransactionImpl curatorTransaction, final CuratorMultiTransactionRecord transaction) { return new TransactionDeleteBuilder() { @Override public CuratorTransactionBridge forPath(String path) throws Exception { String fixedPath = client.fixForNamespace(path); transaction.add(Op.delete(fixedPath, version), OperationType.DELETE, path); return curatorTransaction; } @Override public Pathable withVersion(int version) { DeleteBuilderImpl.this.withVersion(version); return this; } }; } @Override public ChildrenDeletable guaranteed() { guaranteed = true; return this; } @Override public BackgroundVersionable deletingChildrenIfNeeded() { deletingChildrenIfNeeded = true; return this; } @Override public BackgroundPathable withVersion(int version) { this.version = version; return this; } @Override public Pathable inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override public Pathable inBackground(BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override public Pathable inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override public Pathable inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(client, callback, executor); return this; } @Override public Pathable inBackground() { backgrounding = new Backgrounding(true); return this; } @Override public Pathable inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { final TimeTrace trace = client.getZookeeperClient().startTracer("DeleteBuilderImpl-Background"); client.getZooKeeper().delete ( operationAndData.getData(), version, new AsyncCallback.VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { trace.commit(); if ((rc == KeeperException.Code.NOTEMPTY.intValue()) && deletingChildrenIfNeeded) { backgroundDeleteChildrenThenNode(operationAndData); } else { CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.DELETE, rc, path, null, ctx, null, null, null, null, null); client.processBackgroundOperation(operationAndData, event); } } }, backgrounding.getContext() ); } private void backgroundDeleteChildrenThenNode(final OperationAndData mainOperationAndData) { BackgroundOperation operation = new BackgroundOperation() { @Override public void performBackgroundOperation(OperationAndData dummy) throws Exception { try { ZKPaths.deleteChildren(client.getZooKeeper(), mainOperationAndData.getData(), false); } catch ( KeeperException e ) { // ignore } client.queueOperation(mainOperationAndData); } }; OperationAndData parentOperation = new OperationAndData(operation, mainOperationAndData.getData(), null, null, backgrounding.getContext()); client.queueOperation(parentOperation); } @Override public Void forPath(String path) throws Exception { final String unfixedPath = path; path = client.fixForNamespace(path); if ( backgrounding.inBackground() ) { OperationAndData.ErrorCallback errorCallback = null; if ( guaranteed ) { errorCallback = new OperationAndData.ErrorCallback() { @Override public void retriesExhausted(OperationAndData operationAndData) { client.getFailedDeleteManager().addFailedDelete(unfixedPath); } }; } client.processBackgroundOperation(new OperationAndData(this, path, backgrounding.getCallback(), errorCallback, backgrounding.getContext()), null); } else { pathInForeground(path, unfixedPath); } return null; } protected int getVersion() { return version; } private void pathInForeground(final String path, String unfixedPath) throws Exception { TimeTrace trace = client.getZookeeperClient().startTracer("DeleteBuilderImpl-Foreground"); try { RetryLoop.callWithRetry ( client.getZookeeperClient(), new Callable() { @Override public Void call() throws Exception { try { client.getZooKeeper().delete(path, version); } catch (KeeperException.NotEmptyException e) { if (deletingChildrenIfNeeded) { ZKPaths.deleteChildren(client.getZooKeeper(), path, true); } else { throw e; } } return null; } } ); } catch ( Exception e ) { //Only retry a guaranteed delete if it's a retryable error if( RetryLoop.isRetryException(e) && guaranteed ) { client.getFailedDeleteManager().addFailedDelete(unfixedPath); } throw e; } trace.commit(); } } ExistsBuilderImpl.java000066400000000000000000000135021245521677600370520ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.RetryLoop; import org.apache.curator.TimeTrace; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.BackgroundPathable; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.curator.framework.api.ExistsBuilder; import org.apache.curator.framework.api.Pathable; import org.apache.zookeeper.AsyncCallback; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.data.Stat; import java.util.concurrent.Callable; import java.util.concurrent.Executor; class ExistsBuilderImpl implements ExistsBuilder, BackgroundOperation { private final CuratorFrameworkImpl client; private Backgrounding backgrounding; private Watching watching; ExistsBuilderImpl(CuratorFrameworkImpl client) { this.client = client; backgrounding = new Backgrounding(); watching = new Watching(); } @Override public BackgroundPathable watched() { watching = new Watching(true); return this; } @Override public BackgroundPathable usingWatcher(Watcher watcher) { watching = new Watching(client, watcher); return this; } @Override public BackgroundPathable usingWatcher(CuratorWatcher watcher) { watching = new Watching(client, watcher); return this; } @Override public Pathable inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override public Pathable inBackground(BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override public Pathable inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override public Pathable inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(client, callback, executor); return this; } @Override public Pathable inBackground() { backgrounding = new Backgrounding(true); return this; } @Override public Pathable inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { final TimeTrace trace = client.getZookeeperClient().startTracer("ExistsBuilderImpl-Background"); AsyncCallback.StatCallback callback = new AsyncCallback.StatCallback() { @Override public void processResult(int rc, String path, Object ctx, Stat stat) { trace.commit(); CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.EXISTS, rc, path, null, ctx, stat, null, null, null, null); client.processBackgroundOperation(operationAndData, event); } }; if ( watching.isWatched() ) { client.getZooKeeper().exists(operationAndData.getData(), true, callback, backgrounding.getContext()); } else { client.getZooKeeper().exists(operationAndData.getData(), watching.getWatcher(), callback, backgrounding.getContext()); } } @Override public Stat forPath(String path) throws Exception { path = client.fixForNamespace(path); Stat returnStat = null; if ( backgrounding.inBackground() ) { client.processBackgroundOperation(new OperationAndData(this, path, backgrounding.getCallback(), null, backgrounding.getContext()), null); } else { returnStat = pathInForeground(path); } return returnStat; } private Stat pathInForeground(final String path) throws Exception { TimeTrace trace = client.getZookeeperClient().startTracer("ExistsBuilderImpl-Foreground"); Stat returnStat = RetryLoop.callWithRetry ( client.getZookeeperClient(), new Callable() { @Override public Stat call() throws Exception { Stat returnStat; if ( watching.isWatched() ) { returnStat = client.getZooKeeper().exists(path, true); } else { returnStat = client.getZooKeeper().exists(path, watching.getWatcher()); } return returnStat; } } ); trace.commit(); return returnStat; } } FailedDeleteManager.java000066400000000000000000000036221245521677600372460ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.framework.CuratorFramework; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class FailedDeleteManager { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework client; volatile FailedDeleteManagerListener debugListener = null; interface FailedDeleteManagerListener { public void pathAddedForDelete(String path); } FailedDeleteManager(CuratorFramework client) { this.client = client; } void addFailedDelete(String path) { if ( debugListener != null ) { debugListener.pathAddedForDelete(path); } if ( client.getState() == CuratorFrameworkState.STARTED ) { log.debug("Path being added to guaranteed delete set: " + path); try { client.delete().guaranteed().inBackground().forPath(path); } catch ( Exception e ) { addFailedDelete(path); } } } } GetACLBuilderImpl.java000066400000000000000000000116351245521677600366370ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.RetryLoop; import org.apache.curator.TimeTrace; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.framework.api.GetACLBuilder; import org.apache.curator.framework.api.Pathable; import org.apache.zookeeper.AsyncCallback; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Executor; class GetACLBuilderImpl implements GetACLBuilder, BackgroundOperation { private final CuratorFrameworkImpl client; private Backgrounding backgrounding; private Stat responseStat; GetACLBuilderImpl(CuratorFrameworkImpl client) { this.client = client; backgrounding = new Backgrounding(); responseStat = new Stat(); } @Override public Pathable> inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override public Pathable> inBackground(BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override public Pathable> inBackground() { backgrounding = new Backgrounding(true); return this; } @Override public Pathable> inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override public Pathable> inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override public Pathable> inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(client, callback, executor); return this; } @Override public Pathable> storingStatIn(Stat stat) { responseStat = stat; return this; } @Override public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { final TimeTrace trace = client.getZookeeperClient().startTracer("GetACLBuilderImpl-Background"); AsyncCallback.ACLCallback callback = new AsyncCallback.ACLCallback() { @Override public void processResult(int rc, String path, Object ctx, List acl, Stat stat) { trace.commit(); CuratorEventImpl event = new CuratorEventImpl(client, CuratorEventType.GET_ACL, rc, path, null, ctx, stat, null, null, null, acl); client.processBackgroundOperation(operationAndData, event); } }; client.getZooKeeper().getACL(operationAndData.getData(), responseStat, callback, backgrounding.getContext()); } @Override public List forPath(String path) throws Exception { path = client.fixForNamespace(path); List result = null; if ( backgrounding.inBackground() ) { client.processBackgroundOperation(new OperationAndData(this, path, backgrounding.getCallback(), null, backgrounding.getContext()), null); } else { result = pathInForeground(path); } return result; } private List pathInForeground(final String path) throws Exception { TimeTrace trace = client.getZookeeperClient().startTracer("GetACLBuilderImpl-Foreground"); List result = RetryLoop.callWithRetry ( client.getZookeeperClient(), new Callable>() { @Override public List call() throws Exception { return client.getZooKeeper().getACL(path, responseStat); } } ); trace.commit(); return result; } } GetChildrenBuilderImpl.java000066400000000000000000000165711245521677600377740ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import com.google.common.collect.Lists; import org.apache.curator.RetryLoop; import org.apache.curator.TimeTrace; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.BackgroundPathable; import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.curator.framework.api.GetChildrenBuilder; import org.apache.curator.framework.api.Pathable; import org.apache.curator.framework.api.WatchPathable; import org.apache.zookeeper.AsyncCallback; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.data.Stat; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Executor; class GetChildrenBuilderImpl implements GetChildrenBuilder, BackgroundOperation { private final CuratorFrameworkImpl client; private Watching watching; private Backgrounding backgrounding; private Stat responseStat; GetChildrenBuilderImpl(CuratorFrameworkImpl client) { this.client = client; watching = new Watching(); backgrounding = new Backgrounding(); responseStat = null; } @Override public WatchPathable> storingStatIn(Stat stat) { responseStat = stat; return new WatchPathable>() { @Override public List forPath(String path) throws Exception { return GetChildrenBuilderImpl.this.forPath(path); } @Override public Pathable> watched() { GetChildrenBuilderImpl.this.watched(); return GetChildrenBuilderImpl.this; } @Override public Pathable> usingWatcher(Watcher watcher) { GetChildrenBuilderImpl.this.usingWatcher(watcher); return GetChildrenBuilderImpl.this; } @Override public Pathable> usingWatcher(CuratorWatcher watcher) { GetChildrenBuilderImpl.this.usingWatcher(watcher); return GetChildrenBuilderImpl.this; } }; } @Override public Pathable> inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override public Pathable> inBackground(BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override public Pathable> inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override public Pathable> inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(client, callback, executor); return this; } @Override public Pathable> inBackground() { backgrounding = new Backgrounding(true); return this; } @Override public Pathable> inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override public BackgroundPathable> watched() { watching = new Watching(true); return this; } @Override public BackgroundPathable> usingWatcher(Watcher watcher) { watching = new Watching(client, watcher); return this; } @Override public BackgroundPathable> usingWatcher(CuratorWatcher watcher) { watching = new Watching(client, watcher); return this; } @Override public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { final TimeTrace trace = client.getZookeeperClient().startTracer("GetChildrenBuilderImpl-Background"); AsyncCallback.Children2Callback callback = new AsyncCallback.Children2Callback() { @Override public void processResult(int rc, String path, Object o, List strings, Stat stat) { trace.commit(); if ( strings == null ) { strings = Lists.newArrayList(); } CuratorEventImpl event = new CuratorEventImpl(client, CuratorEventType.CHILDREN, rc, path, null, o, stat, null, strings, null, null); client.processBackgroundOperation(operationAndData, event); } }; if ( watching.isWatched() ) { client.getZooKeeper().getChildren(operationAndData.getData(), true, callback, backgrounding.getContext()); } else { client.getZooKeeper().getChildren(operationAndData.getData(), watching.getWatcher(), callback, backgrounding.getContext()); } } @Override public List forPath(String path) throws Exception { path = client.fixForNamespace(path); List children = null; if ( backgrounding.inBackground() ) { client.processBackgroundOperation(new OperationAndData(this, path, backgrounding.getCallback(), null, backgrounding.getContext()), null); } else { children = pathInForeground(path); } return children; } private List pathInForeground(final String path) throws Exception { TimeTrace trace = client.getZookeeperClient().startTracer("GetChildrenBuilderImpl-Foreground"); List children = RetryLoop.callWithRetry ( client.getZookeeperClient(), new Callable>() { @Override public List call() throws Exception { List children; if ( watching.isWatched() ) { children = client.getZooKeeper().getChildren(path, true, responseStat); } else { children = client.getZooKeeper().getChildren(path, watching.getWatcher(), responseStat); } return children; } } ); trace.commit(); return children; } } GetDataBuilderImpl.java000066400000000000000000000244201245521677600371050ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.RetryLoop; import org.apache.curator.TimeTrace; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.BackgroundPathable; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.curator.framework.api.GetDataBuilder; import org.apache.curator.framework.api.GetDataWatchBackgroundStatable; import org.apache.curator.framework.api.Pathable; import org.apache.curator.framework.api.WatchPathable; import org.apache.zookeeper.AsyncCallback; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Callable; import java.util.concurrent.Executor; class GetDataBuilderImpl implements GetDataBuilder, BackgroundOperation { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFrameworkImpl client; private Stat responseStat; private Watching watching; private Backgrounding backgrounding; private boolean decompress; GetDataBuilderImpl(CuratorFrameworkImpl client) { this.client = client; responseStat = null; watching = new Watching(); backgrounding = new Backgrounding(); decompress = false; } @Override public GetDataWatchBackgroundStatable decompressed() { decompress = true; return new GetDataWatchBackgroundStatable() { @Override public Pathable inBackground() { return GetDataBuilderImpl.this.inBackground(); } @Override public Pathable inBackground(BackgroundCallback callback, Object context) { return GetDataBuilderImpl.this.inBackground(callback, context); } @Override public Pathable inBackground(BackgroundCallback callback, Object context, Executor executor) { return GetDataBuilderImpl.this.inBackground(callback, context, executor); } @Override public Pathable inBackground(Object context) { return GetDataBuilderImpl.this.inBackground(context); } @Override public Pathable inBackground(BackgroundCallback callback) { return GetDataBuilderImpl.this.inBackground(callback); } @Override public Pathable inBackground(BackgroundCallback callback, Executor executor) { return GetDataBuilderImpl.this.inBackground(callback, executor); } @Override public byte[] forPath(String path) throws Exception { return GetDataBuilderImpl.this.forPath(path); } @Override public WatchPathable storingStatIn(Stat stat) { return GetDataBuilderImpl.this.storingStatIn(stat); } @Override public BackgroundPathable watched() { return GetDataBuilderImpl.this.watched(); } @Override public BackgroundPathable usingWatcher(Watcher watcher) { return GetDataBuilderImpl.this.usingWatcher(watcher); } @Override public BackgroundPathable usingWatcher(CuratorWatcher watcher) { return GetDataBuilderImpl.this.usingWatcher(watcher); } }; } @Override public WatchPathable storingStatIn(Stat stat) { this.responseStat = stat; return new WatchPathable() { @Override public byte[] forPath(String path) throws Exception { return GetDataBuilderImpl.this.forPath(path); } @Override public Pathable watched() { GetDataBuilderImpl.this.watched(); return GetDataBuilderImpl.this; } @Override public Pathable usingWatcher(Watcher watcher) { GetDataBuilderImpl.this.usingWatcher(watcher); return GetDataBuilderImpl.this; } @Override public Pathable usingWatcher(CuratorWatcher watcher) { GetDataBuilderImpl.this.usingWatcher(watcher); return GetDataBuilderImpl.this; } }; } @Override public Pathable inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override public Pathable inBackground(BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override public Pathable inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override public Pathable inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(client, callback, executor); return this; } @Override public Pathable inBackground() { backgrounding = new Backgrounding(true); return this; } @Override public Pathable inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override public BackgroundPathable watched() { watching = new Watching(true); return this; } @Override public BackgroundPathable usingWatcher(Watcher watcher) { watching = new Watching(client, watcher); return this; } @Override public BackgroundPathable usingWatcher(CuratorWatcher watcher) { watching = new Watching(client, watcher); return this; } @Override public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { final TimeTrace trace = client.getZookeeperClient().startTracer("GetDataBuilderImpl-Background"); AsyncCallback.DataCallback callback = new AsyncCallback.DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { trace.commit(); if ( decompress && (data != null) ) { try { data = client.getCompressionProvider().decompress(path, data); } catch ( Exception e ) { log.error("Decompressing for path: " + path, e); rc = KeeperException.Code.DATAINCONSISTENCY.intValue(); } } CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.GET_DATA, rc, path, null, ctx, stat, data, null, null, null); client.processBackgroundOperation(operationAndData, event); } }; if ( watching.isWatched() ) { client.getZooKeeper().getData(operationAndData.getData(), true, callback, backgrounding.getContext()); } else { client.getZooKeeper().getData(operationAndData.getData(), watching.getWatcher(), callback, backgrounding.getContext()); } } @Override public byte[] forPath(String path) throws Exception { path = client.fixForNamespace(path); byte[] responseData = null; if ( backgrounding.inBackground() ) { client.processBackgroundOperation(new OperationAndData(this, path, backgrounding.getCallback(), null, backgrounding.getContext()), null); } else { responseData = pathInForeground(path); } return responseData; } private byte[] pathInForeground(final String path) throws Exception { TimeTrace trace = client.getZookeeperClient().startTracer("GetDataBuilderImpl-Foreground"); byte[] responseData = RetryLoop.callWithRetry ( client.getZookeeperClient(), new Callable() { @Override public byte[] call() throws Exception { byte[] responseData; if ( watching.isWatched() ) { responseData = client.getZooKeeper().getData(path, true, responseStat); } else { responseData = client.getZooKeeper().getData(path, watching.getWatcher(), responseStat); } return responseData; } } ); trace.commit(); return decompress ? client.getCompressionProvider().decompress(path, responseData) : responseData; } } GzipCompressionProvider.java000066400000000000000000000041051245521677600403070ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.framework.api.CompressionProvider; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; public class GzipCompressionProvider implements CompressionProvider { @Override public byte[] compress(String path, byte[] data) throws Exception { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); GZIPOutputStream out = new GZIPOutputStream(bytes); out.write(data); out.finish(); return bytes.toByteArray(); } @Override public byte[] decompress(String path, byte[] compressedData) throws Exception { ByteArrayOutputStream bytes = new ByteArrayOutputStream(compressedData.length); GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(compressedData)); byte[] buffer = new byte[compressedData.length]; for(;;) { int bytesRead = in.read(buffer, 0, buffer.length); if ( bytesRead < 0 ) { break; } bytes.write(buffer, 0, bytesRead); } return bytes.toByteArray(); } } NamespaceFacade.java000066400000000000000000000101711245521677600364210ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.CuratorZookeeperClient; import org.apache.curator.RetryLoop; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.*; import org.apache.curator.framework.listen.Listenable; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.utils.EnsurePath; import org.apache.zookeeper.ZooKeeper; class NamespaceFacade extends CuratorFrameworkImpl { private final CuratorFrameworkImpl client; private final NamespaceImpl namespace; private final FailedDeleteManager failedDeleteManager = new FailedDeleteManager(this); NamespaceFacade(CuratorFrameworkImpl client, String namespace) { super(client); this.client = client; this.namespace = new NamespaceImpl(client, namespace); } @Override public CuratorFramework nonNamespaceView() { return usingNamespace(null); } @Override public CuratorFramework usingNamespace(String newNamespace) { return client.getNamespaceFacadeCache().get(newNamespace); } @Override public String getNamespace() { return namespace.getNamespace(); } @Override public void start() { throw new UnsupportedOperationException(); } @Override public void close() { throw new UnsupportedOperationException(); } @Override public Listenable getConnectionStateListenable() { return client.getConnectionStateListenable(); } @Override public Listenable getCuratorListenable() { throw new UnsupportedOperationException("getCuratorListenable() is only available from a non-namespaced CuratorFramework instance"); } @Override public Listenable getUnhandledErrorListenable() { return client.getUnhandledErrorListenable(); } @Override public void sync(String path, Object context) { internalSync(this, path, context); } @Override public CuratorZookeeperClient getZookeeperClient() { return client.getZookeeperClient(); } @Override RetryLoop newRetryLoop() { return client.newRetryLoop(); } @Override ZooKeeper getZooKeeper() throws Exception { return client.getZooKeeper(); } @Override void processBackgroundOperation(OperationAndData operationAndData, CuratorEvent event) { client.processBackgroundOperation(operationAndData, event); } @Override void logError(String reason, Throwable e) { client.logError(reason, e); } @Override String unfixForNamespace(String path) { return namespace.unfixForNamespace(path); } @Override String fixForNamespace(String path) { return namespace.fixForNamespace(path, false); } @Override String fixForNamespace(String path, boolean isSequential) { return namespace.fixForNamespace(path, isSequential); } @Override public EnsurePath newNamespaceAwareEnsurePath(String path) { return namespace.newNamespaceAwareEnsurePath(path); } @Override FailedDeleteManager getFailedDeleteManager() { return failedDeleteManager; } } NamespaceFacadeCache.java000066400000000000000000000042061245521677600373470ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; class NamespaceFacadeCache { private final CuratorFrameworkImpl client; private final NamespaceFacade nullNamespace; private final CacheLoader loader = new CacheLoader() { @Override public NamespaceFacade load(String namespace) throws Exception { return new NamespaceFacade(client, namespace); } }; private final LoadingCache cache = CacheBuilder.newBuilder() .expireAfterAccess(5, TimeUnit.MINUTES) // does this need config? probably not .build(loader); NamespaceFacadeCache(CuratorFrameworkImpl client) { this.client = client; nullNamespace = new NamespaceFacade(client, null); } NamespaceFacade get(String namespace) { try { return (namespace != null) ? cache.get(namespace) : nullNamespace; } catch ( ExecutionException e ) { throw new RuntimeException(e); // should never happen } } } NamespaceImpl.java000066400000000000000000000053231245521677600361620ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.utils.EnsurePath; import org.apache.curator.utils.ZKPaths; import org.apache.curator.utils.PathUtils; class NamespaceImpl { private final CuratorFrameworkImpl client; private final String namespace; private final EnsurePath ensurePath; NamespaceImpl(CuratorFrameworkImpl client, String namespace) { if ( namespace != null ) { try { PathUtils.validatePath("/" + namespace); } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException("Invalid namespace: " + namespace); } } this.client = client; this.namespace = namespace; ensurePath = (namespace != null) ? new EnsurePath(ZKPaths.makePath("/", namespace)) : null; } String getNamespace() { return namespace; } String unfixForNamespace(String path) { if ( (namespace != null) && (path != null) ) { String namespacePath = ZKPaths.makePath(namespace, null); if ( path.startsWith(namespacePath) ) { path = (path.length() > namespacePath.length()) ? path.substring(namespacePath.length()) : "/"; } } return path; } String fixForNamespace(String path, boolean isSequential) { if ( ensurePath != null ) { try { ensurePath.ensure(client.getZookeeperClient()); } catch ( Exception e ) { client.logError("Ensure path threw exception", e); } } return ZKPaths.fixForNamespace(namespace, path, isSequential); } EnsurePath newNamespaceAwareEnsurePath(String path) { return new EnsurePath(fixForNamespace(path, false), client.getAclProvider()); } } NamespaceWatchedEvent.java000066400000000000000000000021511245521677600376360ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.zookeeper.WatchedEvent; class NamespaceWatchedEvent extends WatchedEvent { NamespaceWatchedEvent(CuratorFrameworkImpl client, WatchedEvent event) { super(event.getType(), event.getState(), client.unfixForNamespace(event.getPath())); } } NamespaceWatcher.java000066400000000000000000000045111245521677600366540ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import java.io.Closeable; class NamespaceWatcher implements Watcher, Closeable { private volatile CuratorFrameworkImpl client; private volatile Watcher actualWatcher; private volatile CuratorWatcher curatorWatcher; NamespaceWatcher(CuratorFrameworkImpl client, Watcher actualWatcher) { this.client = client; this.actualWatcher = actualWatcher; this.curatorWatcher = null; } NamespaceWatcher(CuratorFrameworkImpl client, CuratorWatcher curatorWatcher) { this.client = client; this.actualWatcher = null; this.curatorWatcher = curatorWatcher; } @Override public void close() { client = null; actualWatcher = null; curatorWatcher = null; } @Override public void process(WatchedEvent event) { if ( client != null ) { if ( actualWatcher != null ) { actualWatcher.process(new NamespaceWatchedEvent(client, event)); } else if ( curatorWatcher != null ) { try { curatorWatcher.process(new NamespaceWatchedEvent(client, event)); } catch ( Exception e ) { client.logError("Watcher exception", e); } } } } } NamespaceWatcherMap.java000066400000000000000000000057211245521677600373160ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import com.google.common.annotations.VisibleForTesting; import com.google.common.cache.CacheBuilder; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.zookeeper.Watcher; import java.io.Closeable; import java.lang.reflect.Field; import java.util.concurrent.ConcurrentMap; class NamespaceWatcherMap implements Closeable { private final ConcurrentMap map = CacheBuilder.newBuilder() .weakValues() .build() .asMap(); private final CuratorFrameworkImpl client; NamespaceWatcherMap(CuratorFrameworkImpl client) { this.client = client; } @Override public void close() { map.clear(); } @VisibleForTesting void drain() throws Exception { Runtime.getRuntime().gc(); // relies on internals of MapMakerInternalMap (obviously) Class mapMakerInternalMapClass = Class.forName("com.google.common.collect.MapMakerInternalMap"); Field drainThresholdField = mapMakerInternalMapClass.getDeclaredField("DRAIN_THRESHOLD"); drainThresholdField.setAccessible(true); int drainThreshold = drainThresholdField.getInt(null) + 1; while ( drainThreshold-- > 0 ) { map.get(new Object()); } } NamespaceWatcher get(Object key) { return map.get(key); } NamespaceWatcher remove(Object key) { return map.remove(key); } @VisibleForTesting boolean isEmpty() { return map.isEmpty(); } NamespaceWatcher getNamespaceWatcher(Watcher watcher) { return get(watcher, new NamespaceWatcher(client, watcher)); } NamespaceWatcher getNamespaceWatcher(CuratorWatcher watcher) { return get(watcher, new NamespaceWatcher(client, watcher)); } private NamespaceWatcher get(Object watcher, NamespaceWatcher newNamespaceWatcher) { NamespaceWatcher existingNamespaceWatcher = map.putIfAbsent(watcher, newNamespaceWatcher); return (existingNamespaceWatcher != null) ? existingNamespaceWatcher : newNamespaceWatcher; } } OperationAndData.java000066400000000000000000000072551245521677600366270ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import com.google.common.annotations.VisibleForTesting; import org.apache.curator.RetrySleeper; import org.apache.curator.framework.api.BackgroundCallback; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; class OperationAndData implements Delayed, RetrySleeper { private static final AtomicLong nextOrdinal = new AtomicLong(); private final BackgroundOperation operation; private final T data; private final BackgroundCallback callback; private final long startTimeMs = System.currentTimeMillis(); private final ErrorCallback errorCallback; private final AtomicInteger retryCount = new AtomicInteger(0); private final AtomicLong sleepUntilTimeMs = new AtomicLong(0); private final long ordinal = nextOrdinal.getAndIncrement(); private final Object context; interface ErrorCallback { void retriesExhausted(OperationAndData operationAndData); } OperationAndData(BackgroundOperation operation, T data, BackgroundCallback callback, ErrorCallback errorCallback, Object context) { this.operation = operation; this.data = data; this.callback = callback; this.errorCallback = errorCallback; this.context = context; } Object getContext() { return context; } void callPerformBackgroundOperation() throws Exception { operation.performBackgroundOperation(this); } T getData() { return data; } long getElapsedTimeMs() { return System.currentTimeMillis() - startTimeMs; } int getThenIncrementRetryCount() { return retryCount.getAndIncrement(); } BackgroundCallback getCallback() { return callback; } ErrorCallback getErrorCallback() { return errorCallback; } @VisibleForTesting BackgroundOperation getOperation() { return operation; } @Override public void sleepFor(long time, TimeUnit unit) throws InterruptedException { sleepUntilTimeMs.set(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(time, unit)); } @Override public long getDelay(TimeUnit unit) { return unit.convert(sleepUntilTimeMs.get() - System.currentTimeMillis(), TimeUnit.MILLISECONDS); } @Override public int compareTo(Delayed o) { if ( o == this ) { return 0; } long diff = getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS); if ( diff == 0 ) { if ( o instanceof OperationAndData ) { diff = ordinal - ((OperationAndData)o).ordinal; } } return (diff < 0) ? -1 : ((diff > 0) ? 1 : 0); } } PathAndBytes.java000066400000000000000000000022121245521677600357640ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; class PathAndBytes { private final String path; private final byte[] data; PathAndBytes(String path, byte[] data) { this.path = path; this.data = data; } String getPath() { return path; } byte[] getData() { return data; } } SetACLBuilderImpl.java000066400000000000000000000125411245521677600366500ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.RetryLoop; import org.apache.curator.TimeTrace; import org.apache.curator.framework.api.*; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.SetACLBuilder; import org.apache.zookeeper.AsyncCallback; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Executor; class SetACLBuilderImpl implements SetACLBuilder, BackgroundPathable, BackgroundOperation { private final CuratorFrameworkImpl client; private ACLing acling; private Backgrounding backgrounding; private int version; SetACLBuilderImpl(CuratorFrameworkImpl client) { this.client = client; backgrounding = new Backgrounding(); acling = new ACLing(client.getAclProvider()); version = -1; } @Override public BackgroundPathable withACL(List aclList) { acling = new ACLing(client.getAclProvider(), aclList); return this; } @Override public ACLable> withVersion(int version) { this.version = version; return this; } @Override public Pathable inBackground() { backgrounding = new Backgrounding(true); return this; } @Override public Pathable inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override public Pathable inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override public Pathable inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override public Pathable inBackground(BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override public Pathable inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(client, callback, executor); return this; } @Override public Stat forPath(String path) throws Exception { path = client.fixForNamespace(path); Stat resultStat = null; if ( backgrounding.inBackground() ) { client.processBackgroundOperation(new OperationAndData(this, path, backgrounding.getCallback(), null, backgrounding.getContext()), null); } else { resultStat = pathInForeground(path); } return resultStat; } @Override public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { final TimeTrace trace = client.getZookeeperClient().startTracer("SetACLBuilderImpl-Background"); String path = operationAndData.getData(); client.getZooKeeper().setACL ( path, acling.getAclList(path), version, new AsyncCallback.StatCallback() { @SuppressWarnings({"unchecked"}) @Override public void processResult(int rc, String path, Object ctx, Stat stat) { trace.commit(); CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.SET_ACL, rc, path, null, ctx, stat, null, null, null, null); client.processBackgroundOperation(operationAndData, event); } }, backgrounding.getContext() ); } private Stat pathInForeground(final String path) throws Exception { TimeTrace trace = client.getZookeeperClient().startTracer("SetACLBuilderImpl-Foreground"); Stat resultStat = RetryLoop.callWithRetry ( client.getZookeeperClient(), new Callable() { @Override public Stat call() throws Exception { return client.getZooKeeper().setACL(path, acling.getAclList(path), version); } } ); trace.commit(); return resultStat; } } SetDataBuilderImpl.java000066400000000000000000000224641245521677600371270ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.RetryLoop; import org.apache.curator.TimeTrace; import org.apache.curator.framework.api.ACLPathAndBytesable; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.BackgroundPathAndBytesable; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.framework.api.PathAndBytesable; import org.apache.curator.framework.api.SetDataBackgroundVersionable; import org.apache.curator.framework.api.SetDataBuilder; import org.apache.curator.framework.api.transaction.CuratorTransactionBridge; import org.apache.curator.framework.api.transaction.OperationType; import org.apache.curator.framework.api.transaction.TransactionSetDataBuilder; import org.apache.zookeeper.AsyncCallback; import org.apache.zookeeper.Op; import org.apache.zookeeper.data.Stat; import java.util.concurrent.Callable; import java.util.concurrent.Executor; class SetDataBuilderImpl implements SetDataBuilder, BackgroundOperation { private final CuratorFrameworkImpl client; private Backgrounding backgrounding; private int version; private boolean compress; SetDataBuilderImpl(CuratorFrameworkImpl client) { this.client = client; backgrounding = new Backgrounding(); version = -1; compress = false; } TransactionSetDataBuilder asTransactionSetDataBuilder(final CuratorTransactionImpl curatorTransaction, final CuratorMultiTransactionRecord transaction) { return new TransactionSetDataBuilder() { @Override public CuratorTransactionBridge forPath(String path, byte[] data) throws Exception { if ( compress ) { data = client.getCompressionProvider().compress(path, data); } String fixedPath = client.fixForNamespace(path); transaction.add(Op.setData(fixedPath, data, version), OperationType.SET_DATA, path); return curatorTransaction; } @Override public CuratorTransactionBridge forPath(String path) throws Exception { return forPath(path, client.getDefaultData()); } @Override public PathAndBytesable withVersion(int version) { SetDataBuilderImpl.this.withVersion(version); return this; } @Override public PathAndBytesable compressed() { compress = true; return this; } }; } @Override public SetDataBackgroundVersionable compressed() { compress = true; return new SetDataBackgroundVersionable() { @Override public PathAndBytesable inBackground() { return SetDataBuilderImpl.this.inBackground(); } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Object context) { return SetDataBuilderImpl.this.inBackground(callback, context); } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Object context, Executor executor) { return SetDataBuilderImpl.this.inBackground(callback, context, executor); } @Override public PathAndBytesable inBackground(Object context) { return SetDataBuilderImpl.this.inBackground(context); } @Override public PathAndBytesable inBackground(BackgroundCallback callback) { return SetDataBuilderImpl.this.inBackground(callback); } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Executor executor) { return SetDataBuilderImpl.this.inBackground(callback, executor); } @Override public Stat forPath(String path, byte[] data) throws Exception { return SetDataBuilderImpl.this.forPath(path, data); } @Override public Stat forPath(String path) throws Exception { return SetDataBuilderImpl.this.forPath(path); } @Override public BackgroundPathAndBytesable withVersion(int version) { return SetDataBuilderImpl.this.withVersion(version); } }; } @Override public BackgroundPathAndBytesable withVersion(int version) { this.version = version; return this; } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override public PathAndBytesable inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override public PathAndBytesable inBackground() { backgrounding = new Backgrounding(true); return this; } @Override public PathAndBytesable inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override public PathAndBytesable inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(client, callback, executor); return this; } @Override public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { final TimeTrace trace = client.getZookeeperClient().startTracer("SetDataBuilderImpl-Background"); client.getZooKeeper().setData ( operationAndData.getData().getPath(), operationAndData.getData().getData(), version, new AsyncCallback.StatCallback() { @SuppressWarnings({"unchecked"}) @Override public void processResult(int rc, String path, Object ctx, Stat stat) { trace.commit(); CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.SET_DATA, rc, path, null, ctx, stat, null, null, null, null); client.processBackgroundOperation(operationAndData, event); } }, backgrounding.getContext() ); } @Override public Stat forPath(String path) throws Exception { return forPath(path, client.getDefaultData()); } @Override public Stat forPath(String path, byte[] data) throws Exception { if ( compress ) { data = client.getCompressionProvider().compress(path, data); } path = client.fixForNamespace(path); Stat resultStat = null; if ( backgrounding.inBackground() ) { client.processBackgroundOperation(new OperationAndData(this, new PathAndBytes(path, data), backgrounding.getCallback(), null, backgrounding.getContext()), null); } else { resultStat = pathInForeground(path, data); } return resultStat; } int getVersion() { return version; } private Stat pathInForeground(final String path, final byte[] data) throws Exception { TimeTrace trace = client.getZookeeperClient().startTracer("SetDataBuilderImpl-Foreground"); Stat resultStat = RetryLoop.callWithRetry ( client.getZookeeperClient(), new Callable() { @Override public Stat call() throws Exception { return client.getZooKeeper().setData(path, data, version); } } ); trace.commit(); return resultStat; } } SyncBuilderImpl.java000066400000000000000000000075471245521677600365230ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.TimeTrace; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.framework.api.Pathable; import org.apache.curator.framework.api.SyncBuilder; import org.apache.zookeeper.AsyncCallback; import java.util.concurrent.Executor; public class SyncBuilderImpl implements SyncBuilder, BackgroundOperation { private final CuratorFrameworkImpl client; private Backgrounding backgrounding = new Backgrounding(); public SyncBuilderImpl(CuratorFrameworkImpl client) { //To change body of created methods use File | Settings | File Templates. this.client = client; } @Override public Pathable inBackground() { // NOP always in background return this; } @Override public Pathable inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override public Pathable inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override public Pathable inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override public Pathable inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(callback, executor); return this; } @Override public Pathable inBackground(BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { final TimeTrace trace = client.getZookeeperClient().startTracer("SyncBuilderImpl-Background"); final String path = operationAndData.getData(); String adjustedPath = client.fixForNamespace(path); AsyncCallback.VoidCallback voidCallback = new AsyncCallback.VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { trace.commit(); CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.SYNC, rc, path, path, ctx, null, null, null, null, null); client.processBackgroundOperation(operationAndData, event); } }; client.getZooKeeper().sync(adjustedPath, voidCallback, backgrounding.getContext()); } @Override public Void forPath(String path) throws Exception { OperationAndData operationAndData = new OperationAndData(this, path, backgrounding.getCallback(), null, backgrounding.getContext()); client.processBackgroundOperation(operationAndData, null); return null; } } TempGetDataBuilderImpl.java000066400000000000000000000050201245521677600377260ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.RetryLoop; import org.apache.curator.TimeTrace; import org.apache.curator.framework.api.Pathable; import org.apache.curator.framework.api.StatPathable; import org.apache.curator.framework.api.TempGetDataBuilder; import org.apache.zookeeper.data.Stat; import java.util.concurrent.Callable; class TempGetDataBuilderImpl implements TempGetDataBuilder { private final CuratorFrameworkImpl client; private Stat responseStat; private boolean decompress; TempGetDataBuilderImpl(CuratorFrameworkImpl client) { this.client = client; responseStat = null; decompress = false; } @Override public StatPathable decompressed() { decompress = true; return this; } @Override public Pathable storingStatIn(Stat stat) { responseStat = stat; return this; } @Override public byte[] forPath(String path) throws Exception { final String localPath = client.fixForNamespace(path); TimeTrace trace = client.getZookeeperClient().startTracer("GetDataBuilderImpl-Foreground"); byte[] responseData = RetryLoop.callWithRetry ( client.getZookeeperClient(), new Callable() { @Override public byte[] call() throws Exception { return client.getZooKeeper().getData(localPath, false, responseStat); } } ); trace.commit(); return decompress ? client.getCompressionProvider().decompress(path, responseData) : responseData; } } Watching.java000066400000000000000000000033731245521677600352130ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.zookeeper.Watcher; class Watching { private final Watcher watcher; private final boolean watched; Watching(boolean watched) { this.watcher = null; this.watched = watched; } Watching(CuratorFrameworkImpl client, Watcher watcher) { this.watcher = (watcher != null) ? client.getNamespaceWatcherMap().getNamespaceWatcher(watcher) : null; this.watched = false; } Watching(CuratorFrameworkImpl client, CuratorWatcher watcher) { this.watcher = (watcher != null) ? client.getNamespaceWatcherMap().getNamespaceWatcher(watcher) : null; this.watched = false; } Watching() { watcher = null; watched = false; } Watcher getWatcher() { return watcher; } boolean isWatched() { return watched; } } curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/listen/000077500000000000000000000000001245521677600332035ustar00rootroot00000000000000Listenable.java000066400000000000000000000031001245521677600360430ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/listen/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.listen; import java.util.concurrent.Executor; /** * Abstracts a listenable object */ public interface Listenable { /** * Add the given listener. The listener will be executed in the containing * instance's thread. * * @param listener listener to add */ public void addListener(T listener); /** * Add the given listener. The listener will be executed using the given * executor * * @param listener listener to add * @param executor executor to run listener in */ public void addListener(T listener, Executor executor); /** * Remove the given listener * * @param listener listener to remove */ public void removeListener(T listener); } ListenerContainer.java000066400000000000000000000057101245521677600374220ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/listen/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.listen; import com.google.common.base.Function; import com.google.common.collect.Maps; import com.google.common.util.concurrent.MoreExecutors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.concurrent.Executor; /** * Abstracts an object that has listeners */ public class ListenerContainer implements Listenable { private final Logger log = LoggerFactory.getLogger(getClass()); private final Map> listeners = Maps.newConcurrentMap(); @Override public void addListener(T listener) { addListener(listener, MoreExecutors.sameThreadExecutor()); } @Override public void addListener(T listener, Executor executor) { listeners.put(listener, new ListenerEntry(listener, executor)); } @Override public void removeListener(T listener) { listeners.remove(listener); } /** * Remove all listeners */ public void clear() { listeners.clear(); } /** * Return the number of listeners * * @return number */ public int size() { return listeners.size(); } /** * Utility - apply the given function to each listener. The function receives * the listener as an argument. * * @param function function to call for each listener */ public void forEach(final Function function) { for ( final ListenerEntry entry : listeners.values() ) { entry.executor.execute ( new Runnable() { @Override public void run() { try { function.apply(entry.listener); } catch ( Throwable e ) { log.error(String.format("Listener (%s) threw an exception", entry.listener), e); } } } ); } } } ListenerEntry.java000066400000000000000000000023201245521677600365730ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/listen/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.listen; import java.util.concurrent.Executor; /** * Generic holder POJO for a listener and its executor * @param the listener type */ public class ListenerEntry { public final T listener; public final Executor executor; public ListenerEntry(T listener, Executor executor) { this.listener = listener; this.executor = executor; } } curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/state/000077500000000000000000000000001245521677600330255ustar00rootroot00000000000000ConnectionState.java000066400000000000000000000056301245521677600367150ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/state/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.state; import org.apache.curator.framework.CuratorFrameworkFactory; /** * Represents state changes in the connection to ZK */ public enum ConnectionState { /** * Sent for the first successful connection to the server. NOTE: You will only * get one of these messages for any CuratorFramework instance. */ CONNECTED { public boolean isConnected() { return true; } }, /** * There has been a loss of connection. Leaders, locks, etc. should suspend * until the connection is re-established. If the connection times-out you will * receive a {@link #LOST} notice */ SUSPENDED { public boolean isConnected() { return false; } }, /** * A suspended, lost, or read-only connection has been re-established */ RECONNECTED { public boolean isConnected() { return true; } }, /** * The connection is confirmed to be lost. Close any locks, leaders, etc. and * attempt to re-create them. NOTE: it is possible to get a {@link #RECONNECTED} * state after this but you should still consider any locks, etc. as dirty/unstable */ LOST { public boolean isConnected() { return false; } }, /** * The connection has gone into read-only mode. This can only happen if you pass true * for {@link CuratorFrameworkFactory.Builder#canBeReadOnly()}. See the ZooKeeper doc * regarding read only connections: * http://wiki.apache.org/hadoop/ZooKeeper/GSoCReadOnlyMode. * The connection will remain in read only mode until another state change is sent. */ READ_ONLY { public boolean isConnected() { return true; } }; /** * Check if this state indicates that Curator has a connection to ZooKeeper * * @return True if connected, false otherwise */ public abstract boolean isConnected(); } ConnectionStateListener.java000066400000000000000000000022441245521677600404210ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/state/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.state; import org.apache.curator.framework.CuratorFramework; public interface ConnectionStateListener { /** * Called when there is a state change in the connection * * @param client the client * @param newState the new state */ public void stateChanged(CuratorFramework client, ConnectionState newState); } ConnectionStateManager.java000066400000000000000000000201451245521677600402060ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/main/java/org/apache/curator/framework/state/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.state; import com.google.common.base.Function; import com.google.common.base.Preconditions; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.listen.ListenerContainer; import org.apache.curator.utils.ThreadUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * Used internally to manage connection state */ public class ConnectionStateManager implements Closeable { private static final int QUEUE_SIZE; static { int size = 25; String property = System.getProperty("ConnectionStateManagerSize", null); if ( property != null ) { try { size = Integer.parseInt(property); } catch ( NumberFormatException ignore ) { // ignore } } QUEUE_SIZE = size; } private final Logger log = LoggerFactory.getLogger(getClass()); private final BlockingQueue eventQueue = new ArrayBlockingQueue(QUEUE_SIZE); private final CuratorFramework client; private final ListenerContainer listeners = new ListenerContainer(); private final AtomicBoolean initialConnectMessageSent = new AtomicBoolean(false); private final ExecutorService service; private final AtomicReference state = new AtomicReference(State.LATENT); // guarded by sync private ConnectionState currentConnectionState; private enum State { LATENT, STARTED, CLOSED } /** * @param client the client * @param threadFactory thread factory to use or null for a default */ public ConnectionStateManager(CuratorFramework client, ThreadFactory threadFactory) { this.client = client; if ( threadFactory == null ) { threadFactory = ThreadUtils.newThreadFactory("ConnectionStateManager"); } service = Executors.newSingleThreadExecutor(threadFactory); } /** * Start the manager */ public void start() { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); service.submit ( new Callable() { @Override public Object call() throws Exception { processEvents(); return null; } } ); } @Override public void close() { if ( state.compareAndSet(State.STARTED, State.CLOSED) ) { service.shutdownNow(); listeners.clear(); } } /** * Return the listenable * * @return listenable */ public ListenerContainer getListenable() { return listeners; } /** * Change to {@link ConnectionState#SUSPENDED} only if not already suspended and not lost * * @return true if connection is set to SUSPENDED */ public synchronized boolean setToSuspended() { if ( state.get() != State.STARTED ) { return false; } if ( (currentConnectionState == ConnectionState.LOST) || (currentConnectionState == ConnectionState.SUSPENDED) ) { return false; } currentConnectionState = ConnectionState.SUSPENDED; postState(ConnectionState.SUSPENDED); return true; } /** * Post a state change. If the manager is already in that state the change * is ignored. Otherwise the change is queued for listeners. * * @param newConnectionState new state * @return true if the state actually changed, false if it was already at that state */ public synchronized boolean addStateChange(ConnectionState newConnectionState) { if ( state.get() != State.STARTED ) { return false; } ConnectionState previousState = currentConnectionState; if ( previousState == newConnectionState ) { return false; } currentConnectionState = newConnectionState; ConnectionState localState = newConnectionState; boolean isNegativeMessage = ((newConnectionState == ConnectionState.LOST) || (newConnectionState == ConnectionState.SUSPENDED) || (newConnectionState == ConnectionState.READ_ONLY)); if ( !isNegativeMessage && initialConnectMessageSent.compareAndSet(false, true) ) { localState = ConnectionState.CONNECTED; } postState(localState); return true; } public synchronized boolean blockUntilConnected(int maxWaitTime, TimeUnit units) throws InterruptedException { long startTime = System.currentTimeMillis(); boolean hasMaxWait = (units != null); long maxWaitTimeMs = hasMaxWait ? TimeUnit.MILLISECONDS.convert(maxWaitTime, units) : 0; while ( !isConnected() ) { if ( hasMaxWait ) { long waitTime = maxWaitTimeMs - (System.currentTimeMillis() - startTime); if ( waitTime <= 0 ) { return isConnected(); } wait(waitTime); } else { wait(); } } return isConnected(); } public synchronized boolean isConnected() { return (currentConnectionState != null) && currentConnectionState.isConnected(); } private void postState(ConnectionState state) { log.info("State change: " + state); notifyAll(); while ( !eventQueue.offer(state) ) { eventQueue.poll(); log.warn("ConnectionStateManager queue full - dropping events to make room"); } } private void processEvents() { try { while ( !Thread.currentThread().isInterrupted() ) { final ConnectionState newState = eventQueue.take(); if ( listeners.size() == 0 ) { log.warn("There are no ConnectionStateListeners registered."); } listeners.forEach ( new Function() { @Override public Void apply(ConnectionStateListener listener) { listener.stateChanged(client, newState); return null; } } ); } } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } } } curator-apache-curator-2.7.1/curator-framework/src/site/000077500000000000000000000000001245521677600233205ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/site/confluence/000077500000000000000000000000001245521677600254415ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/site/confluence/index.confluence000066400000000000000000000137161245521677600306230ustar00rootroot00000000000000h1. Framework The Curator Framework is a high\-level API that greatly simplifies using ZooKeeper. It adds many features that build on ZooKeeper and handles the complexity of managing connections to the ZooKeeper cluster and retrying operations. Some of the features are: * Automatic connection management: ** There are potential error cases that require ZooKeeper clients to recreate a connection and/or retry operations. Curator automatically and transparently (mostly) handles these cases. * Cleaner API: ** simplifies the raw ZooKeeper methods, events, etc. ** provides a modern, fluent interface * Recipe implementations (see [[Recipes|../curator\-recipes/index.html]]): ** Leader election ** Shared lock ** Path cache and watcher ** Distributed Queue ** Distributed Priority Queue ** ... h2. Allocating a Curator Framework Instance CuratorFrameworks are allocated using the CuratorFrameworkFactory which provides both factory methods and a builder for creating instances. IMPORTANT: CuratorFramework instances are fully thread\-safe. You should share one CuratorFramework per ZooKeeper cluster in your application. The factory methods (newClient()) provide a simplified way of creating an instance. The Builder gives control over all parameters. Once you have a CuratorFramework instance, you must call the start() method. At the end of your application, you should call close(). h2. CuratorFramework API The CuratorFramework uses a Fluent\-style interface. Operations are constructed using builders returned by the CuratorFramework instance. When strung together, the methods form sentence\-like statements. e.g. {code} client.create().forPath("/head", new byte[0]); client.delete().inBackground().forPath("/head"); client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/head/child", new byte[0]); client.getData().watched().inBackground().forPath("/test"); {code} h3. Methods |create()|Begins a create operation. Call additional methods (mode or background) and finalize the operation by calling forPath()| |delete()|Begins a delete operation. Call additional methods (version or background) and finalize the operation by calling forPath()| |checkExists()|Begins an operation to check that a ZNode exists. Call additional methods (watch or background) and finalize the operation by calling forPath()| |getData()|Begins an operation to get a ZNode's data. Call additional methods (watch, background or get stat) and finalize the operation by calling forPath()| |setData()|Begins an operation to set a ZNode's data. Call additional methods (version or background) and finalize the operation by calling forPath()| |getChildren()|Begins an operation to get a ZNode's list of children ZNodes. Call additional methods (watch, background or get stat) and finalize the operation by calling forPath()| |inTransaction()|Begins an atomic ZooKeeper transaction. Combine create, setData, check, and/or delete operations and then commit() as a unit.| h3. Notifications Notifications for background operations and watches are published via the ClientListener interface. You register listeners with the CuratorFramework instance using the addListener() method. The listener implements two methods: |eventReceived()|A background operation has completed or a watch has triggered. Examine the given event for details| clientClosedDueToError()|An unrecoverable error has occurred. The CuratorFramework instance has been shut down| h3. ClientEvent The ClientEvent object is a super\-set POJO that can hold every type of background notification and triggered watch. The useful fields of ClientEvent depend on the type of event which is exposed via the getType() method. ||Event Type||Event Methods|| |CREATE|getResultCode() and getPath()| |DELETE|getResultCode() and getPath()| |EXISTS|getResultCode(), getPath() and getStat()| |GET_DATA|getResultCode(), getPath(), getStat() and getData()| |SET_DATA|getResultCode(), getPath() and getStat()| |CHILDREN|getResultCode(), getPath(), getStat(), getChildren()| |WATCHED|getWatchedEvent()| h2. Namespaces Because a ZooKeeper cluster is a shared environment, it's vital that a namespace convention is observed so that various applications that use a given cluster don't use conflicting ZK paths. The CuratorFramework has a concept of a "namespace". You set the namespace when creating a CuratorFramework instance (via the Builder). The CuratorFramework will then prepend the namespace to all paths when one of its APIs is called. i.e. {code} CuratorFramework client = CuratorFrameworkFactory.builder().namespace("MyApp") ... build(); ... client.create().forPath("/test", data); // node was actually written to: "/MyApp/test" {code} h2. Temporary Connections Temporary CuratorFramework instances are meant for single requests to ZooKeeper ensembles over a failure prone network such as a WAN. The APIs available from CuratorTempFramework are limited. Further, the connection will be closed after a period of inactivity. This is based on an idea mentioned in a post by Camille Fournier: [[http://whilefalse.blogspot.com/2012/12/building-global-highly-available.html]]. h3. Creating a CuratorTempFramework CuratorTempFramework instances are created via the CuratorFrameworkFactory just like normal CuratorFramework instances. However, instead of calling the {{build()}} method, call {{buildTemp()}}. {{buildTemp()}} creates a CuratorTempFramework instance that closes itself after 3 minutes of inactivity. There is an alternate version of {{buildTemp()}} that allows you to specify the inactivity period. h3. Limited API CuratorTempFramework instances provide the following methods: {code} /** * Stop the client */ public void close(); /** * Start a transaction builder * * @return builder object * @throws Exception errors */ public CuratorTransaction inTransaction() throws Exception; /** * Start a get data builder * * @return builder object * @throws Exception errors */ public TempGetDataBuilder getData() throws Exception; {code} curator-apache-curator-2.7.1/curator-framework/src/site/site.xml000066400000000000000000000026321245521677600250110ustar00rootroot00000000000000 curator-apache-curator-2.7.1/curator-framework/src/test/000077500000000000000000000000001245521677600233335ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/000077500000000000000000000000001245521677600242545ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/000077500000000000000000000000001245521677600250435ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/000077500000000000000000000000001245521677600262645ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/000077500000000000000000000000001245521677600277435ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/framework/000077500000000000000000000000001245521677600317405ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/framework/imps/000077500000000000000000000000001245521677600327105ustar00rootroot00000000000000TestBlockUntilConnected.java000066400000000000000000000162621245521677600402340ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.TestingServer; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class TestBlockUntilConnected extends BaseClassForTests { /** * Test the case where we're already connected */ @Test public void testBlockUntilConnectedCurrentlyConnected() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.builder(). connectString(server.getConnectString()). retryPolicy(new RetryOneTime(1)). build(); try { final CountDownLatch connectedLatch = new CountDownLatch(1); client.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState.isConnected() ) { connectedLatch.countDown(); } } }); client.start(); Assert.assertTrue(timing.awaitLatch(connectedLatch), "Timed out awaiting latch"); Assert.assertTrue(client.blockUntilConnected(1, TimeUnit.SECONDS), "Not connected"); } catch ( InterruptedException e ) { Assert.fail("Unexpected interruption"); } finally { CloseableUtils.closeQuietly(client); } } /** * Test the case where we are not currently connected and never have been */ @Test public void testBlockUntilConnectedCurrentlyNeverConnected() { CuratorFramework client = CuratorFrameworkFactory.builder(). connectString(server.getConnectString()). retryPolicy(new RetryOneTime(1)). build(); try { client.start(); Assert.assertTrue(client.blockUntilConnected(5, TimeUnit.SECONDS), "Not connected"); } catch ( InterruptedException e ) { Assert.fail("Unexpected interruption"); } finally { CloseableUtils.closeQuietly(client); } } /** * Test the case where we are not currently connected, but have been previously */ @Test public void testBlockUntilConnectedCurrentlyAwaitingReconnect() { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.builder(). connectString(server.getConnectString()). retryPolicy(new RetryOneTime(1)). build(); final CountDownLatch lostLatch = new CountDownLatch(1); client.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState == ConnectionState.LOST ) { lostLatch.countDown(); } } }); try { client.start(); //Block until we're connected Assert.assertTrue(client.blockUntilConnected(5, TimeUnit.SECONDS), "Failed to connect"); //Kill the server CloseableUtils.closeQuietly(server); //Wait until we hit the lost state Assert.assertTrue(timing.awaitLatch(lostLatch), "Failed to reach LOST state"); server = new TestingServer(server.getPort(), server.getTempDirectory()); Assert.assertTrue(client.blockUntilConnected(5, TimeUnit.SECONDS), "Not connected"); } catch ( Exception e ) { Assert.fail("Unexpected exception " + e); } finally { CloseableUtils.closeQuietly(client); } } /** * Test the case where we are not currently connected and time out before a * connection becomes available. */ @Test public void testBlockUntilConnectedConnectTimeout() { //Kill the server CloseableUtils.closeQuietly(server); CuratorFramework client = CuratorFrameworkFactory.builder(). connectString(server.getConnectString()). retryPolicy(new RetryOneTime(1)). build(); try { client.start(); Assert.assertFalse(client.blockUntilConnected(5, TimeUnit.SECONDS), "Connected"); } catch ( InterruptedException e ) { Assert.fail("Unexpected interruption"); } finally { CloseableUtils.closeQuietly(client); } } /** * Test the case where we are not currently connected and the thread gets interrupted * prior to a connection becoming available */ @Test public void testBlockUntilConnectedInterrupt() { //Kill the server CloseableUtils.closeQuietly(server); final CuratorFramework client = CuratorFrameworkFactory.builder(). connectString(server.getConnectString()). retryPolicy(new RetryOneTime(1)). build(); try { client.start(); final Thread threadToInterrupt = Thread.currentThread(); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { threadToInterrupt.interrupt(); } }, 3000); client.blockUntilConnected(5, TimeUnit.SECONDS); Assert.fail("Expected interruption did not occur"); } catch ( InterruptedException e ) { //This is expected } finally { CloseableUtils.closeQuietly(client); } } } TestCompression.java000066400000000000000000000112051245521677600366340ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.CompressionProvider; import org.apache.curator.retry.RetryOneTime; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.atomic.AtomicInteger; public class TestCompression extends BaseClassForTests { @Test public void testCompressionProvider() throws Exception { final byte[] data = "here's a string".getBytes(); final AtomicInteger compressCounter = new AtomicInteger(); final AtomicInteger decompressCounter = new AtomicInteger(); CompressionProvider compressionProvider = new CompressionProvider() { @Override public byte[] compress(String path, byte[] data) throws Exception { compressCounter.incrementAndGet(); byte[] bytes = new byte[data.length * 2]; System.arraycopy(data, 0, bytes, 0, data.length); System.arraycopy(data, 0, bytes, data.length, data.length); return bytes; } @Override public byte[] decompress(String path, byte[] compressedData) throws Exception { decompressCounter.incrementAndGet(); byte[] bytes = new byte[compressedData.length / 2]; System.arraycopy(compressedData, 0, bytes, 0, bytes.length); return bytes; } }; CuratorFramework client = CuratorFrameworkFactory.builder(). compressionProvider(compressionProvider). connectString(server.getConnectString()). retryPolicy(new RetryOneTime(1)). build(); try { client.start(); client.create().compressed().creatingParentsIfNeeded().forPath("/a/b/c", data); Assert.assertNotEquals(data, client.getData().forPath("/a/b/c")); Assert.assertEquals(data.length, client.getData().decompressed().forPath("/a/b/c").length); } finally { CloseableUtils.closeQuietly(client); } Assert.assertEquals(compressCounter.get(), 1); Assert.assertEquals(decompressCounter.get(), 1); } @Test public void testSetData() throws Exception { final byte[] data = "here's a string".getBytes(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); client.create().creatingParentsIfNeeded().forPath("/a/b/c", data); Assert.assertEquals(data, client.getData().forPath("/a/b/c")); client.setData().compressed().forPath("/a/b/c", data); Assert.assertEquals(data.length, client.getData().decompressed().forPath("/a/b/c").length); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testSimple() throws Exception { final byte[] data = "here's a string".getBytes(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); client.create().compressed().creatingParentsIfNeeded().forPath("/a/b/c", data); Assert.assertNotEquals(data, client.getData().forPath("/a/b/c")); Assert.assertEquals(data.length, client.getData().decompressed().forPath("/a/b/c").length); } finally { CloseableUtils.closeQuietly(client); } } } TestCompressionInTransaction.java000066400000000000000000000134161245521677600413370ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.CompressionProvider; import org.apache.curator.retry.RetryOneTime; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.atomic.AtomicInteger; public class TestCompressionInTransaction extends BaseClassForTests { @Test public void testSetData() throws Exception { final String path = "/a"; final byte[] data = "here's a string".getBytes(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); //Create uncompressed data in a transaction client.inTransaction().create().forPath(path, data).and().commit(); Assert.assertEquals(data, client.getData().forPath(path)); //Create compressed data in transaction client.inTransaction().setData().compressed().forPath(path, data).and().commit(); Assert.assertEquals(data, client.getData().decompressed().forPath(path)); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testSetCompressedAndUncompressed() throws Exception { final String path1 = "/a"; final String path2 = "/b"; final byte[] data1 = "here's a string".getBytes(); final byte[] data2 = "here's another string".getBytes(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); //Create the nodes client.inTransaction().create().compressed().forPath(path1).and(). create().forPath(path2).and().commit(); //Check they exist Assert.assertNotNull(client.checkExists().forPath(path1)); Assert.assertNotNull(client.checkExists().forPath(path2)); //Set the nodes, path1 compressed, path2 uncompressed. client.inTransaction().setData().compressed().forPath(path1, data1).and(). setData().forPath(path2, data2).and().commit(); Assert.assertNotEquals(data1, client.getData().forPath(path1)); Assert.assertEquals(data1, client.getData().decompressed().forPath(path1)); Assert.assertEquals(data2, client.getData().forPath(path2)); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testSimple() throws Exception { final String path1 = "/a"; final String path2 = "/a/b"; final byte[] data1 = "here's a string".getBytes(); final byte[] data2 = "here's another string".getBytes(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); client.inTransaction().create().compressed().forPath(path1, data1).and(). create().compressed().forPath(path2, data2).and().commit(); Assert.assertNotEquals(data1, client.getData().forPath(path1)); Assert.assertEquals(data1, client.getData().decompressed().forPath(path1)); Assert.assertNotEquals(data2, client.getData().forPath(path2)); Assert.assertEquals(data2, client.getData().decompressed().forPath(path2)); } finally { CloseableUtils.closeQuietly(client); } } /** * Test the case where both uncompressed and compressed data is generated in * the same transaction * @throws Exception */ @Test public void testCreateCompressedAndUncompressed() throws Exception { final String path1 = "/a"; final String path2 = "/b"; final byte[] data1 = "here's a string".getBytes(); final byte[] data2 = "here's another string".getBytes(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); client.inTransaction().create().compressed().forPath(path1, data1).and(). create().forPath(path2, data2).and().commit(); Assert.assertNotEquals(data1, client.getData().forPath(path1)); Assert.assertEquals(data1, client.getData().decompressed().forPath(path1)); Assert.assertEquals(data2, client.getData().forPath(path2)); } finally { CloseableUtils.closeQuietly(client); } } } TestFailedDeleteManager.java000066400000000000000000000305571245521677600401500ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.imps.FailedDeleteManager.FailedDeleteManagerListener; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.NoNodeException; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicBoolean; public class TestFailedDeleteManager extends BaseClassForTests { @Test public void testLostSession() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); try { client.start(); client.create().forPath("/test-me"); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( (newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED) ) { semaphore.release(); } else if ( newState == ConnectionState.RECONNECTED ) { latch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); server.stop(); Assert.assertTrue(timing.acquireSemaphore(semaphore)); try { client.delete().guaranteed().forPath("/test-me"); Assert.fail(); } catch ( KeeperException.ConnectionLossException e ) { // expected } Assert.assertTrue(timing.acquireSemaphore(semaphore)); timing.sleepABit(); server.restart(); Assert.assertTrue(timing.awaitLatch(latch)); timing.sleepABit(); Assert.assertNull(client.checkExists().forPath("/test-me")); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testWithNamespaceAndLostSession() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()) .sessionTimeoutMs(timing.session()) .connectionTimeoutMs(timing.connection()) .retryPolicy(new ExponentialBackoffRetry(100, 3)) .namespace("aisa") .build(); try { client.start(); client.create().forPath("/test-me"); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( (newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED) ) { semaphore.release(); } else if ( newState == ConnectionState.RECONNECTED ) { latch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); server.stop(); Assert.assertTrue(timing.acquireSemaphore(semaphore)); try { client.delete().guaranteed().forPath("/test-me"); Assert.fail(); } catch ( KeeperException.ConnectionLossException e ) { // expected } Assert.assertTrue(timing.acquireSemaphore(semaphore)); timing.sleepABit(); server.restart(); Assert.assertTrue(timing.awaitLatch(latch)); timing.sleepABit(); Assert.assertNull(client.checkExists().forPath("/test-me")); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testWithNamespaceAndLostSessionAlt() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()) .sessionTimeoutMs(timing.session()) .connectionTimeoutMs(timing.connection()) .retryPolicy(new ExponentialBackoffRetry(100, 3)) .build(); try { client.start(); CuratorFramework namespaceClient = client.usingNamespace("foo"); namespaceClient.create().forPath("/test-me"); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( (newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED) ) { semaphore.release(); } else if ( newState == ConnectionState.RECONNECTED ) { latch.countDown(); } } }; namespaceClient.getConnectionStateListenable().addListener(listener); server.stop(); Assert.assertTrue(timing.acquireSemaphore(semaphore)); try { namespaceClient.delete().guaranteed().forPath("/test-me"); Assert.fail(); } catch ( KeeperException.ConnectionLossException e ) { // expected } Assert.assertTrue(timing.acquireSemaphore(semaphore)); timing.sleepABit(); server.restart(); Assert.assertTrue(timing.awaitLatch(latch)); timing.sleepABit(); Assert.assertNull(namespaceClient.checkExists().forPath("/test-me")); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testBasic() throws Exception { final String PATH = "/one/two/three"; Timing timing = new Timing(); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).connectionTimeoutMs(timing.connection()).sessionTimeoutMs(timing.session()); CuratorFrameworkImpl client = new CuratorFrameworkImpl(builder); client.start(); try { client.create().creatingParentsIfNeeded().forPath(PATH); Assert.assertNotNull(client.checkExists().forPath(PATH)); server.stop(); // cause the next delete to fail try { client.delete().forPath(PATH); Assert.fail(); } catch ( KeeperException.ConnectionLossException e ) { // expected } server.restart(); Assert.assertNotNull(client.checkExists().forPath(PATH)); server.stop(); // cause the next delete to fail try { client.delete().guaranteed().forPath(PATH); Assert.fail(); } catch ( KeeperException.ConnectionLossException e ) { // expected } server.restart(); final int TRIES = 5; for ( int i = 0; i < TRIES; ++i ) { if ( client.checkExists().forPath(PATH) != null ) { timing.sleepABit(); } } Assert.assertNull(client.checkExists().forPath(PATH)); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testGuaranteedDeleteOnNonExistentNodeInForeground() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); final AtomicBoolean pathAdded = new AtomicBoolean(false); ((CuratorFrameworkImpl)client).getFailedDeleteManager().debugListener = new FailedDeleteManagerListener() { @Override public void pathAddedForDelete(String path) { pathAdded.set(true); } }; try { client.delete().guaranteed().forPath("/nonexistent"); Assert.fail(); } catch(NoNodeException e) { //Exception is expected, the delete should not be retried Assert.assertFalse(pathAdded.get()); } finally { client.close(); } } @Test public void testGuaranteedDeleteOnNonExistentNodeInBackground() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); final AtomicBoolean pathAdded = new AtomicBoolean(false); ((CuratorFrameworkImpl)client).getFailedDeleteManager().debugListener = new FailedDeleteManagerListener() { @Override public void pathAddedForDelete(String path) { pathAdded.set(true); } }; final CountDownLatch backgroundLatch = new CountDownLatch(1); BackgroundCallback background = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { backgroundLatch.countDown(); } }; try { client.delete().guaranteed().inBackground(background).forPath("/nonexistent"); backgroundLatch.await(); //Exception is expected, the delete should not be retried Assert.assertFalse(pathAdded.get()); } finally { client.close(); } } } TestFramework.java000066400000000000000000001003761245521677600363000ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import com.google.common.collect.Lists; import org.apache.curator.framework.AuthInfo; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.framework.api.CuratorListener; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.utils.EnsurePath; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; import org.testng.Assert; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; @SuppressWarnings("deprecation") public class TestFramework extends BaseClassForTests { @Test public void testConnectionState() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { final BlockingQueue queue = new LinkedBlockingQueue(); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { queue.add(newState); } }; client.getConnectionStateListenable().addListener(listener); client.start(); Assert.assertEquals(queue.poll(timing.multiple(4).seconds(), TimeUnit.SECONDS), ConnectionState.CONNECTED); server.stop(); Assert.assertEquals(queue.poll(timing.multiple(4).seconds(), TimeUnit.SECONDS), ConnectionState.SUSPENDED); Assert.assertEquals(queue.poll(timing.multiple(4).seconds(), TimeUnit.SECONDS), ConnectionState.LOST); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testNamespaceWithWatcher() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build(); client.start(); try { final BlockingQueue queue = new LinkedBlockingQueue(); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { try { queue.put(event.getPath()); } catch ( InterruptedException e ) { throw new Error(e); } } }; client.create().forPath("/base"); client.getChildren().usingWatcher(watcher).forPath("/base"); client.create().forPath("/base/child"); String path = queue.take(); Assert.assertEquals(path, "/base"); } finally { client.close(); } } @Test public void testNamespaceInBackground() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build(); client.start(); try { final BlockingQueue queue = new LinkedBlockingQueue(); CuratorListener listener = new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getType() == CuratorEventType.EXISTS ) { queue.put(event.getPath()); } } }; client.getCuratorListenable().addListener(listener); client.create().forPath("/base"); client.checkExists().inBackground().forPath("/base"); String path = queue.poll(10, TimeUnit.SECONDS); Assert.assertEquals(path, "/base"); client.getCuratorListenable().removeListener(listener); BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { queue.put(event.getPath()); } }; client.getChildren().inBackground(callback).forPath("/base"); path = queue.poll(10, TimeUnit.SECONDS); Assert.assertEquals(path, "/base"); } finally { client.close(); } } @Test public void testCreateACLSingleAuth() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder .connectString(server.getConnectString()) .authorization("digest", "me1:pass1".getBytes()) .retryPolicy(new RetryOneTime(1)) .build(); client.start(); try { ACL acl = new ACL(ZooDefs.Perms.WRITE, ZooDefs.Ids.AUTH_IDS); List aclList = Lists.newArrayList(acl); client.create().withACL(aclList).forPath("/test", "test".getBytes()); client.close(); // Try setting data with me1:pass1 client = builder .connectString(server.getConnectString()) .authorization("digest", "me1:pass1".getBytes()) .retryPolicy(new RetryOneTime(1)) .build(); client.start(); try { client.setData().forPath("/test", "test".getBytes()); } catch ( KeeperException.NoAuthException e ) { Assert.fail("Auth failed"); } client.close(); // Try setting data with something:else client = builder .connectString(server.getConnectString()) .authorization("digest", "something:else".getBytes()) .retryPolicy(new RetryOneTime(1)) .build(); client.start(); try { client.setData().forPath("/test", "test".getBytes()); Assert.fail("Should have failed with auth exception"); } catch ( KeeperException.NoAuthException e ) { // expected } } finally { client.close(); } } @Test public void testACLDeprecatedApis() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder() .connectString(server.getConnectString()) .retryPolicy(new RetryOneTime(1)); Assert.assertNull(builder.getAuthScheme()); Assert.assertNull(builder.getAuthValue()); builder = builder.authorization("digest", "me1:pass1".getBytes()); Assert.assertEquals(builder.getAuthScheme(), "digest"); Assert.assertEquals(builder.getAuthValue(), "me1:pass1".getBytes()); } @Test public void testCreateACLMultipleAuths() throws Exception { // Add a few authInfos List authInfos = new ArrayList(); authInfos.add(new AuthInfo("digest", "me1:pass1".getBytes())); authInfos.add(new AuthInfo("digest", "me2:pass2".getBytes())); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder .connectString(server.getConnectString()) .authorization(authInfos) .retryPolicy(new RetryOneTime(1)) .build(); client.start(); try { ACL acl = new ACL(ZooDefs.Perms.WRITE, ZooDefs.Ids.AUTH_IDS); List aclList = Lists.newArrayList(acl); client.create().withACL(aclList).forPath("/test", "test".getBytes()); client.close(); // Try setting data with me1:pass1 client = builder .connectString(server.getConnectString()) .authorization("digest", "me1:pass1".getBytes()) .retryPolicy(new RetryOneTime(1)) .build(); client.start(); try { client.setData().forPath("/test", "test".getBytes()); } catch ( KeeperException.NoAuthException e ) { Assert.fail("Auth failed"); } client.close(); // Try setting data with me1:pass1 client = builder .connectString(server.getConnectString()) .authorization("digest", "me2:pass2".getBytes()) .retryPolicy(new RetryOneTime(1)) .build(); client.start(); try { client.setData().forPath("/test", "test".getBytes()); } catch ( KeeperException.NoAuthException e ) { Assert.fail("Auth failed"); } client.close(); // Try setting data with something:else client = builder .connectString(server.getConnectString()) .authorization("digest", "something:else".getBytes()) .retryPolicy(new RetryOneTime(1)) .build(); client.start(); try { client.setData().forPath("/test", "test".getBytes()); Assert.fail("Should have failed with auth exception"); } catch ( KeeperException.NoAuthException e ) { // expected } } finally { client.close(); } } @Test public void testCreateACLWithReset() throws Exception { Timing timing = new Timing(); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder .connectString(server.getConnectString()) .sessionTimeoutMs(timing.session()) .connectionTimeoutMs(timing.connection()) .authorization("digest", "me:pass".getBytes()) .retryPolicy(new RetryOneTime(1)) .build(); client.start(); try { final CountDownLatch lostLatch = new CountDownLatch(1); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState == ConnectionState.LOST ) { lostLatch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); ACL acl = new ACL(ZooDefs.Perms.WRITE, ZooDefs.Ids.AUTH_IDS); List aclList = Lists.newArrayList(acl); client.create().withACL(aclList).forPath("/test", "test".getBytes()); server.stop(); Assert.assertTrue(timing.awaitLatch(lostLatch)); try { client.checkExists().forPath("/"); Assert.fail("Connection should be down"); } catch ( KeeperException.ConnectionLossException e ) { // expected } server.restart(); try { client.setData().forPath("/test", "test".getBytes()); } catch ( KeeperException.NoAuthException e ) { Assert.fail("Auth failed"); } } finally { CloseableUtils.closeQuietly(client); } } @Test public void testCreateParents() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build(); client.start(); try { client.create().creatingParentsIfNeeded().forPath("/one/two/three", "foo".getBytes()); byte[] data = client.getData().forPath("/one/two/three"); Assert.assertEquals(data, "foo".getBytes()); client.create().creatingParentsIfNeeded().forPath("/one/two/another", "bar".getBytes()); data = client.getData().forPath("/one/two/another"); Assert.assertEquals(data, "bar".getBytes()); } finally { client.close(); } } @Test public void testEnsurePathWithNamespace() throws Exception { final String namespace = "jz"; CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace(namespace).build(); client.start(); try { EnsurePath ensurePath = new EnsurePath("/pity/the/fool"); ensurePath.ensure(client.getZookeeperClient()); Assert.assertNull(client.getZookeeperClient().getZooKeeper().exists("/jz/pity/the/fool", false)); ensurePath = client.newNamespaceAwareEnsurePath("/pity/the/fool"); ensurePath.ensure(client.getZookeeperClient()); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/jz/pity/the/fool", false)); } finally { client.close(); } } @Test public void testNamespace() throws Exception { final String namespace = "TestNamespace"; CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace(namespace).build(); client.start(); try { String actualPath = client.create().forPath("/test"); Assert.assertEquals(actualPath, "/test"); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/" + namespace + "/test", false)); Assert.assertNull(client.getZookeeperClient().getZooKeeper().exists("/test", false)); actualPath = client.usingNamespace(null).create().forPath("/non"); Assert.assertEquals(actualPath, "/non"); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/non", false)); client.create().forPath("/test/child", "hey".getBytes()); byte[] bytes = client.getData().forPath("/test/child"); Assert.assertEquals(bytes, "hey".getBytes()); bytes = client.usingNamespace(null).getData().forPath("/" + namespace + "/test/child"); Assert.assertEquals(bytes, "hey".getBytes()); } finally { client.close(); } } @Test public void testCustomCallback() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { final CountDownLatch latch = new CountDownLatch(1); BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getType() == CuratorEventType.CREATE ) { if ( event.getPath().equals("/head") ) { latch.countDown(); } } } }; client.create().inBackground(callback).forPath("/head"); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); } finally { client.close(); } } @Test public void testSync() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.getCuratorListenable().addListener ( new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getType() == CuratorEventType.SYNC ) { Assert.assertEquals(event.getPath(), "/head"); ((CountDownLatch)event.getContext()).countDown(); } } } ); client.create().forPath("/head"); Assert.assertNotNull(client.checkExists().forPath("/head")); CountDownLatch latch = new CountDownLatch(1); client.sync("/head", latch); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); } finally { client.close(); } } @Test public void testSyncNew() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/head"); Assert.assertNotNull(client.checkExists().forPath("/head")); final CountDownLatch latch = new CountDownLatch(1); BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getType() == CuratorEventType.SYNC ) { latch.countDown(); } } }; client.sync().inBackground(callback).forPath("/head"); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); } finally { client.close(); } } @Test public void testBackgroundDelete() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.getCuratorListenable().addListener ( new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getType() == CuratorEventType.DELETE ) { Assert.assertEquals(event.getPath(), "/head"); ((CountDownLatch)event.getContext()).countDown(); } } } ); client.create().forPath("/head"); Assert.assertNotNull(client.checkExists().forPath("/head")); CountDownLatch latch = new CountDownLatch(1); client.delete().inBackground(latch).forPath("/head"); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); Assert.assertNull(client.checkExists().forPath("/head")); } finally { client.close(); } } @Test public void testBackgroundDeleteWithChildren() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.getCuratorListenable().addListener ( new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getType() == CuratorEventType.DELETE ) { Assert.assertEquals(event.getPath(), "/one/two"); ((CountDownLatch)event.getContext()).countDown(); } } } ); client.create().creatingParentsIfNeeded().forPath("/one/two/three/four"); Assert.assertNotNull(client.checkExists().forPath("/one/two/three/four")); CountDownLatch latch = new CountDownLatch(1); client.delete().deletingChildrenIfNeeded().inBackground(latch).forPath("/one/two"); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); Assert.assertNull(client.checkExists().forPath("/one/two")); } finally { client.close(); } } @Test public void testDelete() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/head"); Assert.assertNotNull(client.checkExists().forPath("/head")); client.delete().forPath("/head"); Assert.assertNull(client.checkExists().forPath("/head")); } finally { client.close(); } } @Test public void testDeleteWithChildren() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build(); client.start(); try { client.create().creatingParentsIfNeeded().forPath("/one/two/three/four/five/six", "foo".getBytes()); client.delete().deletingChildrenIfNeeded().forPath("/one/two/three/four/five"); Assert.assertNull(client.checkExists().forPath("/one/two/three/four/five")); client.delete().deletingChildrenIfNeeded().forPath("/one/two"); Assert.assertNull(client.checkExists().forPath("/one/two")); } finally { client.close(); } } @Test public void testDeleteGuaranteedWithChildren() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build(); client.start(); try { client.create().creatingParentsIfNeeded().forPath("/one/two/three/four/five/six", "foo".getBytes()); client.delete().guaranteed().deletingChildrenIfNeeded().forPath("/one/two/three/four/five"); Assert.assertNull(client.checkExists().forPath("/one/two/three/four/five")); client.delete().guaranteed().deletingChildrenIfNeeded().forPath("/one/two"); Assert.assertNull(client.checkExists().forPath("/one/two")); } finally { client.close(); } } @Test public void testGetSequentialChildren() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/head"); for ( int i = 0; i < 10; ++i ) { client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/head/child"); } List children = client.getChildren().forPath("/head"); Assert.assertEquals(children.size(), 10); } finally { client.close(); } } @Test public void testBackgroundGetDataWithWatch() throws Exception { final byte[] data1 = {1, 2, 3}; final byte[] data2 = {4, 5, 6, 7}; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { final CountDownLatch watchedLatch = new CountDownLatch(1); client.getCuratorListenable().addListener ( new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getType() == CuratorEventType.GET_DATA ) { Assert.assertEquals(event.getPath(), "/test"); Assert.assertEquals(event.getData(), data1); ((CountDownLatch)event.getContext()).countDown(); } else if ( event.getType() == CuratorEventType.WATCHED ) { if ( event.getWatchedEvent().getType() == Watcher.Event.EventType.NodeDataChanged ) { Assert.assertEquals(event.getPath(), "/test"); watchedLatch.countDown(); } } } } ); client.create().forPath("/test", data1); CountDownLatch backgroundLatch = new CountDownLatch(1); client.getData().watched().inBackground(backgroundLatch).forPath("/test"); Assert.assertTrue(backgroundLatch.await(10, TimeUnit.SECONDS)); client.setData().forPath("/test", data2); Assert.assertTrue(watchedLatch.await(10, TimeUnit.SECONDS)); byte[] checkData = client.getData().forPath("/test"); Assert.assertEquals(checkData, data2); } finally { client.close(); } } @Test public void testBackgroundCreate() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.getCuratorListenable().addListener ( new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getType() == CuratorEventType.CREATE ) { Assert.assertEquals(event.getPath(), "/test"); ((CountDownLatch)event.getContext()).countDown(); } } } ); CountDownLatch latch = new CountDownLatch(1); client.create().inBackground(latch).forPath("/test", new byte[]{1, 2, 3}); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); } finally { client.close(); } } @Test public void testCreateModes() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { byte[] writtenBytes = {1, 2, 3}; client.create().forPath("/test", writtenBytes); // should be persistent client.close(); client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); byte[] readBytes = client.getData().forPath("/test"); Assert.assertEquals(writtenBytes, readBytes); client.create().withMode(CreateMode.EPHEMERAL).forPath("/ghost", writtenBytes); client.close(); client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); readBytes = client.getData().forPath("/test"); Assert.assertEquals(writtenBytes, readBytes); Stat stat = client.checkExists().forPath("/ghost"); Assert.assertNull(stat); String realPath = client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/pseq", writtenBytes); Assert.assertNotSame(realPath, "/pseq"); client.close(); client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); readBytes = client.getData().forPath(realPath); Assert.assertEquals(writtenBytes, readBytes); realPath = client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/eseq", writtenBytes); Assert.assertNotSame(realPath, "/eseq"); client.close(); client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); stat = client.checkExists().forPath(realPath); Assert.assertNull(stat); } finally { client.close(); } } @Test public void testSimple() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { String path = client.create().withMode(CreateMode.PERSISTENT).forPath("/test", new byte[]{1, 2, 3}); Assert.assertEquals(path, "/test"); } finally { client.close(); } } @Test public void testSequentialWithTrailingSeparator() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/test"); //This should create a node in the form of "/test/00000001" String path = client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/test/"); Assert.assertTrue(path.startsWith("/test/")); } finally { client.close(); } } } TestFrameworkBackground.java000066400000000000000000000251151245521677600402750ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import com.google.common.collect.Lists; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.UnhandledErrorListener; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryNTimes; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.TestingServer; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.apache.zookeeper.KeeperException.Code; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; public class TestFrameworkBackground extends BaseClassForTests { @Test public void testListenerConnectedAtStart() throws Exception { server.close(); Timing timing = new Timing(2); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryNTimes(0, 0)); try { client.start(); final CountDownLatch connectedLatch = new CountDownLatch(1); final AtomicBoolean firstListenerAction = new AtomicBoolean(true); final AtomicReference firstListenerState = new AtomicReference(); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( firstListenerAction.compareAndSet(true, false) ) { firstListenerState.set(newState); System.out.println("First listener state is " + newState); } if ( newState == ConnectionState.CONNECTED ) { connectedLatch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); // due to CURATOR-72, this was causing a LOST event to precede the CONNECTED event client.create().inBackground().forPath("/foo"); server = new TestingServer(server.getPort()); Assert.assertTrue(timing.awaitLatch(connectedLatch)); Assert.assertFalse(firstListenerAction.get()); ConnectionState firstconnectionState = firstListenerState.get(); Assert.assertEquals(firstconnectionState, ConnectionState.CONNECTED, "First listener state MUST BE CONNECTED but is " + firstconnectionState); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testRetries() throws Exception { final int SLEEP = 1000; final int TIMES = 5; Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryNTimes(TIMES, SLEEP)); try { client.start(); client.getZookeeperClient().blockUntilConnectedOrTimedOut(); final CountDownLatch latch = new CountDownLatch(TIMES); final List times = Lists.newArrayList(); final AtomicLong start = new AtomicLong(System.currentTimeMillis()); ((CuratorFrameworkImpl)client).debugListener = new CuratorFrameworkImpl.DebugBackgroundListener() { @Override public void listen(OperationAndData data) { if ( data.getOperation().getClass().getName().contains("CreateBuilderImpl") ) { long now = System.currentTimeMillis(); times.add(now - start.get()); start.set(now); latch.countDown(); } } }; server.stop(); client.create().inBackground().forPath("/one"); latch.await(); for ( long elapsed : times.subList(1, times.size()) ) // first one isn't a retry { Assert.assertTrue(elapsed >= SLEEP, elapsed + ": " + times); } } finally { CloseableUtils.closeQuietly(client); } } @Test public void testBasic() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); final CountDownLatch latch = new CountDownLatch(3); final List paths = Lists.newArrayList(); BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { paths.add(event.getPath()); latch.countDown(); } }; client.create().inBackground(callback).forPath("/one"); client.create().inBackground(callback).forPath("/one/two"); client.create().inBackground(callback).forPath("/one/two/three"); latch.await(); Assert.assertEquals(paths, Arrays.asList("/one", "/one/two", "/one/two/three")); } finally { CloseableUtils.closeQuietly(client); } } /** * Attempt a background operation while Zookeeper server is down. * Return code must be {@link Code#CONNECTIONLOSS} */ @Test public void testCuratorCallbackOnError() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection()).retryPolicy(new RetryOneTime(1000)).build(); final CountDownLatch latch = new CountDownLatch(1); try { client.start(); BackgroundCallback curatorCallback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getResultCode() == Code.CONNECTIONLOSS.intValue() ) { latch.countDown(); } } }; // Stop the Zookeeper server server.stop(); // Attempt to retrieve children list client.getChildren().inBackground(curatorCallback).forPath("/"); // Check if the callback has been called with a correct return code Assert.assertTrue(timing.awaitLatch(latch), "Callback has not been called by curator !"); } finally { client.close(); } } /** * CURATOR-126 * Shutdown the Curator client while there are still background operations running. */ @Test public void testShutdown() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory .builder() .connectString(server.getConnectString()) .sessionTimeoutMs(timing.session()) .connectionTimeoutMs(timing.connection()).retryPolicy(new RetryOneTime(1)) .maxCloseWaitMs(timing.forWaiting().milliseconds()) .build(); try { final AtomicBoolean hadIllegalStateException = new AtomicBoolean(false); ((CuratorFrameworkImpl)client).debugUnhandledErrorListener = new UnhandledErrorListener() { @Override public void unhandledError(String message, Throwable e) { if ( e instanceof IllegalStateException ) { hadIllegalStateException.set(true); } } }; client.start(); final CountDownLatch operationReadyLatch = new CountDownLatch(1); ((CuratorFrameworkImpl)client).debugListener = new CuratorFrameworkImpl.DebugBackgroundListener() { @Override public void listen(OperationAndData data) { try { operationReadyLatch.await(); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } } }; // queue a background operation that will block due to the debugListener client.create().inBackground().forPath("/hey"); timing.sleepABit(); // close the client while the background is still blocked client.close(); // unblock the background operationReadyLatch.countDown(); timing.sleepABit(); // should not generate an exception Assert.assertFalse(hadIllegalStateException.get()); } finally { CloseableUtils.closeQuietly(client); } } } TestFrameworkEdges.java000066400000000000000000000362721245521677600372530ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import com.google.common.collect.Queues; import org.apache.curator.RetryPolicy; import org.apache.curator.RetrySleeper; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.framework.api.CuratorListener; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.KillSession; import org.apache.curator.test.TestingServer; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.data.Stat; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public class TestFrameworkEdges extends BaseClassForTests { private final Timing timing = new Timing(); @Test public void connectionLossWithBackgroundTest() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), 1, new RetryOneTime(1)); try { final CountDownLatch latch = new CountDownLatch(1); client.start(); client.getZookeeperClient().blockUntilConnectedOrTimedOut(); server.close(); client.getChildren().inBackground ( new BackgroundCallback() { public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { latch.countDown(); } } ).forPath("/"); Assert.assertTrue(timing.awaitLatch(latch)); } finally { client.close(); } } @Test public void testReconnectAfterLoss() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); final CountDownLatch lostLatch = new CountDownLatch(1); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState == ConnectionState.LOST ) { lostLatch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); client.checkExists().forPath("/"); server.close(); Assert.assertTrue(timing.awaitLatch(lostLatch)); try { client.checkExists().forPath("/"); Assert.fail(); } catch ( KeeperException.ConnectionLossException e ) { // correct } server = new TestingServer(server.getPort()); client.checkExists().forPath("/"); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testGetAclNoStat() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { try { client.getACL().forPath("/"); } catch ( NullPointerException e ) { Assert.fail(); } } finally { CloseableUtils.closeQuietly(client); } } @Test public void testMissedResponseOnBackgroundESCreate() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { CreateBuilderImpl createBuilder = (CreateBuilderImpl)client.create(); createBuilder.failNextCreateForTesting = true; final BlockingQueue queue = Queues.newArrayBlockingQueue(1); BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { queue.put(event.getPath()); } }; createBuilder.withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).inBackground(callback).forPath("/"); String ourPath = queue.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS); Assert.assertTrue(ourPath.startsWith(ZKPaths.makePath("/", CreateBuilderImpl.PROTECTED_PREFIX))); Assert.assertFalse(createBuilder.failNextCreateForTesting); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testMissedResponseOnESCreate() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { CreateBuilderImpl createBuilder = (CreateBuilderImpl)client.create(); createBuilder.failNextCreateForTesting = true; String ourPath = createBuilder.withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/"); Assert.assertTrue(ourPath.startsWith(ZKPaths.makePath("/", CreateBuilderImpl.PROTECTED_PREFIX))); Assert.assertFalse(createBuilder.failNextCreateForTesting); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testSessionKilled() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/sessionTest"); final AtomicBoolean sessionDied = new AtomicBoolean(false); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { if ( event.getState() == Event.KeeperState.Expired ) { sessionDied.set(true); } } }; client.checkExists().usingWatcher(watcher).forPath("/sessionTest"); KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString()); Assert.assertNotNull(client.checkExists().forPath("/sessionTest")); Assert.assertTrue(sessionDied.get()); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testNestedCalls() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { client.getCuratorListenable().addListener ( new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getType() == CuratorEventType.EXISTS ) { Stat stat = client.checkExists().forPath("/yo/yo/yo"); Assert.assertNull(stat); client.create().inBackground(event.getContext()).forPath("/what"); } else if ( event.getType() == CuratorEventType.CREATE ) { ((CountDownLatch)event.getContext()).countDown(); } } } ); CountDownLatch latch = new CountDownLatch(1); client.checkExists().inBackground(latch).forPath("/hey"); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testBackgroundFailure() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { final CountDownLatch latch = new CountDownLatch(1); client.getConnectionStateListenable().addListener ( new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState == ConnectionState.LOST ) { latch.countDown(); } } } ); client.checkExists().forPath("/hey"); client.checkExists().inBackground().forPath("/hey"); server.stop(); client.checkExists().inBackground().forPath("/hey"); Assert.assertTrue(timing.awaitLatch(latch)); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testFailure() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), 100, 100, new RetryOneTime(1)); client.start(); try { client.checkExists().forPath("/hey"); client.checkExists().inBackground().forPath("/hey"); server.stop(); client.checkExists().forPath("/hey"); Assert.fail(); } catch ( KeeperException.ConnectionLossException e ) { // correct } finally { CloseableUtils.closeQuietly(client); } } @Test public void testRetry() throws Exception { final int MAX_RETRIES = 3; final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(10)); client.start(); try { final AtomicInteger retries = new AtomicInteger(0); final Semaphore semaphore = new Semaphore(0); RetryPolicy policy = new RetryPolicy() { @Override public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) { semaphore.release(); if ( retries.incrementAndGet() == MAX_RETRIES ) { try { server.restart(); } catch ( Exception e ) { throw new Error(e); } } try { sleeper.sleepFor(100, TimeUnit.MILLISECONDS); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } return true; } }; client.getZookeeperClient().setRetryPolicy(policy); server.stop(); // test foreground retry client.checkExists().forPath("/hey"); Assert.assertTrue(semaphore.tryAcquire(MAX_RETRIES, timing.forWaiting().seconds(), TimeUnit.SECONDS), "Remaining leases: " + semaphore.availablePermits()); // make sure we're reconnected client.getZookeeperClient().setRetryPolicy(new RetryOneTime(100)); client.checkExists().forPath("/hey"); client.getZookeeperClient().setRetryPolicy(policy); semaphore.drainPermits(); retries.set(0); server.stop(); // test background retry client.checkExists().inBackground().forPath("/hey"); Assert.assertTrue(semaphore.tryAcquire(MAX_RETRIES, timing.forWaiting().seconds(), TimeUnit.SECONDS), "Remaining leases: " + semaphore.availablePermits()); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testNotStarted() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.getData(); Assert.fail(); } catch ( Exception e ) { // correct } catch ( Throwable e ) { Assert.fail("", e); } } @Test public void testStopped() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); client.getData(); } finally { CloseableUtils.closeQuietly(client); } try { client.getData(); Assert.fail(); } catch ( Exception e ) { // correct } } } TestMultiClient.java000066400000000000000000000073421245521677600365730ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.framework.api.CuratorListener; import org.apache.curator.retry.RetryOneTime; import org.apache.zookeeper.Watcher; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class TestMultiClient extends BaseClassForTests { @Test public void testNotify() throws Exception { CuratorFramework client1 = null; CuratorFramework client2 = null; try { client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client1.start(); client2.start(); final CountDownLatch latch = new CountDownLatch(1); client1.getCuratorListenable().addListener ( new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getType() == CuratorEventType.WATCHED ) { if ( event.getWatchedEvent().getType() == Watcher.Event.EventType.NodeDataChanged ) { if ( event.getPath().equals("/test") ) { latch.countDown(); } } } } } ); client1.create().forPath("/test", new byte[]{1, 2, 3}); client1.checkExists().watched().forPath("/test"); client2.getCuratorListenable().addListener ( new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getType() == CuratorEventType.SYNC ) { client.setData().forPath("/test", new byte[]{10, 20}); } } } ); client2.sync().forPath("/test"); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); } finally { CloseableUtils.closeQuietly(client1); CloseableUtils.closeQuietly(client2); } } } TestNamespaceFacade.java000066400000000000000000000205251245521677600373200ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import java.util.Collections; import java.util.List; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.retry.RetryOneTime; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.KeeperException.NoAuthException; import org.apache.zookeeper.data.ACL; import org.testng.Assert; import org.testng.annotations.Test; public class TestNamespaceFacade extends BaseClassForTests { @Test public void testInvalid() throws Exception { try { CuratorFrameworkFactory.builder().namespace("/snafu").retryPolicy(new RetryOneTime(1)).connectString("").build(); Assert.fail(); } catch ( IllegalArgumentException e ) { // correct } } @Test public void testGetNamespace() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); CuratorFramework client2 = CuratorFrameworkFactory.builder().namespace("snafu").retryPolicy(new RetryOneTime(1)).connectString("").build(); try { client.start(); CuratorFramework fooClient = client.usingNamespace("foo"); CuratorFramework barClient = client.usingNamespace("bar"); Assert.assertEquals(client.getNamespace(), ""); Assert.assertEquals(client2.getNamespace(), "snafu"); Assert.assertEquals(fooClient.getNamespace(), "foo"); Assert.assertEquals(barClient.getNamespace(), "bar"); } finally { CloseableUtils.closeQuietly(client2); CloseableUtils.closeQuietly(client); } } @Test public void testSimultaneous() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); CuratorFramework fooClient = client.usingNamespace("foo"); CuratorFramework barClient = client.usingNamespace("bar"); fooClient.create().forPath("/one"); barClient.create().forPath("/one"); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/foo/one", false)); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/bar/one", false)); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testCache() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); Assert.assertSame(client.usingNamespace("foo"), client.usingNamespace("foo")); Assert.assertNotSame(client.usingNamespace("foo"), client.usingNamespace("bar")); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testBasic() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); client.create().forPath("/one"); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/one", false)); client.usingNamespace("space").create().forPath("/one"); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/space", false)); client.usingNamespace("name").create().forPath("/one"); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/name", false)); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/name/one", false)); } finally { CloseableUtils.closeQuietly(client); } } /** * CURATOR-128: access root node within a namespace. */ @Test public void testRootAccess() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); client.create().forPath("/one"); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/one", false)); Assert.assertNotNull(client.checkExists().forPath("/")); try { client.checkExists().forPath(""); Assert.fail("IllegalArgumentException expected"); } catch ( IllegalArgumentException expected ) { } Assert.assertNotNull(client.usingNamespace("one").checkExists().forPath("/")); try { client.usingNamespace("one").checkExists().forPath(""); Assert.fail("IllegalArgumentException expected"); } catch ( IllegalArgumentException expected ) { } } finally { CloseableUtils.closeQuietly(client); } } @Test public void testIsStarted() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); CuratorFramework namespaced = client.usingNamespace(null); Assert.assertEquals(client.getState(), namespaced.getState(), "Namespaced state did not match true state after call to start."); client.close(); Assert.assertEquals(client.getState(), namespaced.getState(), "Namespaced state did not match true state after call to close."); } /** * Test that ACLs work on a NamespaceFacade. See CURATOR-132 * @throws Exception */ @Test public void testACL() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); client.getZookeeperClient().blockUntilConnectedOrTimedOut(); client.create().creatingParentsIfNeeded().forPath("/parent/child", "A string".getBytes()); CuratorFramework client2 = client.usingNamespace("parent"); Assert.assertNotNull(client2.getData().forPath("/child")); client.setACL().withACL(Collections.singletonList( new ACL(ZooDefs.Perms.WRITE, ZooDefs.Ids.ANYONE_ID_UNSAFE))). forPath("/parent/child"); // This will attempt to setACL on /parent/child, Previously this failed because /child // isn't present. Using "child" would case a failure because the path didn't start with // a slash try { List acls = client2.getACL().forPath("/child"); Assert.assertNotNull(acls); Assert.assertEquals(acls.size(), 1); Assert.assertEquals(acls.get(0).getId(), ZooDefs.Ids.ANYONE_ID_UNSAFE); Assert.assertEquals(acls.get(0).getPerms(), ZooDefs.Perms.WRITE); client2.setACL().withACL(Collections.singletonList( new ACL(ZooDefs.Perms.DELETE, ZooDefs.Ids.ANYONE_ID_UNSAFE))). forPath("/child"); Assert.fail("Expected auth exception was not thrown"); } catch(NoAuthException e) { //Expected } } } TestNeverConnected.java000066400000000000000000000052331245521677600372410ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import com.google.common.collect.Queues; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.Timing; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; public class TestNeverConnected { @Test public void testNeverConnected() throws Exception { Timing timing = new Timing(); // use a connection string to a non-existent server CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:1111", 100, 100, new RetryOneTime(1)); try { final BlockingQueue queue = Queues.newLinkedBlockingQueue(); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState state) { queue.add(state); } }; client.getConnectionStateListenable().addListener(listener); client.start(); client.create().inBackground().forPath("/"); ConnectionState polled = queue.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS); Assert.assertEquals(polled, ConnectionState.SUSPENDED); polled = queue.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS); Assert.assertEquals(polled, ConnectionState.LOST); } finally { CloseableUtils.closeQuietly(client); } } } TestReadOnly.java000066400000000000000000000143111245521677600360510ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import com.google.common.collect.Queues; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.retry.RetryNTimes; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.InstanceSpec; import org.apache.curator.test.TestingCluster; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.Iterator; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class TestReadOnly { @BeforeMethod public void setup() { System.setProperty("readonlymode.enabled", "true"); } @AfterMethod public void tearDown() { System.setProperty("readonlymode.enabled", "false"); } @Test public void testConnectionStateNewClient() throws Exception { Timing timing = new Timing(); TestingCluster cluster = new TestingCluster(3); CuratorFramework client = null; try { cluster.start(); client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(100)); client.start(); client.checkExists().forPath("/"); client.close(); client = null; Iterator iterator = cluster.getInstances().iterator(); for ( int i = 0; i < 2; ++i ) { cluster.killServer(iterator.next()); } client = CuratorFrameworkFactory.builder() .connectString(cluster.getConnectString()) .sessionTimeoutMs(timing.session()) .connectionTimeoutMs(timing.connection()) .retryPolicy(new RetryNTimes(3, timing.milliseconds())) .canBeReadOnly(true) .build(); final BlockingQueue states = Queues.newLinkedBlockingQueue(); client.getConnectionStateListenable().addListener ( new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { states.add(newState); } } ); client.start(); client.checkExists().forPath("/"); ConnectionState state = states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS); Assert.assertEquals(state, ConnectionState.READ_ONLY); } finally { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(cluster); } } @Test public void testReadOnly() throws Exception { Timing timing = new Timing(); CuratorFramework client = null; TestingCluster cluster = new TestingCluster(2); try { cluster.start(); client = CuratorFrameworkFactory.builder().connectString(cluster.getConnectString()).canBeReadOnly(true).connectionTimeoutMs(timing.connection()).sessionTimeoutMs(timing.session()).retryPolicy(new ExponentialBackoffRetry(100, 3)).build(); client.start(); client.create().forPath("/test"); final CountDownLatch readOnlyLatch = new CountDownLatch(1); final CountDownLatch reconnectedLatch = new CountDownLatch(1); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState == ConnectionState.READ_ONLY ) { readOnlyLatch.countDown(); } else if ( newState == ConnectionState.RECONNECTED ) { reconnectedLatch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); InstanceSpec ourInstance = cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper()); Iterator iterator = cluster.getInstances().iterator(); InstanceSpec killInstance = iterator.next(); if ( killInstance.equals(ourInstance) ) { killInstance = iterator.next(); // kill the instance we're not connected to } cluster.killServer(killInstance); Assert.assertEquals(reconnectedLatch.getCount(), 1); Assert.assertTrue(timing.awaitLatch(readOnlyLatch)); Assert.assertEquals(reconnectedLatch.getCount(), 1); cluster.restartServer(killInstance); Assert.assertTrue(timing.awaitLatch(reconnectedLatch)); } finally { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(cluster); } } } TestTempFramework.java000066400000000000000000000057131245521677600371250ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.CuratorTempFramework; import org.apache.curator.retry.RetryOneTime; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class TestTempFramework extends BaseClassForTests { @Test public void testBasic() throws Exception { CuratorTempFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).buildTemp(); try { client.inTransaction().create().forPath("/foo", "data".getBytes()).and().commit(); byte[] bytes = client.getData().forPath("/foo"); Assert.assertEquals(bytes, "data".getBytes()); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testInactivity() throws Exception { final CuratorTempFrameworkImpl client = (CuratorTempFrameworkImpl)CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).buildTemp(1, TimeUnit.SECONDS); try { ScheduledExecutorService service = Executors.newScheduledThreadPool(1); Runnable command = new Runnable() { @Override public void run() { client.updateLastAccess(); } }; service.scheduleAtFixedRate(command, 10, 10, TimeUnit.MILLISECONDS); client.inTransaction().create().forPath("/foo", "data".getBytes()).and().commit(); service.shutdownNow(); Thread.sleep(2000); Assert.assertNull(client.getCleanup()); Assert.assertNull(client.getClient()); } finally { CloseableUtils.closeQuietly(client); } } } TestTransactions.java000066400000000000000000000127421245521677600370120ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import com.google.common.collect.Iterables; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.transaction.CuratorTransactionResult; import org.apache.curator.framework.api.transaction.OperationType; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.data.Stat; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Collection; public class TestTransactions extends BaseClassForTests { @Test public void testCheckVersion() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/foo"); Stat stat = client.setData().forPath("/foo", "new".getBytes()); // up the version try { client.inTransaction() .check().withVersion(stat.getVersion() + 1).forPath("/foo") // force a bad version .and() .create().forPath("/bar") .and() .commit(); Assert.fail(); } catch ( KeeperException.BadVersionException correct ) { // correct } Assert.assertNull(client.checkExists().forPath("/bar")); } finally { client.close(); } } @Test public void testWithNamespace() throws Exception { CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace("galt").build(); client.start(); try { Collection results = client.inTransaction() .create().forPath("/foo", "one".getBytes()) .and() .create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/test-", "one".getBytes()) .and() .setData().forPath("/foo", "two".getBytes()) .and() .create().forPath("/foo/bar") .and() .delete().forPath("/foo/bar") .and() .commit(); Assert.assertTrue(client.checkExists().forPath("/foo") != null); Assert.assertTrue(client.usingNamespace(null).checkExists().forPath("/galt/foo") != null); Assert.assertEquals(client.getData().forPath("/foo"), "two".getBytes()); Assert.assertTrue(client.checkExists().forPath("/foo/bar") == null); CuratorTransactionResult ephemeralResult = Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/test-")); Assert.assertNotNull(ephemeralResult); Assert.assertNotEquals(ephemeralResult.getResultPath(), "/test-"); Assert.assertTrue(ephemeralResult.getResultPath().startsWith("/test-")); } finally { client.close(); } } @Test public void testBasic() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { Collection results = client.inTransaction() .create().forPath("/foo") .and() .create().forPath("/foo/bar", "snafu".getBytes()) .and() .commit(); Assert.assertTrue(client.checkExists().forPath("/foo/bar") != null); Assert.assertEquals(client.getData().forPath("/foo/bar"), "snafu".getBytes()); CuratorTransactionResult fooResult = Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/foo")); CuratorTransactionResult fooBarResult = Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/foo/bar")); Assert.assertNotNull(fooResult); Assert.assertNotNull(fooBarResult); Assert.assertNotSame(fooResult, fooBarResult); Assert.assertEquals(fooResult.getResultPath(), "/foo"); Assert.assertEquals(fooBarResult.getResultPath(), "/foo/bar"); } finally { client.close(); } } } TestWatcherIdentity.java000066400000000000000000000150701245521677600374460ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.Timing; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; public class TestWatcherIdentity extends BaseClassForTests { private static final String PATH = "/foo"; private static class CountCuratorWatcher implements CuratorWatcher { private final AtomicInteger count = new AtomicInteger(0); @Override public void process(WatchedEvent event) throws Exception { count.incrementAndGet(); } } private static class CountZKWatcher implements Watcher { private final AtomicInteger count = new AtomicInteger(0); @Override public void process(WatchedEvent event) { System.out.println("count=" + count); count.incrementAndGet(); } } @Test public void testRefExpiration() throws Exception { final int MAX_CHECKS = 10; final CuratorFrameworkImpl client = (CuratorFrameworkImpl)CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { Assert.assertNull(client.getNamespaceWatcherMap().get(new CountCuratorWatcher())); final CountDownLatch latch = new CountDownLatch(1); ExecutorService service = Executors.newSingleThreadExecutor(); service.submit ( new Callable() { @Override public Void call() throws Exception { CountZKWatcher watcher = new CountZKWatcher(); client.getNamespaceWatcherMap().getNamespaceWatcher(watcher); Assert.assertNotNull(client.getNamespaceWatcherMap().get(watcher)); latch.countDown(); return null; } } ); latch.await(); service.shutdownNow(); Timing timing = new Timing(); for ( int i = 0; i < MAX_CHECKS; ++i ) { Assert.assertTrue((i + 1) < MAX_CHECKS); timing.sleepABit(); client.getNamespaceWatcherMap().drain(); // just to cause drainReferenceQueues() to get called if ( client.getNamespaceWatcherMap().isEmpty() ) { break; } } } finally { CloseableUtils.closeQuietly(client); } } @Test public void testSimpleId() { CountCuratorWatcher curatorWatcher = new CountCuratorWatcher(); CountZKWatcher zkWatcher = new CountZKWatcher(); CuratorFrameworkImpl client = (CuratorFrameworkImpl)CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { Assert.assertSame(client.getNamespaceWatcherMap().getNamespaceWatcher(curatorWatcher), client.getNamespaceWatcherMap().getNamespaceWatcher(curatorWatcher)); Assert.assertSame(client.getNamespaceWatcherMap().getNamespaceWatcher(zkWatcher), client.getNamespaceWatcherMap().getNamespaceWatcher(zkWatcher)); Assert.assertNotSame(client.getNamespaceWatcherMap().getNamespaceWatcher(curatorWatcher), client.getNamespaceWatcherMap().getNamespaceWatcher(zkWatcher)); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testCuratorWatcher() throws Exception { Timing timing = new Timing(); CountCuratorWatcher watcher = new CountCuratorWatcher(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); client.create().forPath(PATH); // Add twice the same watcher on the same path client.getData().usingWatcher(watcher).forPath(PATH); client.getData().usingWatcher(watcher).forPath(PATH); // Ok, let's test it client.setData().forPath(PATH, new byte[]{}); timing.sleepABit(); Assert.assertEquals(1, watcher.count.get()); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testZKWatcher() throws Exception { Timing timing = new Timing(); CountZKWatcher watcher = new CountZKWatcher(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); client.create().forPath(PATH); // Add twice the same watcher on the same path client.getData().usingWatcher(watcher).forPath(PATH); client.getData().usingWatcher(watcher).forPath(PATH); // Ok, let's test it client.setData().forPath(PATH, new byte[]{}); timing.sleepABit(); Assert.assertEquals(1, watcher.count.get()); } finally { CloseableUtils.closeQuietly(client); } } } TestWithCluster.java000066400000000000000000000112521245521677600366120ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/java/org/apache/curator/framework/imps/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.imps; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.InstanceSpec; import org.apache.curator.test.TestingCluster; import org.apache.curator.test.Timing; import org.apache.zookeeper.CreateMode; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.CountDownLatch; public class TestWithCluster { @Test public void testSessionSurvives() throws Exception { Timing timing = new Timing(); CuratorFramework client = null; TestingCluster cluster = new TestingCluster(3); cluster.start(); try { client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); client.start(); client.create().withMode(CreateMode.EPHEMERAL).forPath("/temp", "value".getBytes()); Assert.assertNotNull(client.checkExists().forPath("/temp")); for ( InstanceSpec spec : cluster.getInstances() ) { cluster.killServer(spec); timing.forWaiting().sleepABit(); cluster.restartServer(spec); timing.sleepABit(); } timing.sleepABit(); Assert.assertNotNull(client.checkExists().forPath("/temp")); } finally { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(cluster); } } @Test public void testSplitBrain() throws Exception { Timing timing = new Timing(); CuratorFramework client = null; TestingCluster cluster = new TestingCluster(3); cluster.start(); try { // make sure all instances are up for ( InstanceSpec instanceSpec : cluster.getInstances() ) { client = CuratorFrameworkFactory.newClient(instanceSpec.getConnectString(), new RetryOneTime(1)); client.start(); client.checkExists().forPath("/"); client.close(); client = null; } client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); final CountDownLatch latch = new CountDownLatch(2); client.getConnectionStateListenable().addListener ( new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( (newState == ConnectionState.SUSPENDED) || (newState == ConnectionState.LOST) ) { latch.countDown(); } } } ); client.checkExists().forPath("/"); for ( InstanceSpec instanceSpec : cluster.getInstances() ) { if ( !instanceSpec.equals(cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper())) ) { Assert.assertTrue(cluster.killServer(instanceSpec)); } } Assert.assertTrue(timing.awaitLatch(latch)); } finally { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(cluster); } } } curator-apache-curator-2.7.1/curator-framework/src/test/resources/000077500000000000000000000000001245521677600253455ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-framework/src/test/resources/log4j.properties000066400000000000000000000021131245521677600304770ustar00rootroot00000000000000# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # log4j.rootLogger=ERROR, console log4j.logger.org.apache.curator=DEBUG, console log4j.additivity.org.apache.curator=false log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%-5p %c %x %m [%t]%n curator-apache-curator-2.7.1/curator-recipes/000077500000000000000000000000001245521677600212225ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/LICENSE000066400000000000000000000261361245521677600222370ustar00rootroot00000000000000 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. curator-apache-curator-2.7.1/curator-recipes/NOTICE000066400000000000000000000002501245521677600221230ustar00rootroot00000000000000Apache Curator Copyright 2013-2014 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). curator-apache-curator-2.7.1/curator-recipes/pom.xml000066400000000000000000000044751245521677600225510ustar00rootroot00000000000000 4.0.0 org.apache.curator apache-curator 2.7.1 curator-recipes 2.7.1 bundle Curator Recipes All of the recipes listed on the ZooKeeper recipes doc (except two phase commit). 2011 * org.apache.curator.framework.recipes*;version="${project.version}";-noimport:=true org.apache.curator curator-framework org.apache.curator curator-test test org.mockito mockito-core test curator-apache-curator-2.7.1/curator-recipes/src/000077500000000000000000000000001245521677600220115ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/000077500000000000000000000000001245521677600227355ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/000077500000000000000000000000001245521677600236565ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/000077500000000000000000000000001245521677600244455ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/000077500000000000000000000000001245521677600256665ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/000077500000000000000000000000001245521677600273455ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/000077500000000000000000000000001245521677600313425ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/000077500000000000000000000000001245521677600327745ustar00rootroot00000000000000AfterConnectionEstablished.java000066400000000000000000000051321245521677600410120ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.ThreadUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; /** * Utility class to allow execution of logic once a ZooKeeper connection becomes available. */ public class AfterConnectionEstablished { private final static Logger log = LoggerFactory.getLogger(AfterConnectionEstablished.class); /** * Spawns a new new background thread that will block until a connection is available and * then execute the 'runAfterConnection' logic * * @param client The curator client * @param runAfterConnection The logic to run * @return future of the task so it can be canceled, etc. if needed */ public static Future execute(final CuratorFramework client, final Runnable runAfterConnection) throws Exception { //Block until connected final ExecutorService executor = ThreadUtils.newSingleThreadExecutor(ThreadUtils.getProcessName(runAfterConnection.getClass())); Runnable internalCall = new Runnable() { @Override public void run() { try { client.blockUntilConnected(); runAfterConnection.run(); } catch ( Exception e ) { log.error("An error occurred blocking until a connection is available", e); } finally { executor.shutdown(); } } }; return executor.submit(internalCall); } private AfterConnectionEstablished() { } } 000077500000000000000000000000001245521677600341715ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomicAtomicStats.java000066400000000000000000000043441245521677600372740ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.atomic; /** * Debugging stats about operations */ public class AtomicStats { private int optimisticTries = 0; private int promotedLockTries = 0; private long optimisticTimeMs = 0; private long promotedTimeMs = 0; /** * Returns the number of optimistic locks used to perform the operation * * @return qty */ public int getOptimisticTries() { return optimisticTries; } /** * Returns the number of mutex locks used to perform the operation * * @return qty */ public int getPromotedLockTries() { return promotedLockTries; } /** * Returns the time spent trying the operation with optimistic locks * * @return time in ms */ public long getOptimisticTimeMs() { return optimisticTimeMs; } /** * Returns the time spent trying the operation with mutex locks * * @return time in ms */ public long getPromotedTimeMs() { return promotedTimeMs; } void incrementOptimisticTries() { ++optimisticTries; } void incrementPromotedTries() { ++promotedLockTries; } void setOptimisticTimeMs(long optimisticTimeMs) { this.optimisticTimeMs = optimisticTimeMs; } void setPromotedTimeMs(long promotedTimeMs) { this.promotedTimeMs = promotedTimeMs; } } AtomicValue.java000066400000000000000000000031631245521677600372500ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.atomic; /** * Abstracts a value returned from one of the Atomics */ public interface AtomicValue { /** * MUST be checked. Returns true if the operation succeeded. If false is returned, * the operation failed and the atomic was not updated. * * @return true/false */ public boolean succeeded(); /** * Returns the value of the counter prior to the operation * * @return pre-operation value */ public T preValue(); /** * Returns the value of the counter after to the operation * * @return post-operation value */ public T postValue(); /** * Returns debugging stats about the operation * * @return stats */ public AtomicStats getStats(); } CachedAtomicInteger.java000066400000000000000000000046641245521677600406700ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.atomic; /** * Uses an {@link DistributedAtomicNumber} and allocates values in chunks for better performance */ public class CachedAtomicInteger { private final DistributedAtomicInteger number; private final int cacheFactor; private AtomicValue currentValue = null; private int currentIndex = 0; /** * @param number the number to use * @param cacheFactor the number of values to allocate at a time */ public CachedAtomicInteger(DistributedAtomicInteger number, int cacheFactor) { this.number = number; this.cacheFactor = cacheFactor; } /** * Returns the next value (incrementing by 1). If a new chunk of numbers is needed, it is * requested from the number * * @return next increment * @throws Exception errors */ public AtomicValue next() throws Exception { MutableAtomicValue result = new MutableAtomicValue(0, 0); if ( currentValue == null ) { currentValue = number.add(cacheFactor); if ( !currentValue.succeeded() ) { currentValue = null; result.succeeded = false; return result; } currentIndex = 0; } result.succeeded = true; result.preValue = currentValue.preValue() + currentIndex; result.postValue = result.preValue + 1; if ( ++currentIndex >= cacheFactor ) { currentValue = null; } return result; } } CachedAtomicLong.java000066400000000000000000000046341245521677600401670ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.atomic; /** * Uses an {@link DistributedAtomicNumber} and allocates values in chunks for better performance */ public class CachedAtomicLong { private final DistributedAtomicLong number; private final long cacheFactor; private AtomicValue currentValue = null; private int currentIndex = 0; /** * @param number the number to use * @param cacheFactor the number of values to allocate at a time */ public CachedAtomicLong(DistributedAtomicLong number, int cacheFactor) { this.number = number; this.cacheFactor = cacheFactor; } /** * Returns the next value (incrementing by 1). If a new chunk of numbers is needed, it is * requested from the number * * @return next increment * @throws Exception errors */ public AtomicValue next() throws Exception { MutableAtomicValue result = new MutableAtomicValue(0L, 0L); if ( currentValue == null ) { currentValue = number.add(cacheFactor); if ( !currentValue.succeeded() ) { currentValue = null; result.succeeded = false; return result; } currentIndex = 0; } result.succeeded = true; result.preValue = currentValue.preValue() + currentIndex; result.postValue = result.preValue + 1; if ( ++currentIndex >= cacheFactor ) { currentValue = null; } return result; } } DistributedAtomicInteger.java000066400000000000000000000165241245521677600420010ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.atomic; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; /** *

A counter that attempts atomic increments. It first tries uses optimistic locking. If that fails, * an optional {@link InterProcessMutex} is taken. For both optimistic and mutex, a retry policy is used to * retry the increment.

* *

The various increment methods return an {@link AtomicValue} object. You must always check * {@link AtomicValue#succeeded()}. None of the methods (other than get()) are guaranteed to succeed.

*/ public class DistributedAtomicInteger implements DistributedAtomicNumber { private final DistributedAtomicValue value; /** * Creates in optimistic mode only - i.e. the promotion to a mutex is not done * * @param client the client * @param counterPath path to hold the value * @param retryPolicy the retry policy to use */ public DistributedAtomicInteger(CuratorFramework client, String counterPath, RetryPolicy retryPolicy) { this(client, counterPath, retryPolicy, null); } /** * Creates in mutex promotion mode. The optimistic lock will be tried first using * the given retry policy. If the increment does not succeed, a {@link InterProcessMutex} will be tried * with its own retry policy * * @param client the client * @param counterPath path to hold the value * @param retryPolicy the retry policy to use * @param promotedToLock the arguments for the mutex promotion */ public DistributedAtomicInteger(CuratorFramework client, String counterPath, RetryPolicy retryPolicy, PromotedToLock promotedToLock) { value = new DistributedAtomicValue(client, counterPath, retryPolicy, promotedToLock); } @Override public AtomicValue get() throws Exception { return new AtomicInteger(value.get()); } @Override public void forceSet(Integer newValue) throws Exception { value.forceSet(valueToBytes(newValue)); } @Override public AtomicValue compareAndSet(Integer expectedValue, Integer newValue) throws Exception { return new AtomicInteger(value.compareAndSet(valueToBytes(expectedValue), valueToBytes(newValue))); } @Override public AtomicValue trySet(Integer newValue) throws Exception { return new AtomicInteger(value.trySet(valueToBytes(newValue))); } @Override public boolean initialize(Integer initialize) throws Exception { return value.initialize(valueToBytes(initialize)); } /** * Add 1 to the current value and return the new value information. Remember to always * check {@link AtomicValue#succeeded()}. * * @return value info * @throws Exception ZooKeeper errors */ @Override public AtomicValue increment() throws Exception { return worker(1); } /** * Subtract 1 from the current value and return the new value information. Remember to always * check {@link AtomicValue#succeeded()}. * * @return value info * @throws Exception ZooKeeper errors */ @Override public AtomicValue decrement() throws Exception { return worker(-1); } /** * Add delta to the current value and return the new value information. Remember to always * check {@link AtomicValue#succeeded()}. * * @param delta amount to add * @return value info * @throws Exception ZooKeeper errors */ @Override public AtomicValue add(Integer delta) throws Exception { return worker(delta); } /** * Subtract delta from the current value and return the new value information. Remember to always * check {@link AtomicValue#succeeded()}. * * @param delta amount to subtract * @return value info * @throws Exception ZooKeeper errors */ @Override public AtomicValue subtract(Integer delta) throws Exception { return worker(-1 * delta); } @VisibleForTesting byte[] valueToBytes(Integer newValue) { Preconditions.checkNotNull(newValue, "newValue cannot be null"); byte[] newData = new byte[4]; ByteBuffer wrapper = ByteBuffer.wrap(newData); wrapper.putInt(newValue); return newData; } @VisibleForTesting int bytesToValue(byte[] data) { if ( (data == null) || (data.length == 0) ) { return 0; } ByteBuffer wrapper = ByteBuffer.wrap(data); try { return wrapper.getInt(); } catch ( BufferUnderflowException e ) { throw value.createCorruptionException(data); } catch ( BufferOverflowException e ) { throw value.createCorruptionException(data); } } private AtomicValue worker(final Integer addAmount) throws Exception { Preconditions.checkNotNull(addAmount, "addAmount cannot be null"); MakeValue makeValue = new MakeValue() { @Override public byte[] makeFrom(byte[] previous) { int previousValue = (previous != null) ? bytesToValue(previous) : 0; int newValue = previousValue + addAmount; return valueToBytes(newValue); } }; AtomicValue result = value.trySet(makeValue); return new AtomicInteger(result); } private class AtomicInteger implements AtomicValue { private AtomicValue bytes; private AtomicInteger(AtomicValue bytes) { this.bytes = bytes; } @Override public boolean succeeded() { return bytes.succeeded(); } @Override public Integer preValue() { return bytesToValue(bytes.preValue()); } @Override public Integer postValue() { return bytesToValue(bytes.postValue()); } @Override public AtomicStats getStats() { return bytes.getStats(); } } } DistributedAtomicLong.java000066400000000000000000000164011245521677600412750ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.atomic; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; /** *

A counter that attempts atomic increments. It first tries uses optimistic locking. If that fails, * an optional {@link InterProcessMutex} is taken. For both optimistic and mutex, a retry policy is used to * retry the increment.

* *

The various increment methods return an {@link AtomicValue} object. You must always check * {@link AtomicValue#succeeded()}. None of the methods (other than get()) are guaranteed to succeed.

*/ public class DistributedAtomicLong implements DistributedAtomicNumber { private final DistributedAtomicValue value; /** * Creates in optimistic mode only - i.e. the promotion to a mutex is not done * * @param client the client * @param counterPath path to hold the value * @param retryPolicy the retry policy to use */ public DistributedAtomicLong(CuratorFramework client, String counterPath, RetryPolicy retryPolicy) { this(client, counterPath, retryPolicy, null); } /** * Creates in mutex promotion mode. The optimistic lock will be tried first using * the given retry policy. If the increment does not succeed, a {@link InterProcessMutex} will be tried * with its own retry policy * * @param client the client * @param counterPath path to hold the value * @param retryPolicy the retry policy to use * @param promotedToLock the arguments for the mutex promotion */ public DistributedAtomicLong(CuratorFramework client, String counterPath, RetryPolicy retryPolicy, PromotedToLock promotedToLock) { value = new DistributedAtomicValue(client, counterPath, retryPolicy, promotedToLock); } @Override public AtomicValue get() throws Exception { return new AtomicLong(value.get()); } @Override public void forceSet(Long newValue) throws Exception { value.forceSet(valueToBytes(newValue)); } @Override public AtomicValue compareAndSet(Long expectedValue, Long newValue) throws Exception { return new AtomicLong(value.compareAndSet(valueToBytes(expectedValue), valueToBytes(newValue))); } @Override public AtomicValue trySet(Long newValue) throws Exception { return new AtomicLong(value.trySet(valueToBytes(newValue))); } @Override public boolean initialize(Long initialize) throws Exception { return value.initialize(valueToBytes(initialize)); } /** * Add 1 to the current value and return the new value information. Remember to always * check {@link AtomicValue#succeeded()}. * * @return value info * @throws Exception ZooKeeper errors */ @Override public AtomicValue increment() throws Exception { return worker(1L); } /** * Subtract 1 from the current value and return the new value information. Remember to always * check {@link AtomicValue#succeeded()}. * * @return value info * @throws Exception ZooKeeper errors */ @Override public AtomicValue decrement() throws Exception { return worker(-1L); } /** * Add delta to the current value and return the new value information. Remember to always * check {@link AtomicValue#succeeded()}. * * @param delta amount to add * @return value info * @throws Exception ZooKeeper errors */ @Override public AtomicValue add(Long delta) throws Exception { return worker(delta); } /** * Subtract delta from the current value and return the new value information. Remember to always * check {@link AtomicValue#succeeded()}. * * @param delta amount to subtract * @return value info * @throws Exception ZooKeeper errors */ @Override public AtomicValue subtract(Long delta) throws Exception { return worker(-1 * delta); } @VisibleForTesting byte[] valueToBytes(Long newValue) { Preconditions.checkNotNull(newValue, "newValue cannot be null"); byte[] newData = new byte[8]; ByteBuffer wrapper = ByteBuffer.wrap(newData); wrapper.putLong(newValue); return newData; } @VisibleForTesting long bytesToValue(byte[] data) { if ( (data == null) || (data.length == 0) ) { return 0; } ByteBuffer wrapper = ByteBuffer.wrap(data); try { return wrapper.getLong(); } catch ( BufferUnderflowException e ) { throw value.createCorruptionException(data); } catch ( BufferOverflowException e ) { throw value.createCorruptionException(data); } } private AtomicValue worker(final Long addAmount) throws Exception { Preconditions.checkNotNull(addAmount, "addAmount cannot be null"); MakeValue makeValue = new MakeValue() { @Override public byte[] makeFrom(byte[] previous) { long previousValue = (previous != null) ? bytesToValue(previous) : 0; long newValue = previousValue + addAmount; return valueToBytes(newValue); } }; AtomicValue result = value.trySet(makeValue); return new AtomicLong(result); } private class AtomicLong implements AtomicValue { private AtomicValue bytes; private AtomicLong(AtomicValue bytes) { this.bytes = bytes; } @Override public boolean succeeded() { return bytes.succeeded(); } @Override public Long preValue() { return bytesToValue(bytes.preValue()); } @Override public Long postValue() { return bytesToValue(bytes.postValue()); } @Override public AtomicStats getStats() { return bytes.getStats(); } } } DistributedAtomicNumber.java000066400000000000000000000074721245521677600416360ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.atomic; public interface DistributedAtomicNumber { /** * Returns the current value of the counter. NOTE: if the value has never been set, * 0 is returned. * * @return value info * @throws Exception ZooKeeper errors */ public AtomicValue get() throws Exception; /** * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * Remember to always check {@link AtomicValue#succeeded()}. * * @param expectedValue the expected value * @param newValue the new value for the counter * @return value info * @throws Exception ZooKeeper errors */ public AtomicValue compareAndSet(T expectedValue, T newValue) throws Exception; /** * Attempt to atomically set the value to the given value. Remember to always * check {@link AtomicValue#succeeded()}. * * @param newValue the value to set * @return value info * @throws Exception ZooKeeper errors */ public AtomicValue trySet(T newValue) throws Exception; /** * Atomic values are initially set to the equivalent of NULL in a database. * Use this method to initialize the value. The value will be set if and only iff the node does not exist. * * @param value the initial value to set * @return true if the value was set, false if the node already existed * @throws Exception ZooKeeper errors */ public boolean initialize(T value) throws Exception; /** * Forcibly sets the value of the counter without any guarantees of atomicity. * * @param newValue the new value * @throws Exception ZooKeeper errors */ public void forceSet(T newValue) throws Exception; /** * Add 1 to the current value and return the new value information. Remember to always * check {@link AtomicValue#succeeded()}. * * @return value info * @throws Exception ZooKeeper errors */ public AtomicValue increment() throws Exception; /** * Subtract 1 from the current value and return the new value information. Remember to always * check {@link AtomicValue#succeeded()}. * * @return value info * @throws Exception ZooKeeper errors */ public AtomicValue decrement() throws Exception; /** * Add delta to the current value and return the new value information. Remember to always * check {@link AtomicValue#succeeded()}. * * @param delta amount to add * @return value info * @throws Exception ZooKeeper errors */ public AtomicValue add(T delta) throws Exception; /** * Subtract delta from the current value and return the new value information. Remember to always * check {@link AtomicValue#succeeded()}. * * @param delta amount to subtract * @return value info * @throws Exception ZooKeeper errors */ public AtomicValue subtract(T delta) throws Exception; } DistributedAtomicValue.java000066400000000000000000000276371245521677600414670ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.atomic; import org.apache.curator.RetryLoop; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import org.apache.curator.utils.EnsurePath; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.data.Stat; import java.util.Arrays; import org.apache.curator.utils.PathUtils; import org.apache.zookeeper.ZKUtil; /** *

A distributed value that attempts atomic sets. It first tries uses optimistic locking. If that fails, * an optional {@link InterProcessMutex} is taken. For both optimistic and mutex, a retry policy is used to * retry the increment.

* *

The various methods return an {@link AtomicValue} object. You must always check * {@link AtomicValue#succeeded()}. None of the methods (other than get()) are guaranteed to succeed.

*/ public class DistributedAtomicValue { private final CuratorFramework client; private final String path; private final RetryPolicy retryPolicy; private final PromotedToLock promotedToLock; private final InterProcessMutex mutex; private final EnsurePath ensurePath; /** * Creates in optimistic mode only - i.e. the promotion to a mutex is not done * * @param client the client * @param path path to hold the value * @param retryPolicy the retry policy to use */ public DistributedAtomicValue(CuratorFramework client, String path, RetryPolicy retryPolicy) { this(client, path, retryPolicy, null); } /** * Creates in mutex promotion mode. The optimistic lock will be tried first using * the given retry policy. If the increment does not succeed, a {@link InterProcessMutex} will be tried * with its own retry policy * * @param client the client * @param path path to hold the value * @param retryPolicy the retry policy to use * @param promotedToLock the arguments for the mutex promotion */ public DistributedAtomicValue(CuratorFramework client, String path, RetryPolicy retryPolicy, PromotedToLock promotedToLock) { this.client = client; this.path = PathUtils.validatePath(path); this.retryPolicy = retryPolicy; this.promotedToLock = promotedToLock; mutex = (promotedToLock != null) ? new InterProcessMutex(client, promotedToLock.getPath()) : null; ensurePath = client.newNamespaceAwareEnsurePath(path).excludingLast(); } /** * Returns the current value of the counter. NOTE: if the value has never been set, * 0 is returned. * * @return value info * @throws Exception ZooKeeper errors */ public AtomicValue get() throws Exception { MutableAtomicValue result = new MutableAtomicValue(null, null, false); getCurrentValue(result, new Stat()); result.postValue = result.preValue; result.succeeded = true; return result; } /** * Forcibly sets the value any guarantees of atomicity. * * @param newValue the new value * @throws Exception ZooKeeper errors */ public void forceSet(byte[] newValue) throws Exception { try { ensurePath.ensure(client.getZookeeperClient()); client.setData().forPath(path, newValue); } catch ( KeeperException.NoNodeException dummy ) { try { client.create().forPath(path, newValue); } catch ( KeeperException.NodeExistsException dummy2 ) { client.setData().forPath(path, newValue); } } } /** * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * Remember to always check {@link AtomicValue#succeeded()}. * * * @param expectedValue the expected value * @param newValue the new value * @return value info * @throws Exception ZooKeeper errors */ public AtomicValue compareAndSet(byte[] expectedValue, byte[] newValue) throws Exception { Stat stat = new Stat(); MutableAtomicValue result = new MutableAtomicValue(null, null, false); boolean createIt = getCurrentValue(result, stat); if ( !createIt && Arrays.equals(expectedValue, result.preValue) ) { try { client.setData().withVersion(stat.getVersion()).forPath(path, newValue); result.succeeded = true; result.postValue = newValue; } catch ( KeeperException.BadVersionException dummy ) { result.succeeded = false; } catch ( KeeperException.NoNodeException dummy ) { result.succeeded = false; } } else { result.succeeded = false; } return result; } /** * Attempt to atomically set the value to the given value. Remember to always * check {@link AtomicValue#succeeded()}. * * @param newValue the value to set * @return value info * @throws Exception ZooKeeper errors */ public AtomicValue trySet(final byte[] newValue) throws Exception { MutableAtomicValue result = new MutableAtomicValue(null, null, false); MakeValue makeValue = new MakeValue() { @Override public byte[] makeFrom(byte[] previous) { return newValue; } }; tryOptimistic(result, makeValue); if ( !result.succeeded() && (mutex != null) ) { tryWithMutex(result, makeValue); } return result; } /** * Atomic values are initially set to the equivalent of NULL in a database. * Use this method to initialize the value. The value will be set if and only iff the node does not exist. * * @param value the initial value to set * @return true if the value was set, false if the node already existed * @throws Exception ZooKeeper errors */ public boolean initialize(byte[] value) throws Exception { ensurePath.ensure(client.getZookeeperClient()); try { client.create().forPath(path, value); } catch ( KeeperException.NodeExistsException ignore ) { // ignore return false; } return true; } AtomicValue trySet(MakeValue makeValue) throws Exception { MutableAtomicValue result = new MutableAtomicValue(null, null, false); tryOptimistic(result, makeValue); if ( !result.succeeded() && (mutex != null) ) { tryWithMutex(result, makeValue); } return result; } RuntimeException createCorruptionException(byte[] bytes) { StringBuilder str = new StringBuilder(); str.append('['); boolean first = true; for ( byte b : bytes ) { if ( first ) { first = false; } else { str.append(", "); } str.append("0x").append(Integer.toHexString((b & 0xff))); } str.append(']'); return new RuntimeException(String.format("Corrupted data for node \"%s\": %s", path, str.toString())); } private boolean getCurrentValue(MutableAtomicValue result, Stat stat) throws Exception { boolean createIt = false; try { ensurePath.ensure(client.getZookeeperClient()); result.preValue = client.getData().storingStatIn(stat).forPath(path); } catch ( KeeperException.NoNodeException e ) { result.preValue = null; createIt = true; } return createIt; } private void tryWithMutex(MutableAtomicValue result, MakeValue makeValue) throws Exception { long startMs = System.currentTimeMillis(); int retryCount = 0; if ( mutex.acquire(promotedToLock.getMaxLockTime(), promotedToLock.getMaxLockTimeUnit()) ) { try { boolean done = false; while ( !done ) { result.stats.incrementPromotedTries(); if ( tryOnce(result, makeValue) ) { result.succeeded = true; done = true; } else { if ( !promotedToLock.getRetryPolicy().allowRetry(retryCount++, System.currentTimeMillis() - startMs, RetryLoop.getDefaultRetrySleeper()) ) { done = true; } } } } finally { mutex.release(); } } result.stats.setPromotedTimeMs(System.currentTimeMillis() - startMs); } private void tryOptimistic(MutableAtomicValue result, MakeValue makeValue) throws Exception { long startMs = System.currentTimeMillis(); int retryCount = 0; boolean done = false; while ( !done ) { result.stats.incrementOptimisticTries(); if ( tryOnce(result, makeValue) ) { result.succeeded = true; done = true; } else { if ( !retryPolicy.allowRetry(retryCount++, System.currentTimeMillis() - startMs, RetryLoop.getDefaultRetrySleeper()) ) { done = true; } } } result.stats.setOptimisticTimeMs(System.currentTimeMillis() - startMs); } private boolean tryOnce(MutableAtomicValue result, MakeValue makeValue) throws Exception { Stat stat = new Stat(); boolean createIt = getCurrentValue(result, stat); boolean success = false; try { byte[] newValue = makeValue.makeFrom(result.preValue); if ( createIt ) { client.create().forPath(path, newValue); } else { client.setData().withVersion(stat.getVersion()).forPath(path, newValue); } result.postValue = Arrays.copyOf(newValue, newValue.length); success = true; } catch ( KeeperException.NodeExistsException e ) { // do Retry } catch ( KeeperException.BadVersionException e ) { // do Retry } catch ( KeeperException.NoNodeException e ) { // do Retry } return success; } } MakeValue.java000066400000000000000000000016521245521677600367120ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.atomic; interface MakeValue { public byte[] makeFrom(byte[] previous); } MutableAtomicValue.java000066400000000000000000000031461245521677600405630ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.atomic; class MutableAtomicValue implements AtomicValue { T preValue; T postValue; boolean succeeded = false; AtomicStats stats = new AtomicStats(); MutableAtomicValue(T preValue, T postValue) { this(preValue, postValue, false); } MutableAtomicValue(T preValue, T postValue, boolean succeeded) { this.preValue = preValue; this.postValue = postValue; this.succeeded = succeeded; } @Override public T preValue() { return preValue; } @Override public T postValue() { return postValue; } @Override public boolean succeeded() { return succeeded; } @Override public AtomicStats getStats() { return stats; } } PromotedToLock.java000066400000000000000000000075771245521677600377610ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.atomic; import com.google.common.base.Preconditions; import org.apache.curator.RetryPolicy; import org.apache.curator.retry.RetryNTimes; import java.util.concurrent.TimeUnit; import org.apache.curator.utils.PathUtils; /** * Abstraction of arguments for mutex promotion. Use {@link #builder()} to create. */ public class PromotedToLock { private final String path; private final long maxLockTime; private final TimeUnit maxLockTimeUnit; private final RetryPolicy retryPolicy; /** * Allocate a new builder * * @return new builder */ public static Builder builder() { return new Builder(); } public static class Builder { private PromotedToLock instance = new PromotedToLock(null, -1, null, new RetryNTimes(0, 0)); /** * Build the argument block * * @return new block */ public PromotedToLock build() { Preconditions.checkNotNull(instance.path, "path cannot be null"); Preconditions.checkNotNull(instance.retryPolicy, "retryPolicy cannot be null"); return new PromotedToLock(instance.path, instance.maxLockTime, instance.maxLockTimeUnit, instance.retryPolicy); } /** * Set the path for the mutex lock (required) * * @param path path * @return this */ public Builder lockPath(String path) { instance = new PromotedToLock(PathUtils.validatePath(path), instance.maxLockTime, instance.maxLockTimeUnit, instance.retryPolicy); return this; } /** * Set the retry policy to use when an operation does not succeed * * @param retryPolicy new policy * @return this */ public Builder retryPolicy(RetryPolicy retryPolicy) { instance = new PromotedToLock(instance.path, instance.maxLockTime, instance.maxLockTimeUnit, retryPolicy); return this; } /** * Set the timeout to use when locking (optional) * * @param maxLockTime time * @param maxLockTimeUnit unit * @return this */ public Builder timeout(long maxLockTime, TimeUnit maxLockTimeUnit) { instance = new PromotedToLock(instance.path, maxLockTime, maxLockTimeUnit, instance.retryPolicy); return this; } private Builder() { } } String getPath() { return path; } long getMaxLockTime() { return maxLockTime; } TimeUnit getMaxLockTimeUnit() { return maxLockTimeUnit; } RetryPolicy getRetryPolicy() { return retryPolicy; } private PromotedToLock(String path, long maxLockTime, TimeUnit maxLockTimeUnit, RetryPolicy retryPolicy) { this.path = path; this.maxLockTime = maxLockTime; this.maxLockTimeUnit = maxLockTimeUnit; this.retryPolicy = retryPolicy; } } 000077500000000000000000000000001245521677600345265ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/barriersDistributedBarrier.java000066400000000000000000000103501245521677600411610ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/barriers/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.barriers; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import java.util.concurrent.TimeUnit; import org.apache.curator.utils.PathUtils; /** *

* A barrier as described in the ZK recipes. Quoting the recipe: *

* *
* Distributed systems use barriers to block processing of a set of nodes * until a condition is met at which time all the nodes are allowed to proceed *
*/ public class DistributedBarrier { private final CuratorFramework client; private final String barrierPath; private final Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { notifyFromWatcher(); } }; /** * @param client client * @param barrierPath path to use as the barrier */ public DistributedBarrier(CuratorFramework client, String barrierPath) { this.client = client; this.barrierPath = PathUtils.validatePath(barrierPath); } /** * Utility to set the barrier node * * @throws Exception errors */ public synchronized void setBarrier() throws Exception { try { client.create().creatingParentsIfNeeded().forPath(barrierPath); } catch ( KeeperException.NodeExistsException ignore ) { // ignore } } /** * Utility to remove the barrier node * * @throws Exception errors */ public synchronized void removeBarrier() throws Exception { try { client.delete().forPath(barrierPath); } catch ( KeeperException.NoNodeException ignore ) { // ignore } } /** * Blocks until the barrier node comes into existence * * @throws Exception errors */ public synchronized void waitOnBarrier() throws Exception { waitOnBarrier(-1, null); } /** * Blocks until the barrier no longer exists or the timeout elapses * * @param maxWait max time to block * @param unit time unit * @return true if the wait was successful, false if the timeout elapsed first * @throws Exception errors */ public synchronized boolean waitOnBarrier(long maxWait, TimeUnit unit) throws Exception { long startMs = System.currentTimeMillis(); boolean hasMaxWait = (unit != null); long maxWaitMs = hasMaxWait ? TimeUnit.MILLISECONDS.convert(maxWait, unit) : Long.MAX_VALUE; boolean result; for(;;) { result = (client.checkExists().usingWatcher(watcher).forPath(barrierPath) == null); if ( result ) { break; } if ( hasMaxWait ) { long elapsed = System.currentTimeMillis() - startMs; long thisWaitMs = maxWaitMs - elapsed; if ( thisWaitMs <= 0 ) { break; } wait(thisWaitMs); } else { wait(); } } return result; } private synchronized void notifyFromWatcher() { notifyAll(); } } DistributedDoubleBarrier.java000066400000000000000000000265761245521677600423350ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/barriers/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.barriers; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.data.Stat; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.curator.utils.PathUtils; /** *

* A double barrier as described in the ZK recipes. Quoting the recipe: *

* *
* Double barriers enable * clients to synchronize the beginning and the end of a computation. When enough processes * have joined the barrier, processes start their computation and leave the barrier * once they have finished. *
*/ public class DistributedDoubleBarrier { private final CuratorFramework client; private final String barrierPath; private final int memberQty; private final String ourPath; private final String readyPath; private final AtomicBoolean hasBeenNotified = new AtomicBoolean(false); private final AtomicBoolean connectionLost = new AtomicBoolean(false); private final Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { connectionLost.set(event.getState() != Event.KeeperState.SyncConnected); notifyFromWatcher(); } }; private static final String READY_NODE = "ready"; /** * Creates the barrier abstraction. memberQty is the number of members in the * barrier. When {@link #enter()} is called, it blocks until all members have entered. When * {@link #leave()} is called, it blocks until all members have left. * * @param client the client * @param barrierPath path to use * @param memberQty the number of members in the barrier. NOTE: more than memberQty * can enter the barrier. memberQty is a threshold, not a limit */ public DistributedDoubleBarrier(CuratorFramework client, String barrierPath, int memberQty) { Preconditions.checkState(memberQty > 0, "memberQty cannot be 0"); this.client = client; this.barrierPath = PathUtils.validatePath(barrierPath); this.memberQty = memberQty; ourPath = ZKPaths.makePath(barrierPath, UUID.randomUUID().toString()); readyPath = ZKPaths.makePath(barrierPath, READY_NODE); } /** * Enter the barrier and block until all members have entered * * @throws Exception interruptions, errors, etc. */ public void enter() throws Exception { enter(-1, null); } /** * Enter the barrier and block until all members have entered or the timeout has * elapsed * * @param maxWait max time to block * @param unit time unit * @return true if the entry was successful, false if the timeout elapsed first * @throws Exception interruptions, errors, etc. */ public boolean enter(long maxWait, TimeUnit unit) throws Exception { long startMs = System.currentTimeMillis(); boolean hasMaxWait = (unit != null); long maxWaitMs = hasMaxWait ? TimeUnit.MILLISECONDS.convert(maxWait, unit) : Long.MAX_VALUE; boolean readyPathExists = (client.checkExists().usingWatcher(watcher).forPath(readyPath) != null); client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(ourPath); boolean result = (readyPathExists || internalEnter(startMs, hasMaxWait, maxWaitMs)); if ( connectionLost.get() ) { throw new KeeperException.ConnectionLossException(); } return result; } /** * Leave the barrier and block until all members have left * * @throws Exception interruptions, errors, etc. */ public synchronized void leave() throws Exception { leave(-1, null); } /** * Leave the barrier and block until all members have left or the timeout has * elapsed * * @param maxWait max time to block * @param unit time unit * @return true if leaving was successful, false if the timeout elapsed first * @throws Exception interruptions, errors, etc. */ public synchronized boolean leave(long maxWait, TimeUnit unit) throws Exception { long startMs = System.currentTimeMillis(); boolean hasMaxWait = (unit != null); long maxWaitMs = hasMaxWait ? TimeUnit.MILLISECONDS.convert(maxWait, unit) : Long.MAX_VALUE; return internalLeave(startMs, hasMaxWait, maxWaitMs); } @VisibleForTesting protected List getChildrenForEntering() throws Exception { return client.getChildren().forPath(barrierPath); } private List filterAndSortChildren(List children) { Iterable filtered = Iterables.filter ( children, new Predicate() { @Override public boolean apply(String name) { return !name.equals(READY_NODE); } } ); ArrayList filteredList = Lists.newArrayList(filtered); Collections.sort(filteredList); return filteredList; } private boolean internalLeave(long startMs, boolean hasMaxWait, long maxWaitMs) throws Exception { String ourPathName = ZKPaths.getNodeFromPath(ourPath); boolean ourNodeShouldExist = true; boolean result = true; for(;;) { if ( connectionLost.get() ) { throw new KeeperException.ConnectionLossException(); } List children; try { children = client.getChildren().forPath(barrierPath); } catch ( KeeperException.NoNodeException dummy ) { children = Lists.newArrayList(); } children = filterAndSortChildren(children); if ( (children == null) || (children.size() == 0) ) { break; } int ourIndex = children.indexOf(ourPathName); if ( (ourIndex < 0) && ourNodeShouldExist ) { if ( connectionLost.get() ) { break; // connection was lost but we've reconnected. However, our ephemeral node is gone } else { throw new IllegalStateException(String.format("Our path (%s) is missing", ourPathName)); } } if ( children.size() == 1 ) { if ( ourNodeShouldExist && !children.get(0).equals(ourPathName) ) { throw new IllegalStateException(String.format("Last path (%s) is not ours (%s)", children.get(0), ourPathName)); } checkDeleteOurPath(ourNodeShouldExist); break; } Stat stat; boolean IsLowestNode = (ourIndex == 0); if ( IsLowestNode ) { String highestNodePath = ZKPaths.makePath(barrierPath, children.get(children.size() - 1)); stat = client.checkExists().usingWatcher(watcher).forPath(highestNodePath); } else { String lowestNodePath = ZKPaths.makePath(barrierPath, children.get(0)); stat = client.checkExists().usingWatcher(watcher).forPath(lowestNodePath); checkDeleteOurPath(ourNodeShouldExist); ourNodeShouldExist = false; } if ( stat != null ) { if ( hasMaxWait ) { long elapsed = System.currentTimeMillis() - startMs; long thisWaitMs = maxWaitMs - elapsed; if ( thisWaitMs <= 0 ) { result = false; } else { wait(thisWaitMs); } } else { wait(); } } } try { client.delete().forPath(readyPath); } catch ( KeeperException.NoNodeException ignore ) { // ignore } return result; } private void checkDeleteOurPath(boolean shouldExist) throws Exception { if ( shouldExist ) { client.delete().forPath(ourPath); } } private synchronized boolean internalEnter(long startMs, boolean hasMaxWait, long maxWaitMs) throws Exception { boolean result = true; do { List children = getChildrenForEntering(); int count = (children != null) ? children.size() : 0; if ( count >= memberQty ) { try { client.create().forPath(readyPath); } catch ( KeeperException.NodeExistsException ignore ) { // ignore } break; } if ( hasMaxWait && !hasBeenNotified.get() ) { long elapsed = System.currentTimeMillis() - startMs; long thisWaitMs = maxWaitMs - elapsed; if ( thisWaitMs <= 0 ) { result = false; } else { wait(thisWaitMs); } if ( !hasBeenNotified.get() ) { result = false; } } else { wait(); } } while ( false ); return result; } private synchronized void notifyFromWatcher() { hasBeenNotified.set(true); notifyAll(); } } 000077500000000000000000000000001245521677600337605ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cacheChildData.java000066400000000000000000000073611245521677600364470ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; import org.apache.zookeeper.data.Stat; import java.util.Arrays; import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.utils.PathUtils; public class ChildData implements Comparable { private final String path; private final Stat stat; private final AtomicReference data; public ChildData(String path, Stat stat, byte[] data) { this.path = PathUtils.validatePath(path); this.stat = stat; this.data = new AtomicReference(data); } /** * {@inheritDoc} * * Note: this class has a natural ordering that is inconsistent with equals. */ @Override public int compareTo(ChildData rhs) { if ( this == rhs ) { return 0; } if ( rhs == null || getClass() != rhs.getClass() ) { return -1; } return path.compareTo(rhs.path); } @SuppressWarnings("RedundantIfStatement") @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } ChildData childData = (ChildData)o; if ( !Arrays.equals(data.get(), childData.data.get()) ) { return false; } if ( path != null ? !path.equals(childData.path) : childData.path != null ) { return false; } if ( stat != null ? !stat.equals(childData.stat) : childData.stat != null ) { return false; } return true; } @Override public int hashCode() { int result = path != null ? path.hashCode() : 0; result = 31 * result + (stat != null ? stat.hashCode() : 0); result = 31 * result + (data != null ? Arrays.hashCode(data.get()) : 0); return result; } /** * Returns the full path of the this child * * @return full path */ public String getPath() { return path; } /** * Returns the stat data for this child * * @return stat or null */ public Stat getStat() { return stat; } /** *

Returns the node data for this child when the cache mode is set to cache data.

* *

NOTE: the byte array returned is the raw reference of this instance's field. If you change * the values in the array any other callers to this method will see the change.

* * @return node data or null */ public byte[] getData() { return data.get(); } void clearData() { data.set(null); } @Override public String toString() { return "ChildData{" + "path='" + path + '\'' + ", stat=" + stat + ", data=" + Arrays.toString(data.get()) + '}'; } } EventOperation.java000066400000000000000000000025311245521677600375660ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; class EventOperation implements Operation { private final PathChildrenCache cache; private final PathChildrenCacheEvent event; EventOperation(PathChildrenCache cache, PathChildrenCacheEvent event) { this.cache = cache; this.event = event; } @Override public void invoke() { cache.callListeners(event); } @Override public String toString() { return "EventOperation{" + "event=" + event + '}'; } } GetDataOperation.java000066400000000000000000000037131245521677600400210ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; import org.apache.curator.utils.PathUtils; class GetDataOperation implements Operation { private final PathChildrenCache cache; private final String fullPath; GetDataOperation(PathChildrenCache cache, String fullPath) { this.cache = cache; this.fullPath = PathUtils.validatePath(fullPath); } @Override public void invoke() throws Exception { cache.getDataAndStat(fullPath); } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } GetDataOperation that = (GetDataOperation)o; //noinspection RedundantIfStatement if ( !fullPath.equals(that.fullPath) ) { return false; } return true; } @Override public int hashCode() { return fullPath.hashCode(); } @Override public String toString() { return "GetDataOperation{" + "fullPath='" + fullPath + '\'' + '}'; } } NodeCache.java000066400000000000000000000245321245521677600364420ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.curator.framework.listen.ListenerContainer; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.utils.EnsurePath; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.Exchanger; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.utils.PathUtils; /** *

A utility that attempts to keep the data from a node locally cached. This class * will watch the node, respond to update/create/delete events, pull down the data, etc. You can * register a listener that will get notified when changes occur.

* *

IMPORTANT - it's not possible to stay transactionally in sync. Users of this class must * be prepared for false-positives and false-negatives. Additionally, always use the version number * when updating data to avoid overwriting another process' change.

*/ public class NodeCache implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework client; private final String path; private final boolean dataIsCompressed; private final EnsurePath ensurePath; private final AtomicReference data = new AtomicReference(null); private final AtomicReference state = new AtomicReference(State.LATENT); private final ListenerContainer listeners = new ListenerContainer(); private final AtomicBoolean isConnected = new AtomicBoolean(true); private final ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( (newState == ConnectionState.CONNECTED) || (newState == ConnectionState.RECONNECTED) ) { if ( isConnected.compareAndSet(false, true) ) { try { reset(); } catch ( Exception e ) { log.error("Trying to reset after reconnection", e); } } } else { isConnected.set(false); } } }; private final CuratorWatcher watcher = new CuratorWatcher() { @Override public void process(WatchedEvent event) throws Exception { reset(); } }; private enum State { LATENT, STARTED, CLOSED } private final BackgroundCallback backgroundCallback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { processBackgroundResult(event); } }; /** * @param client curztor client * @param path the full path to the node to cache */ public NodeCache(CuratorFramework client, String path) { this(client, path, false); } /** * @param client curztor client * @param path the full path to the node to cache * @param dataIsCompressed if true, data in the path is compressed */ public NodeCache(CuratorFramework client, String path, boolean dataIsCompressed) { this.client = client; this.path = PathUtils.validatePath(path); this.dataIsCompressed = dataIsCompressed; ensurePath = client.newNamespaceAwareEnsurePath(path).excludingLast(); } /** * Start the cache. The cache is not started automatically. You must call this method. * * @throws Exception errors */ public void start() throws Exception { start(false); } /** * Same as {@link #start()} but gives the option of doing an initial build * * @param buildInitial if true, {@link #rebuild()} will be called before this method * returns in order to get an initial view of the node * @throws Exception errors */ public void start(boolean buildInitial) throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); ensurePath.ensure(client.getZookeeperClient()); client.getConnectionStateListenable().addListener(connectionStateListener); if ( buildInitial ) { internalRebuild(); } reset(); } @Override public void close() throws IOException { if ( state.compareAndSet(State.STARTED, State.CLOSED) ) { listeners.clear(); } client.getConnectionStateListenable().removeListener(connectionStateListener); } /** * Return the cache listenable * * @return listenable */ public ListenerContainer getListenable() { Preconditions.checkState(state.get() != State.CLOSED, "Closed"); return listeners; } /** * NOTE: this is a BLOCKING method. Completely rebuild the internal cache by querying * for all needed data WITHOUT generating any events to send to listeners. * * @throws Exception errors */ public void rebuild() throws Exception { Preconditions.checkState(state.get() == State.STARTED, "Not started"); internalRebuild(); reset(); } /** * Return the current data. There are no guarantees of accuracy. This is * merely the most recent view of the data. If the node does not exist, * this returns null * * @return data or null */ public ChildData getCurrentData() { return data.get(); } @VisibleForTesting volatile Exchanger rebuildTestExchanger; private void reset() throws Exception { if ( (state.get() == State.STARTED) && isConnected.get() ) { client.checkExists().usingWatcher(watcher).inBackground(backgroundCallback).forPath(path); } } private void internalRebuild() throws Exception { try { Stat stat = new Stat(); byte[] bytes = dataIsCompressed ? client.getData().decompressed().storingStatIn(stat).forPath(path) : client.getData().storingStatIn(stat).forPath(path); data.set(new ChildData(path, stat, bytes)); } catch ( KeeperException.NoNodeException e ) { data.set(null); } } private void processBackgroundResult(CuratorEvent event) throws Exception { switch ( event.getType() ) { case GET_DATA: { if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) { ChildData childData = new ChildData(path, event.getStat(), event.getData()); setNewData(childData); } break; } case EXISTS: { if ( event.getResultCode() == KeeperException.Code.NONODE.intValue() ) { setNewData(null); } else if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) { if ( dataIsCompressed ) { client.getData().decompressed().usingWatcher(watcher).inBackground(backgroundCallback).forPath(path); } else { client.getData().usingWatcher(watcher).inBackground(backgroundCallback).forPath(path); } } break; } } } private void setNewData(ChildData newData) throws InterruptedException { ChildData previousData = data.getAndSet(newData); if ( !Objects.equal(previousData, newData) ) { listeners.forEach ( new Function() { @Override public Void apply(NodeCacheListener listener) { try { listener.nodeChanged(); } catch ( Exception e ) { log.error("Calling listener", e); } return null; } } ); if ( rebuildTestExchanger != null ) { try { rebuildTestExchanger.exchange(new Object()); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } } } } } NodeCacheListener.java000066400000000000000000000017621245521677600401500ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; public interface NodeCacheListener { /** * Called when a change has occurred */ public void nodeChanged() throws Exception; } Operation.java000066400000000000000000000016451245521677600365710ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; interface Operation { public void invoke() throws Exception; } PathChildrenCache.java000066400000000000000000000707421245521677600401260ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.listen.ListenerContainer; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.utils.CloseableExecutorService; import org.apache.curator.utils.EnsurePath; import org.apache.curator.utils.ThreadUtils; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Exchanger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.utils.PathUtils; /** *

A utility that attempts to keep all data from all children of a ZK path locally cached. This class * will watch the ZK path, respond to update/create/delete events, pull down the data, etc. You can * register a listener that will get notified when changes occur.

*

*

IMPORTANT - it's not possible to stay transactionally in sync. Users of this class must * be prepared for false-positives and false-negatives. Additionally, always use the version number * when updating data to avoid overwriting another process' change.

*/ @SuppressWarnings("NullableProblems") public class PathChildrenCache implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework client; private final String path; private final CloseableExecutorService executorService; private final boolean cacheData; private final boolean dataIsCompressed; private final EnsurePath ensurePath; private final ListenerContainer listeners = new ListenerContainer(); private final ConcurrentMap currentData = Maps.newConcurrentMap(); private final AtomicReference> initialSet = new AtomicReference>(); private final Set operationsQuantizer = Sets.newSetFromMap(Maps.newConcurrentMap()); private final AtomicReference state = new AtomicReference(State.LATENT); private enum State { LATENT, STARTED, CLOSED } private static final ChildData NULL_CHILD_DATA = new ChildData("/", null, null); private static final boolean USE_EXISTS = Boolean.getBoolean("curator-path-children-cache-use-exists"); private volatile Watcher childrenWatcher = new Watcher() { @Override public void process(WatchedEvent event) { offerOperation(new RefreshOperation(PathChildrenCache.this, RefreshMode.STANDARD)); } }; private volatile Watcher dataWatcher = new Watcher() { @Override public void process(WatchedEvent event) { try { if ( event.getType() == Event.EventType.NodeDeleted ) { remove(event.getPath()); } else if ( event.getType() == Event.EventType.NodeDataChanged ) { offerOperation(new GetDataOperation(PathChildrenCache.this, event.getPath())); } } catch ( Exception e ) { handleException(e); } } }; @VisibleForTesting volatile Exchanger rebuildTestExchanger; private volatile ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { handleStateChange(newState); } }; private static final ThreadFactory defaultThreadFactory = ThreadUtils.newThreadFactory("PathChildrenCache"); /** * @param client the client * @param path path to watch * @param mode caching mode * @deprecated use {@link #PathChildrenCache(CuratorFramework, String, boolean)} instead */ @SuppressWarnings("deprecation") public PathChildrenCache(CuratorFramework client, String path, PathChildrenCacheMode mode) { this(client, path, mode != PathChildrenCacheMode.CACHE_PATHS_ONLY, false, new CloseableExecutorService(Executors.newSingleThreadExecutor(defaultThreadFactory), true)); } /** * @param client the client * @param path path to watch * @param mode caching mode * @param threadFactory factory to use when creating internal threads * @deprecated use {@link #PathChildrenCache(CuratorFramework, String, boolean, ThreadFactory)} instead */ @SuppressWarnings("deprecation") public PathChildrenCache(CuratorFramework client, String path, PathChildrenCacheMode mode, ThreadFactory threadFactory) { this(client, path, mode != PathChildrenCacheMode.CACHE_PATHS_ONLY, false, new CloseableExecutorService(Executors.newSingleThreadExecutor(threadFactory), true)); } /** * @param client the client * @param path path to watch * @param cacheData if true, node contents are cached in addition to the stat */ public PathChildrenCache(CuratorFramework client, String path, boolean cacheData) { this(client, path, cacheData, false, new CloseableExecutorService(Executors.newSingleThreadExecutor(defaultThreadFactory), true)); } /** * @param client the client * @param path path to watch * @param cacheData if true, node contents are cached in addition to the stat * @param threadFactory factory to use when creating internal threads */ public PathChildrenCache(CuratorFramework client, String path, boolean cacheData, ThreadFactory threadFactory) { this(client, path, cacheData, false, new CloseableExecutorService(Executors.newSingleThreadExecutor(threadFactory), true)); } /** * @param client the client * @param path path to watch * @param cacheData if true, node contents are cached in addition to the stat * @param dataIsCompressed if true, data in the path is compressed * @param threadFactory factory to use when creating internal threads */ public PathChildrenCache(CuratorFramework client, String path, boolean cacheData, boolean dataIsCompressed, ThreadFactory threadFactory) { this(client, path, cacheData, dataIsCompressed, new CloseableExecutorService(Executors.newSingleThreadExecutor(threadFactory), true)); } /** * @param client the client * @param path path to watch * @param cacheData if true, node contents are cached in addition to the stat * @param dataIsCompressed if true, data in the path is compressed * @param executorService ExecutorService to use for the PathChildrenCache's background thread */ public PathChildrenCache(CuratorFramework client, String path, boolean cacheData, boolean dataIsCompressed, final ExecutorService executorService) { this(client, path, cacheData, dataIsCompressed, new CloseableExecutorService(executorService)); } /** * @param client the client * @param path path to watch * @param cacheData if true, node contents are cached in addition to the stat * @param dataIsCompressed if true, data in the path is compressed * @param executorService Closeable ExecutorService to use for the PathChildrenCache's background thread */ public PathChildrenCache(CuratorFramework client, String path, boolean cacheData, boolean dataIsCompressed, final CloseableExecutorService executorService) { this.client = client; this.path = PathUtils.validatePath(path); this.cacheData = cacheData; this.dataIsCompressed = dataIsCompressed; this.executorService = executorService; ensurePath = client.newNamespaceAwareEnsurePath(path); } /** * Start the cache. The cache is not started automatically. You must call this method. * * @throws Exception errors */ public void start() throws Exception { start(StartMode.NORMAL); } /** * Same as {@link #start()} but gives the option of doing an initial build * * @param buildInitial if true, {@link #rebuild()} will be called before this method * returns in order to get an initial view of the node; otherwise, * the cache will be initialized asynchronously * @throws Exception errors * @deprecated use {@link #start(StartMode)} */ public void start(boolean buildInitial) throws Exception { start(buildInitial ? StartMode.BUILD_INITIAL_CACHE : StartMode.NORMAL); } /** * Method of priming cache on {@link PathChildrenCache#start(StartMode)} */ public enum StartMode { /** * The cache will be primed (in the background) with initial values. * Events for existing and new nodes will be posted. */ NORMAL, /** * The cache will be primed (in the foreground) with initial values. * {@link PathChildrenCache#rebuild()} will be called before * the {@link PathChildrenCache#start(StartMode)} method returns * in order to get an initial view of the node. */ BUILD_INITIAL_CACHE, /** * After cache is primed with initial values (in the background) a * {@link PathChildrenCacheEvent.Type#INITIALIZED} will be posted. */ POST_INITIALIZED_EVENT } /** * Start the cache. The cache is not started automatically. You must call this method. * * @param mode Method for priming the cache * @throws Exception errors */ public void start(StartMode mode) throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "already started"); mode = Preconditions.checkNotNull(mode, "mode cannot be null"); client.getConnectionStateListenable().addListener(connectionStateListener); switch ( mode ) { case NORMAL: { offerOperation(new RefreshOperation(this, RefreshMode.STANDARD)); break; } case BUILD_INITIAL_CACHE: { rebuild(); break; } case POST_INITIALIZED_EVENT: { initialSet.set(Maps.newConcurrentMap()); offerOperation(new RefreshOperation(this, RefreshMode.POST_INITIALIZED)); break; } } } /** * NOTE: this is a BLOCKING method. Completely rebuild the internal cache by querying * for all needed data WITHOUT generating any events to send to listeners. * * @throws Exception errors */ public void rebuild() throws Exception { Preconditions.checkState(!executorService.isShutdown(), "cache has been closed"); ensurePath.ensure(client.getZookeeperClient()); clear(); List children = client.getChildren().forPath(path); for ( String child : children ) { String fullPath = ZKPaths.makePath(path, child); internalRebuildNode(fullPath); if ( rebuildTestExchanger != null ) { rebuildTestExchanger.exchange(new Object()); } } // this is necessary so that any updates that occurred while rebuilding are taken offerOperation(new RefreshOperation(this, RefreshMode.FORCE_GET_DATA_AND_STAT)); } /** * NOTE: this is a BLOCKING method. Rebuild the internal cache for the given node by querying * for all needed data WITHOUT generating any events to send to listeners. * * @param fullPath full path of the node to rebuild * @throws Exception errors */ public void rebuildNode(String fullPath) throws Exception { Preconditions.checkArgument(ZKPaths.getPathAndNode(fullPath).getPath().equals(path), "Node is not part of this cache: " + fullPath); Preconditions.checkState(!executorService.isShutdown(), "cache has been closed"); ensurePath.ensure(client.getZookeeperClient()); internalRebuildNode(fullPath); // this is necessary so that any updates that occurred while rebuilding are taken // have to rebuild entire tree in case this node got deleted in the interim offerOperation(new RefreshOperation(this, RefreshMode.FORCE_GET_DATA_AND_STAT)); } /** * Close/end the cache * * @throws IOException errors */ @Override public void close() throws IOException { if ( state.compareAndSet(State.STARTED, State.CLOSED) ) { client.getConnectionStateListenable().removeListener(connectionStateListener); listeners.clear(); executorService.close(); client.clearWatcherReferences(childrenWatcher); client.clearWatcherReferences(dataWatcher); // TODO // This seems to enable even more GC - I'm not sure why yet - it // has something to do with Guava's cache and circular references connectionStateListener = null; childrenWatcher = null; dataWatcher = null; } } /** * Return the cache listenable * * @return listenable */ public ListenerContainer getListenable() { return listeners; } /** * Return the current data. There are no guarantees of accuracy. This is * merely the most recent view of the data. The data is returned in sorted order. * * @return list of children and data */ public List getCurrentData() { return ImmutableList.copyOf(Sets.newTreeSet(currentData.values())); } /** * Return the current data for the given path. There are no guarantees of accuracy. This is * merely the most recent view of the data. If there is no child with that path, null * is returned. * * @param fullPath full path to the node to check * @return data or null */ public ChildData getCurrentData(String fullPath) { return currentData.get(fullPath); } /** * As a memory optimization, you can clear the cached data bytes for a node. Subsequent * calls to {@link ChildData#getData()} for this node will return null. * * @param fullPath the path of the node to clear */ public void clearDataBytes(String fullPath) { clearDataBytes(fullPath, -1); } /** * As a memory optimization, you can clear the cached data bytes for a node. Subsequent * calls to {@link ChildData#getData()} for this node will return null. * * @param fullPath the path of the node to clear * @param ifVersion if non-negative, only clear the data if the data's version matches this version * @return true if the data was cleared */ public boolean clearDataBytes(String fullPath, int ifVersion) { ChildData data = currentData.get(fullPath); if ( data != null ) { if ( (ifVersion < 0) || (ifVersion == data.getStat().getVersion()) ) { data.clearData(); return true; } } return false; } /** * Clear out current data and begin a new query on the path * * @throws Exception errors */ public void clearAndRefresh() throws Exception { currentData.clear(); offerOperation(new RefreshOperation(this, RefreshMode.STANDARD)); } /** * Clears the current data without beginning a new query and without generating any events * for listeners. */ public void clear() { currentData.clear(); } enum RefreshMode { STANDARD, FORCE_GET_DATA_AND_STAT, POST_INITIALIZED } void refresh(final RefreshMode mode) throws Exception { ensurePath.ensure(client.getZookeeperClient()); final BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { if (PathChildrenCache.this.state.get().equals(State.CLOSED)) { // This ship is closed, don't handle the callback return; } if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) { processChildren(event.getChildren(), mode); } } }; client.getChildren().usingWatcher(childrenWatcher).inBackground(callback).forPath(path); } void callListeners(final PathChildrenCacheEvent event) { listeners.forEach ( new Function() { @Override public Void apply(PathChildrenCacheListener listener) { try { listener.childEvent(client, event); } catch ( Exception e ) { handleException(e); } return null; } } ); } void getDataAndStat(final String fullPath) throws Exception { BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { applyNewData(fullPath, event.getResultCode(), event.getStat(), cacheData ? event.getData() : null); } }; if ( USE_EXISTS && !cacheData ) { client.checkExists().usingWatcher(dataWatcher).inBackground(callback).forPath(fullPath); } else { // always use getData() instead of exists() to avoid leaving unneeded watchers which is a type of resource leak if ( dataIsCompressed && cacheData ) { client.getData().decompressed().usingWatcher(dataWatcher).inBackground(callback).forPath(fullPath); } else { client.getData().usingWatcher(dataWatcher).inBackground(callback).forPath(fullPath); } } } /** * Default behavior is just to log the exception * * @param e the exception */ protected void handleException(Throwable e) { log.error("", e); } @VisibleForTesting protected void remove(String fullPath) { ChildData data = currentData.remove(fullPath); if ( data != null ) { offerOperation(new EventOperation(this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CHILD_REMOVED, data))); } Map localInitialSet = initialSet.get(); if ( localInitialSet != null ) { localInitialSet.remove(fullPath); maybeOfferInitializedEvent(localInitialSet); } } private void internalRebuildNode(String fullPath) throws Exception { if ( cacheData ) { try { Stat stat = new Stat(); byte[] bytes = dataIsCompressed ? client.getData().decompressed().storingStatIn(stat).forPath(fullPath) : client.getData().storingStatIn(stat).forPath(fullPath); currentData.put(fullPath, new ChildData(fullPath, stat, bytes)); } catch ( KeeperException.NoNodeException ignore ) { // node no longer exists - remove it currentData.remove(fullPath); } } else { Stat stat = client.checkExists().forPath(fullPath); if ( stat != null ) { currentData.put(fullPath, new ChildData(fullPath, stat, null)); } else { // node no longer exists - remove it currentData.remove(fullPath); } } } private void handleStateChange(ConnectionState newState) { switch ( newState ) { case SUSPENDED: { offerOperation(new EventOperation(this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CONNECTION_SUSPENDED, null))); break; } case LOST: { offerOperation(new EventOperation(this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CONNECTION_LOST, null))); break; } case RECONNECTED: { try { offerOperation(new RefreshOperation(this, RefreshMode.FORCE_GET_DATA_AND_STAT)); offerOperation(new EventOperation(this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED, null))); } catch ( Exception e ) { handleException(e); } break; } } } private void processChildren(List children, RefreshMode mode) throws Exception { Set removedNodes = Sets.newHashSet(currentData.keySet()); for ( String child : children ) { removedNodes.remove(ZKPaths.makePath(path, child)); } for ( String fullPath : removedNodes ) { remove(fullPath); } for ( String name : children ) { String fullPath = ZKPaths.makePath(path, name); if ( (mode == RefreshMode.FORCE_GET_DATA_AND_STAT) || !currentData.containsKey(fullPath) ) { getDataAndStat(fullPath); } updateInitialSet(name, NULL_CHILD_DATA); } maybeOfferInitializedEvent(initialSet.get()); } private void applyNewData(String fullPath, int resultCode, Stat stat, byte[] bytes) { if ( resultCode == KeeperException.Code.OK.intValue() ) // otherwise - node must have dropped or something - we should be getting another event { ChildData data = new ChildData(fullPath, stat, bytes); ChildData previousData = currentData.put(fullPath, data); if ( previousData == null ) // i.e. new { offerOperation(new EventOperation(this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CHILD_ADDED, data))); } else if ( previousData.getStat().getVersion() != stat.getVersion() ) { offerOperation(new EventOperation(this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CHILD_UPDATED, data))); } updateInitialSet(ZKPaths.getNodeFromPath(fullPath), data); } } private void updateInitialSet(String name, ChildData data) { Map localInitialSet = initialSet.get(); if ( localInitialSet != null ) { localInitialSet.put(name, data); maybeOfferInitializedEvent(localInitialSet); } } private void maybeOfferInitializedEvent(Map localInitialSet) { if ( !hasUninitialized(localInitialSet) ) { // all initial children have been processed - send initialized message if ( initialSet.getAndSet(null) != null ) // avoid edge case - don't send more than 1 INITIALIZED event { final List children = ImmutableList.copyOf(localInitialSet.values()); PathChildrenCacheEvent event = new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.INITIALIZED, null) { @Override public List getInitialData() { return children; } }; offerOperation(new EventOperation(this, event)); } } } private boolean hasUninitialized(Map localInitialSet) { if ( localInitialSet == null ) { return false; } Map uninitializedChildren = Maps.filterValues ( localInitialSet, new Predicate() { @Override public boolean apply(ChildData input) { return (input == NULL_CHILD_DATA); // check against ref intentional } } ); return (uninitializedChildren.size() != 0); } void offerOperation(final Operation operation) { if ( operationsQuantizer.add(operation) ) { submitToExecutor ( new Runnable() { @Override public void run() { try { operationsQuantizer.remove(operation); operation.invoke(); } catch ( InterruptedException e ) { //We expect to get interrupted during shutdown, //so just ignore these events if ( state.get() != State.CLOSED ) { handleException(e); } Thread.currentThread().interrupt(); } catch ( Exception e ) { handleException(e); } } } ); } } /** * Submits a runnable to the executor. *

* This method is synchronized because it has to check state about whether this instance is still open. Without this check * there is a race condition with the dataWatchers that get set. Even after this object is closed() it can still be * called by those watchers, because the close() method cannot actually disable the watcher. *

* The synchronization overhead should be minimal if non-existant as this is generally only called from the * ZK client thread and will only contend if close() is called in parallel with an update, and that's the exact state * we want to protect from. * * @param command The runnable to run */ private synchronized void submitToExecutor(final Runnable command) { if ( state.get() == State.STARTED ) { executorService.submit(command); } } } PathChildrenCacheEvent.java000066400000000000000000000121311245521677600411140ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; import org.apache.curator.framework.state.ConnectionState; import java.util.List; /** * POJO that abstracts a change to a path */ public class PathChildrenCacheEvent { private final Type type; private final ChildData data; /** * Type of change */ public enum Type { /** * A child was added to the path */ CHILD_ADDED, /** * A child's data was changed */ CHILD_UPDATED, /** * A child was removed from the path */ CHILD_REMOVED, /** * Called when the connection has changed to {@link ConnectionState#SUSPENDED} * * This is exposed so that users of the class can be notified of issues that *might* affect normal operation. * The PathChildrenCache is written such that listeners are not expected to do anything special on this * event, except for those people who want to cause some application-specific logic to fire when this occurs. * While the connection is down, the PathChildrenCache will continue to have its state from before it lost * the connection and after the connection is restored, the PathChildrenCache will emit normal child events * for all of the adds, deletes and updates that happened during the time that it was disconnected. */ CONNECTION_SUSPENDED, /** * Called when the connection has changed to {@link ConnectionState#RECONNECTED} * * This is exposed so that users of the class can be notified of issues that *might* affect normal operation. * The PathChildrenCache is written such that listeners are not expected to do anything special on this * event, except for those people who want to cause some application-specific logic to fire when this occurs. * While the connection is down, the PathChildrenCache will continue to have its state from before it lost * the connection and after the connection is restored, the PathChildrenCache will emit normal child events * for all of the adds, deletes and updates that happened during the time that it was disconnected. */ CONNECTION_RECONNECTED, /** * Called when the connection has changed to {@link ConnectionState#LOST} * * This is exposed so that users of the class can be notified of issues that *might* affect normal operation. * The PathChildrenCache is written such that listeners are not expected to do anything special on this * event, except for those people who want to cause some application-specific logic to fire when this occurs. * While the connection is down, the PathChildrenCache will continue to have its state from before it lost * the connection and after the connection is restored, the PathChildrenCache will emit normal child events * for all of the adds, deletes and updates that happened during the time that it was disconnected. */ CONNECTION_LOST, /** * Posted when {@link PathChildrenCache#start(PathChildrenCache.StartMode)} is called * with {@link PathChildrenCache.StartMode#POST_INITIALIZED_EVENT}. This * event signals that the initial cache has been populated. */ INITIALIZED } /** * @param type event type * @param data event data or null */ public PathChildrenCacheEvent(Type type, ChildData data) { this.type = type; this.data = data; } /** * @return change type */ public Type getType() { return type; } /** * @return the node's data */ public ChildData getData() { return data; } /** * Special purpose method. When an {@link Type#INITIALIZED} * event is received, you can call this method to * receive the initial state of the cache. * * @return initial state of cache for {@link Type#INITIALIZED} events. Otherwise, null. */ public List getInitialData() { return null; } @Override public String toString() { return "PathChildrenCacheEvent{" + "type=" + type + ", data=" + data + '}'; } } PathChildrenCacheListener.java000066400000000000000000000024071245521677600416250ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; import org.apache.curator.framework.CuratorFramework; /** * Listener for PathChildrenCache changes */ public interface PathChildrenCacheListener { /** * Called when a change has occurred * * @param client the client * @param event describes the change * @throws Exception errors */ public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception; } PathChildrenCacheMode.java000066400000000000000000000034111245521677600407200ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; import org.apache.curator.framework.CuratorFramework; import java.util.concurrent.ThreadFactory; /** * Controls which data is cached * * @deprecated no longer used. Instead use either {@link PathChildrenCache#PathChildrenCache(CuratorFramework, String, boolean)} * or {@link PathChildrenCache#PathChildrenCache(CuratorFramework, String, boolean, ThreadFactory)} */ public enum PathChildrenCacheMode { /** * The cache will hold all the children, the data for each child node * and the stat for each child node */ CACHE_DATA_AND_STAT, /** * The cache will hold all the children and the data for each child node. * {@link ChildData#getStat()} will return null. */ CACHE_DATA, /** * The cache will hold only the children path names. * {@link ChildData#getStat()} and {@link ChildData#getData()} will both return null. */ CACHE_PATHS_ONLY } RefreshOperation.java000066400000000000000000000035301245521677600401030ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; class RefreshOperation implements Operation { private final PathChildrenCache cache; private final PathChildrenCache.RefreshMode mode; RefreshOperation(PathChildrenCache cache, PathChildrenCache.RefreshMode mode) { this.cache = cache; this.mode = mode; } @Override public void invoke() throws Exception { cache.refresh(mode); } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } RefreshOperation that = (RefreshOperation)o; //noinspection RedundantIfStatement if ( mode != that.mode ) { return false; } return true; } @Override public int hashCode() { return mode.hashCode(); } @Override public String toString() { return "RefreshOperation(" + mode + "){}"; } } TreeCache.java000066400000000000000000000661251245521677600364600ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.UnhandledErrorListener; import org.apache.curator.framework.listen.Listenable; import org.apache.curator.framework.listen.ListenerContainer; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.utils.CloseableExecutorService; import org.apache.curator.utils.ThreadUtils; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import static com.google.common.base.Preconditions.checkNotNull; import static org.apache.curator.utils.PathUtils.validatePath; /** *

A utility that attempts to keep all data from all children of a ZK path locally cached. This class * will watch the ZK path, respond to update/create/delete events, pull down the data, etc. You can * register a listener that will get notified when changes occur.

*

*

IMPORTANT - it's not possible to stay transactionally in sync. Users of this class must * be prepared for false-positives and false-negatives. Additionally, always use the version number * when updating data to avoid overwriting another process' change.

*/ public class TreeCache implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(TreeCache.class); public static final class Builder { private final CuratorFramework client; private final String path; private boolean cacheData = true; private boolean dataIsCompressed = false; private CloseableExecutorService executorService = null; private int maxDepth = Integer.MAX_VALUE; private Builder(CuratorFramework client, String path) { this.client = checkNotNull(client); this.path = validatePath(path); } /** * Builds the {@link TreeCache} based on configured values. */ public TreeCache build() { CloseableExecutorService executor = executorService; if ( executor == null ) { executor = new CloseableExecutorService(Executors.newSingleThreadExecutor(defaultThreadFactory)); } return new TreeCache(client, path, cacheData, dataIsCompressed, maxDepth, executor); } /** * Sets whether or not to cache byte data per node; default {@code true}. */ public Builder setCacheData(boolean cacheData) { this.cacheData = cacheData; return this; } /** * Sets whether or to decompress node data; default {@code false}. */ public Builder setDataIsCompressed(boolean dataIsCompressed) { this.dataIsCompressed = dataIsCompressed; return this; } /** * Sets the executor to publish events; a default executor will be created if not specified. */ public Builder setExecutor(ThreadFactory threadFactory) { return setExecutor(new CloseableExecutorService(Executors.newSingleThreadExecutor(threadFactory))); } /** * Sets the executor to publish events; a default executor will be created if not specified. */ public Builder setExecutor(ExecutorService executorService) { if ( executorService instanceof CloseableExecutorService ) { return setExecutor((CloseableExecutorService)executorService); } else { return setExecutor(new CloseableExecutorService(executorService)); } } /** * Sets the executor to publish events; a default executor will be created if not specified. */ public Builder setExecutor(CloseableExecutorService executorService) { this.executorService = checkNotNull(executorService); return this; } /** * Sets the maximum depth to explore/watch. A {@code maxDepth} of {@code 0} will watch only * the root node (like {@link NodeCache}); a {@code maxDepth} of {@code 1} will watch the * root node and its immediate children (kind of like {@link PathChildrenCache}. * Default: {@code Integer.MAX_VALUE} */ public Builder setMaxDepth(int maxDepth) { this.maxDepth = maxDepth; return this; } } /** * Create a TreeCache builder for the given client and path to configure advanced options. *

* If the client is namespaced, all operations on the resulting TreeCache will be in terms of * the namespace, including all published events. The given path is the root at which the * TreeCache will watch and explore. If no node exists at the given path, the TreeCache will * be initially empty. * * @param client the client to use; may be namespaced * @param path the path to the root node to watch/explore; this path need not actually exist on * the server * @return a new builder */ public static Builder newBuilder(CuratorFramework client, String path) { return new Builder(client, path); } private enum NodeState { PENDING, LIVE, DEAD } private final class TreeNode implements Watcher, BackgroundCallback { final AtomicReference nodeState = new AtomicReference(NodeState.PENDING); final TreeNode parent; final String path; final AtomicReference stat = new AtomicReference(); final AtomicReference data = new AtomicReference(); final AtomicReference> children = new AtomicReference>(); final int depth; TreeNode(String path, TreeNode parent) { this.path = path; this.parent = parent; this.depth = parent == null ? 0 : parent.depth + 1; } private void refresh() throws Exception { if (depth < maxDepth) { outstandingOps.addAndGet(2); doRefreshData(); doRefreshChildren(); } else { refreshData(); } } private void refreshChildren() throws Exception { if (depth < maxDepth) { outstandingOps.incrementAndGet(); doRefreshChildren(); } } private void refreshData() throws Exception { outstandingOps.incrementAndGet(); doRefreshData(); } private void doRefreshChildren() throws Exception { client.getChildren().usingWatcher(this).inBackground(this).forPath(path); } private void doRefreshData() throws Exception { if ( dataIsCompressed ) { client.getData().decompressed().usingWatcher(this).inBackground(this).forPath(path); } else { client.getData().usingWatcher(this).inBackground(this).forPath(path); } } void wasReconnected() throws Exception { refresh(); ConcurrentMap childMap = children.get(); if ( childMap != null ) { for ( TreeNode child : childMap.values() ) { child.wasReconnected(); } } } void wasCreated() throws Exception { refresh(); } void wasDeleted() throws Exception { stat.set(null); data.set(null); client.clearWatcherReferences(this); ConcurrentMap childMap = children.getAndSet(null); if ( childMap != null ) { ArrayList childCopy = new ArrayList(childMap.values()); childMap.clear(); for ( TreeNode child : childCopy ) { child.wasDeleted(); } } if ( treeState.get() == TreeState.CLOSED ) { return; } if ( nodeState.compareAndSet(NodeState.LIVE, NodeState.DEAD) ) { publishEvent(TreeCacheEvent.Type.NODE_REMOVED, path); } if ( parent == null ) { // Root node; use an exist query to watch for existence. client.checkExists().usingWatcher(this).inBackground().forPath(path); } else { // Remove from parent if we're currently a child ConcurrentMap parentChildMap = parent.children.get(); if ( parentChildMap != null ) { parentChildMap.remove(ZKPaths.getNodeFromPath(path), this); } } } @Override public void process(WatchedEvent event) { try { switch ( event.getType() ) { case NodeCreated: Preconditions.checkState(parent == null, "unexpected NodeCreated on non-root node"); wasCreated(); break; case NodeChildrenChanged: refreshChildren(); break; case NodeDataChanged: refreshData(); break; case NodeDeleted: wasDeleted(); break; } } catch ( Exception e ) { handleException(e); } } @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { Stat newStat = event.getStat(); switch ( event.getType() ) { case EXISTS: Preconditions.checkState(parent == null, "unexpected EXISTS on non-root node"); if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) { nodeState.compareAndSet(NodeState.DEAD, NodeState.PENDING); wasCreated(); } else if ( event.getResultCode() == KeeperException.Code.NONODE.intValue() ) { wasDeleted(); } break; case CHILDREN: if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) { Stat oldStat = stat.get(); if ( oldStat != null && oldStat.getMzxid() == newStat.getMzxid() ) { // Only update stat if mzxid is different, otherwise we might obscure // GET_DATA event updates. stat.set(newStat); } if ( event.getChildren().isEmpty() ) { break; } ConcurrentMap childMap = children.get(); if ( childMap == null ) { childMap = Maps.newConcurrentMap(); if ( !children.compareAndSet(null, childMap) ) { childMap = children.get(); } } // Present new children in sorted order for test determinism. List newChildren = new ArrayList(); for ( String child : event.getChildren() ) { if ( !childMap.containsKey(child) ) { newChildren.add(child); } } Collections.sort(newChildren); for ( String child : newChildren ) { String fullPath = ZKPaths.makePath(path, child); TreeNode node = new TreeNode(fullPath, this); if ( childMap.putIfAbsent(child, node) == null ) { node.wasCreated(); } } } else if ( event.getResultCode() == KeeperException.Code.NONODE.intValue() ) { wasDeleted(); } break; case GET_DATA: if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) { if ( cacheData ) { data.set(event.getData()); } Stat oldStat = stat.getAndSet(newStat); if ( nodeState.compareAndSet(NodeState.PENDING, NodeState.LIVE) ) { publishEvent(TreeCacheEvent.Type.NODE_ADDED, new ChildData(event.getPath(), newStat, event.getData())); } else { if ( oldStat == null || oldStat.getMzxid() != newStat.getMzxid() ) { publishEvent(TreeCacheEvent.Type.NODE_UPDATED, new ChildData(event.getPath(), newStat, event.getData())); } } } else if ( event.getResultCode() == KeeperException.Code.NONODE.intValue() ) { wasDeleted(); } break; default: // An unknown event, probably an error of some sort like connection loss. LOG.info(String.format("Unknown event %s", event)); // Don't produce an initialized event on error; reconnect can fix this. outstandingOps.decrementAndGet(); return; } if ( outstandingOps.decrementAndGet() == 0 ) { if ( isInitialized.compareAndSet(false, true) ) { publishEvent(TreeCacheEvent.Type.INITIALIZED); } } } } private enum TreeState { LATENT, STARTED, CLOSED } /** * Tracks the number of outstanding background requests in flight. The first time this count reaches 0, we publish the initialized event. */ private final AtomicLong outstandingOps = new AtomicLong(0); /** * Have we published the {@link TreeCacheEvent.Type#INITIALIZED} event yet? */ private final AtomicBoolean isInitialized = new AtomicBoolean(false); private final TreeNode root; private final CuratorFramework client; private final CloseableExecutorService executorService; private final boolean cacheData; private final boolean dataIsCompressed; private final int maxDepth; private final ListenerContainer listeners = new ListenerContainer(); private final ListenerContainer errorListeners = new ListenerContainer(); private final AtomicReference treeState = new AtomicReference(TreeState.LATENT); private final ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { handleStateChange(newState); } }; static final ThreadFactory defaultThreadFactory = ThreadUtils.newThreadFactory("TreeCache"); /** * Create a TreeCache for the given client and path with default options. *

* If the client is namespaced, all operations on the resulting TreeCache will be in terms of * the namespace, including all published events. The given path is the root at which the * TreeCache will watch and explore. If no node exists at the given path, the TreeCache will * be initially empty. * * @param client the client to use; may be namespaced * @param path the path to the root node to watch/explore; this path need not actually exist on * the server * @see #newBuilder(CuratorFramework, String) */ public TreeCache(CuratorFramework client, String path) { this(client, path, true, false, Integer.MAX_VALUE, new CloseableExecutorService(Executors.newSingleThreadExecutor(defaultThreadFactory), true)); } /** * @param client the client * @param path path to watch * @param cacheData if true, node contents are cached in addition to the stat * @param dataIsCompressed if true, data in the path is compressed * @param executorService Closeable ExecutorService to use for the TreeCache's background thread */ TreeCache(CuratorFramework client, String path, boolean cacheData, boolean dataIsCompressed, int maxDepth, final CloseableExecutorService executorService) { this.root = new TreeNode(validatePath(path), null); this.client = client; this.cacheData = cacheData; this.dataIsCompressed = dataIsCompressed; this.maxDepth = maxDepth; this.executorService = executorService; } /** * Start the cache. The cache is not started automatically. You must call this method. * * @return this * @throws Exception errors */ public TreeCache start() throws Exception { Preconditions.checkState(treeState.compareAndSet(TreeState.LATENT, TreeState.STARTED), "already started"); client.getConnectionStateListenable().addListener(connectionStateListener); if ( client.getZookeeperClient().isConnected() ) { root.wasCreated(); } return this; } /** * Close/end the cache. */ @Override public void close() { if ( treeState.compareAndSet(TreeState.STARTED, TreeState.CLOSED) ) { client.getConnectionStateListenable().removeListener(connectionStateListener); listeners.clear(); executorService.close(); try { root.wasDeleted(); } catch ( Exception e ) { handleException(e); } } } /** * Return the cache listenable * * @return listenable */ public Listenable getListenable() { return listeners; } /** * Allows catching unhandled errors in asynchornous operations. * * TODO: consider making public. */ @VisibleForTesting Listenable getUnhandledErrorListenable() { return errorListeners; } private TreeNode find(String fullPath) { if ( !fullPath.startsWith(root.path) ) { return null; } TreeNode current = root; if ( fullPath.length() > root.path.length() ) { if ( root.path.length() > 1 ) { fullPath = fullPath.substring(root.path.length()); } List split = ZKPaths.split(fullPath); for ( String part : split ) { ConcurrentMap map = current.children.get(); if ( map == null ) { return null; } current = map.get(part); if ( current == null ) { return null; } } } return current; } /** * Return the current set of children at the given path, mapped by child name. There are no * guarantees of accuracy; this is merely the most recent view of the data. If there is no * node at this path, {@code null} is returned. * * @param fullPath full path to the node to check * @return a possibly-empty list of children if the node is alive, or null */ public Map getCurrentChildren(String fullPath) { TreeNode node = find(fullPath); if ( node == null || node.nodeState.get() != NodeState.LIVE ) { return null; } ConcurrentMap map = node.children.get(); Map result; if ( map == null ) { result = ImmutableMap.of(); } else { ImmutableMap.Builder builder = ImmutableMap.builder(); for ( Map.Entry entry : map.entrySet() ) { TreeNode childNode = entry.getValue(); ChildData childData = new ChildData(childNode.path, childNode.stat.get(), childNode.data.get()); // Double-check liveness after retreiving data. if ( childNode.nodeState.get() == NodeState.LIVE ) { builder.put(entry.getKey(), childData); } } result = builder.build(); } // Double-check liveness after retreiving children. return node.nodeState.get() == NodeState.LIVE ? result : null; } /** * Return the current data for the given path. There are no guarantees of accuracy. This is * merely the most recent view of the data. If there is no node at the given path, * {@code null} is returned. * * @param fullPath full path to the node to check * @return data if the node is alive, or null */ public ChildData getCurrentData(String fullPath) { TreeNode node = find(fullPath); if ( node == null || node.nodeState.get() != NodeState.LIVE ) { return null; } ChildData result = new ChildData(node.path, node.stat.get(), node.data.get()); // Double-check liveness after retreiving data. return node.nodeState.get() == NodeState.LIVE ? result : null; } private void callListeners(final TreeCacheEvent event) { listeners.forEach(new Function() { @Override public Void apply(TreeCacheListener listener) { try { listener.childEvent(client, event); } catch ( Exception e ) { handleException(e); } return null; } }); } /** * Send an exception to any listeners, or else log the error if there are none. */ private void handleException(final Throwable e) { if ( errorListeners.size() == 0 ) { LOG.error("", e); } else { errorListeners.forEach(new Function() { @Override public Void apply(UnhandledErrorListener listener) { try { listener.unhandledError("", e); } catch ( Exception e ) { LOG.error("Exception handling exception", e); } return null; } }); } } private void handleStateChange(ConnectionState newState) { switch ( newState ) { case SUSPENDED: publishEvent(TreeCacheEvent.Type.CONNECTION_SUSPENDED); break; case LOST: publishEvent(TreeCacheEvent.Type.CONNECTION_LOST); break; case CONNECTED: try { root.wasCreated(); } catch ( Exception e ) { handleException(e); } break; case RECONNECTED: try { root.wasReconnected(); publishEvent(TreeCacheEvent.Type.CONNECTION_RECONNECTED); } catch ( Exception e ) { handleException(e); } break; } } private void publishEvent(TreeCacheEvent.Type type) { publishEvent(new TreeCacheEvent(type, null)); } private void publishEvent(TreeCacheEvent.Type type, String path) { publishEvent(new TreeCacheEvent(type, new ChildData(path, null, null))); } private void publishEvent(TreeCacheEvent.Type type, ChildData data) { publishEvent(new TreeCacheEvent(type, data)); } private void publishEvent(final TreeCacheEvent event) { if ( treeState.get() != TreeState.CLOSED ) { executorService.submit(new Runnable() { @Override public void run() { { try { callListeners(event); } catch ( Exception e ) { handleException(e); } } } }); } } } TreeCacheEvent.java000066400000000000000000000122421245521677600374510ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; /** * POJO that abstracts a change to a path */ public class TreeCacheEvent { private final Type type; private final ChildData data; /** * Type of change */ public enum Type { /** * A node was added. */ NODE_ADDED, /** * A node's data was changed */ NODE_UPDATED, /** * A node was removed from the tree */ NODE_REMOVED, /** * Called when the connection has changed to {@link org.apache.curator.framework.state.ConnectionState#SUSPENDED} *

* This is exposed so that users of the class can be notified of issues that *might* affect normal operation. * The TreeCache is written such that listeners are not expected to do anything special on this * event, except for those people who want to cause some application-specific logic to fire when this occurs. * While the connection is down, the TreeCache will continue to have its state from before it lost * the connection and after the connection is restored, the TreeCache will emit normal child events * for all of the adds, deletes and updates that happened during the time that it was disconnected. *

*/ CONNECTION_SUSPENDED, /** * Called when the connection has changed to {@link org.apache.curator.framework.state.ConnectionState#RECONNECTED} *

* This is exposed so that users of the class can be notified of issues that *might* affect normal operation. * The TreeCache is written such that listeners are not expected to do anything special on this * event, except for those people who want to cause some application-specific logic to fire when this occurs. * While the connection is down, the TreeCache will continue to have its state from before it lost * the connection and after the connection is restored, the TreeCache will emit normal child events * for all of the adds, deletes and updates that happened during the time that it was disconnected. *

*/ CONNECTION_RECONNECTED, /** * Called when the connection has changed to {@link org.apache.curator.framework.state.ConnectionState#LOST} *

* This is exposed so that users of the class can be notified of issues that *might* affect normal operation. * The TreeCache is written such that listeners are not expected to do anything special on this * event, except for those people who want to cause some application-specific logic to fire when this occurs. * While the connection is down, the TreeCache will continue to have its state from before it lost * the connection and after the connection is restored, the TreeCache will emit normal child events * for all of the adds, deletes and updates that happened during the time that it was disconnected. *

*/ CONNECTION_LOST, /** * Posted after the initial cache has been fully populated. *

* On startup, the cache synchronizes its internal * state with the server, publishing a series of {@link #NODE_ADDED} events as new nodes are discovered. Once * the cachehas been fully synchronized, this {@link #INITIALIZED} this event is published. All events * published after this event represent actual server-side mutations. *

* Note: because the initial population is inherently asynchronous, so it's possible to observe server-side changes * (such as a {@link #NODE_UPDATED}) prior to this event being published. *

*/ INITIALIZED } /** * @param type event type * @param data event data or null */ public TreeCacheEvent(Type type, ChildData data) { this.type = type; this.data = data; } /** * @return change type */ public Type getType() { return type; } /** * @return the node's data */ public ChildData getData() { return data; } @Override public String toString() { return TreeCacheEvent.class.getSimpleName() + "{" + "type=" + type + ", data=" + data + '}'; } } TreeCacheListener.java000066400000000000000000000023651245521677600401620ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; import org.apache.curator.framework.CuratorFramework; /** * Listener for {@link TreeCache} changes */ public interface TreeCacheListener { /** * Called when a change has occurred * * @param client the client * @param event describes the change * @throws Exception errors */ public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception; } 000077500000000000000000000000001245521677600341515ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leaderCancelLeadershipException.java000066400000000000000000000032511245521677600420620ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.leader; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.state.ConnectionState; /** * When thrown from {@link LeaderSelectorListener#stateChanged(CuratorFramework, ConnectionState)}, will * cause {@link LeaderSelector#interruptLeadership()} to get called. IMPORTANT: this is only supported * when thrown from {@link LeaderSelectorListener#stateChanged(CuratorFramework, ConnectionState)}. */ public class CancelLeadershipException extends RuntimeException { public CancelLeadershipException() { } public CancelLeadershipException(String message) { super(message); } public CancelLeadershipException(String message, Throwable cause) { super(message, cause); } public CancelLeadershipException(Throwable cause) { super(cause); } } LeaderLatch.java000066400000000000000000000547271245521677600372030ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.leader; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Preconditions; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.listen.ListenerContainer; import org.apache.curator.framework.recipes.AfterConnectionEstablished; import org.apache.curator.framework.recipes.locks.LockInternals; import org.apache.curator.framework.recipes.locks.LockInternalsSorter; import org.apache.curator.framework.recipes.locks.StandardLockInternalsDriver; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.EOFException; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.utils.PathUtils; /** *

* Abstraction to select a "leader" amongst multiple contenders in a group of JMVs connected to * a Zookeeper cluster. If a group of N thread/processes contend for leadership one will * randomly be assigned leader until it releases leadership at which time another one from the * group will randomly be chosen *

*/ public class LeaderLatch implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework client; private final String latchPath; private final String id; private final AtomicReference state = new AtomicReference(State.LATENT); private final AtomicBoolean hasLeadership = new AtomicBoolean(false); private final AtomicReference ourPath = new AtomicReference(); private final ListenerContainer listeners = new ListenerContainer(); private final CloseMode closeMode; private final AtomicReference> startTask = new AtomicReference>(); private final ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { handleStateChange(newState); } }; private static final String LOCK_NAME = "latch-"; private static final LockInternalsSorter sorter = new LockInternalsSorter() { @Override public String fixForSorting(String str, String lockName) { return StandardLockInternalsDriver.standardFixForSorting(str, lockName); } }; public enum State { LATENT, STARTED, CLOSED } /** * How to handle listeners when the latch is closed */ public enum CloseMode { /** * When the latch is closed, listeners will *not* be notified (default behavior) */ SILENT, /** * When the latch is closed, listeners *will* be notified */ NOTIFY_LEADER } /** * @param client the client * @param latchPath the path for this leadership group */ public LeaderLatch(CuratorFramework client, String latchPath) { this(client, latchPath, "", CloseMode.SILENT); } /** * @param client the client * @param latchPath the path for this leadership group * @param id participant ID */ public LeaderLatch(CuratorFramework client, String latchPath, String id) { this(client, latchPath, id, CloseMode.SILENT); } /** * @param client the client * @param latchPath the path for this leadership group * @param id participant ID * @param closeMode behaviour of listener on explicit close. */ public LeaderLatch(CuratorFramework client, String latchPath, String id, CloseMode closeMode) { this.client = Preconditions.checkNotNull(client, "client cannot be null"); this.latchPath = PathUtils.validatePath(latchPath); this.id = Preconditions.checkNotNull(id, "id cannot be null"); this.closeMode = Preconditions.checkNotNull(closeMode, "closeMode cannot be null"); } /** * Add this instance to the leadership election and attempt to acquire leadership. * * @throws Exception errors */ public void start() throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); startTask.set(AfterConnectionEstablished.execute(client, new Runnable() { @Override public void run() { try { internalStart(); } finally { startTask.set(null); } } })); } /** * Remove this instance from the leadership election. If this instance is the leader, leadership * is released. IMPORTANT: the only way to release leadership is by calling close(). All LeaderLatch * instances must eventually be closed. * * @throws IOException errors */ @Override public void close() throws IOException { close(closeMode); } /** * Remove this instance from the leadership election. If this instance is the leader, leadership * is released. IMPORTANT: the only way to release leadership is by calling close(). All LeaderLatch * instances must eventually be closed. * * @param closeMode allows the default close mode to be overridden at the time the latch is closed. * @throws IOException errors */ public synchronized void close(CloseMode closeMode) throws IOException { Preconditions.checkState(state.compareAndSet(State.STARTED, State.CLOSED), "Already closed or has not been started"); Preconditions.checkNotNull(closeMode, "closeMode cannot be null"); cancelStartTask(); try { setNode(null); } catch ( Exception e ) { throw new IOException(e); } finally { client.getConnectionStateListenable().removeListener(listener); switch ( closeMode ) { case NOTIFY_LEADER: { setLeadership(false); listeners.clear(); break; } default: { listeners.clear(); setLeadership(false); break; } } } } @VisibleForTesting protected boolean cancelStartTask() { Future localStartTask = startTask.getAndSet(null); if ( localStartTask != null ) { localStartTask.cancel(true); return true; } return false; } /** * Attaches a listener to this LeaderLatch *

* Attaching the same listener multiple times is a noop from the second time on. *

* All methods for the listener are run using the provided Executor. It is common to pass in a single-threaded * executor so that you can be certain that listener methods are called in sequence, but if you are fine with * them being called out of order you are welcome to use multiple threads. *

* * @param listener the listener to attach */ public void addListener(LeaderLatchListener listener) { listeners.addListener(listener); } /** * Attaches a listener to this LeaderLatch *

* Attaching the same listener multiple times is a noop from the second time on. *

* All methods for the listener are run using the provided Executor. It is common to pass in a single-threaded * executor so that you can be certain that listener methods are called in sequence, but if you are fine with * them being called out of order you are welcome to use multiple threads. *

* * @param listener the listener to attach * @param executor An executor to run the methods for the listener on. */ public void addListener(LeaderLatchListener listener, Executor executor) { listeners.addListener(listener, executor); } /** * Removes a given listener from this LeaderLatch * * @param listener the listener to remove */ public void removeListener(LeaderLatchListener listener) { listeners.removeListener(listener); } /** *

Causes the current thread to wait until this instance acquires leadership * unless the thread is {@linkplain Thread#interrupt interrupted} or {@linkplain #close() closed}.

*

If this instance already is the leader then this method returns immediately.

*

*

Otherwise the current * thread becomes disabled for thread scheduling purposes and lies * dormant until one of three things happen:

*
    *
  • This instance becomes the leader
  • *
  • Some other thread {@linkplain Thread#interrupt interrupts} * the current thread
  • *
  • The instance is {@linkplain #close() closed}
  • *
*

If the current thread:

*
    *
  • has its interrupted status set on entry to this method; or *
  • is {@linkplain Thread#interrupt interrupted} while waiting, *
*

then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared.

* * @throws InterruptedException if the current thread is interrupted * while waiting * @throws EOFException if the instance is {@linkplain #close() closed} * while waiting */ public void await() throws InterruptedException, EOFException { synchronized(this) { while ( (state.get() == State.STARTED) && !hasLeadership.get() ) { wait(); } } if ( state.get() != State.STARTED ) { throw new EOFException(); } } /** *

Causes the current thread to wait until this instance acquires leadership * unless the thread is {@linkplain Thread#interrupt interrupted}, * the specified waiting time elapses or the instance is {@linkplain #close() closed}.

*

*

If this instance already is the leader then this method returns immediately * with the value {@code true}.

*

*

Otherwise the current * thread becomes disabled for thread scheduling purposes and lies * dormant until one of four things happen:

*
    *
  • This instance becomes the leader
  • *
  • Some other thread {@linkplain Thread#interrupt interrupts} * the current thread
  • *
  • The specified waiting time elapses.
  • *
  • The instance is {@linkplain #close() closed}
  • *
*

*

If the current thread:

*
    *
  • has its interrupted status set on entry to this method; or *
  • is {@linkplain Thread#interrupt interrupted} while waiting, *
*

then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared.

*

*

If the specified waiting time elapses or the instance is {@linkplain #close() closed} * then the value {@code false} is returned. If the time is less than or equal to zero, the method * will not wait at all.

* * @param timeout the maximum time to wait * @param unit the time unit of the {@code timeout} argument * @return {@code true} if the count reached zero and {@code false} * if the waiting time elapsed before the count reached zero or the instances was closed * @throws InterruptedException if the current thread is interrupted * while waiting */ public boolean await(long timeout, TimeUnit unit) throws InterruptedException { long waitNanos = TimeUnit.NANOSECONDS.convert(timeout, unit); synchronized(this) { while ( (waitNanos > 0) && (state.get() == State.STARTED) && !hasLeadership.get() ) { long startNanos = System.nanoTime(); TimeUnit.NANOSECONDS.timedWait(this, waitNanos); long elapsed = System.nanoTime() - startNanos; waitNanos -= elapsed; } } return hasLeadership(); } /** * Return this instance's participant Id * * @return participant Id */ public String getId() { return id; } /** * Returns this instances current state, this is the only way to verify that the object has been closed before * closing again. If you try to close a latch multiple times, the close() method will throw an * IllegalArgumentException which is often not caught and ignored (CloseableUtils.closeQuietly() only looks for * IOException). * * @return the state of the current instance */ public State getState() { return state.get(); } /** *

* Returns the set of current participants in the leader selection *

*

*

* NOTE - this method polls the ZK server. Therefore it can possibly * return a value that does not match {@link #hasLeadership()} as hasLeadership * uses a local field of the class. *

* * @return participants * @throws Exception ZK errors, interruptions, etc. */ public Collection getParticipants() throws Exception { Collection participantNodes = LockInternals.getParticipantNodes(client, latchPath, LOCK_NAME, sorter); return LeaderSelector.getParticipants(client, participantNodes); } /** *

* Return the id for the current leader. If for some reason there is no * current leader, a dummy participant is returned. *

*

*

* NOTE - this method polls the ZK server. Therefore it can possibly * return a value that does not match {@link #hasLeadership()} as hasLeadership * uses a local field of the class. *

* * @return leader * @throws Exception ZK errors, interruptions, etc. */ public Participant getLeader() throws Exception { Collection participantNodes = LockInternals.getParticipantNodes(client, latchPath, LOCK_NAME, sorter); return LeaderSelector.getLeader(client, participantNodes); } /** * Return true if leadership is currently held by this instance * * @return true/false */ public boolean hasLeadership() { return (state.get() == State.STARTED) && hasLeadership.get(); } @VisibleForTesting volatile CountDownLatch debugResetWaitLatch = null; @VisibleForTesting void reset() throws Exception { setLeadership(false); setNode(null); BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { if ( debugResetWaitLatch != null ) { debugResetWaitLatch.await(); debugResetWaitLatch = null; } if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) { setNode(event.getName()); if ( state.get() == State.CLOSED ) { setNode(null); } else { getChildren(); } } else { log.error("getChildren() failed. rc = " + event.getResultCode()); } } }; client.create().creatingParentsIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).inBackground(callback).forPath(ZKPaths.makePath(latchPath, LOCK_NAME), LeaderSelector.getIdBytes(id)); } private synchronized void internalStart() { if ( state.get() == State.STARTED ) { client.getConnectionStateListenable().addListener(listener); try { reset(); } catch ( Exception e ) { log.error("An error occurred checking resetting leadership.", e); } } } private void checkLeadership(List children) throws Exception { final String localOurPath = ourPath.get(); List sortedChildren = LockInternals.getSortedChildren(LOCK_NAME, sorter, children); int ourIndex = (localOurPath != null) ? sortedChildren.indexOf(ZKPaths.getNodeFromPath(localOurPath)) : -1; if ( ourIndex < 0 ) { log.error("Can't find our node. Resetting. Index: " + ourIndex); reset(); } else if ( ourIndex == 0 ) { setLeadership(true); } else { String watchPath = sortedChildren.get(ourIndex - 1); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { if ( (state.get() == State.STARTED) && (event.getType() == Event.EventType.NodeDeleted) && (localOurPath != null) ) { try { getChildren(); } catch ( Exception ex ) { log.error("An error occurred checking the leadership.", ex); } } } }; BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getResultCode() == KeeperException.Code.NONODE.intValue() ) { // previous node is gone - reset reset(); } } }; // use getData() instead of exists() to avoid leaving unneeded watchers which is a type of resource leak client.getData().usingWatcher(watcher).inBackground(callback).forPath(ZKPaths.makePath(latchPath, watchPath)); } } private void getChildren() throws Exception { BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) { checkLeadership(event.getChildren()); } } }; client.getChildren().inBackground(callback).forPath(ZKPaths.makePath(latchPath, null)); } private void handleStateChange(ConnectionState newState) { switch ( newState ) { default: { // NOP break; } case RECONNECTED: { try { reset(); } catch ( Exception e ) { log.error("Could not reset leader latch", e); setLeadership(false); } break; } case SUSPENDED: case LOST: { setLeadership(false); break; } } } private synchronized void setLeadership(boolean newValue) { boolean oldValue = hasLeadership.getAndSet(newValue); if ( oldValue && !newValue ) { // Lost leadership, was true, now false listeners.forEach(new Function() { @Override public Void apply(LeaderLatchListener listener) { listener.notLeader(); return null; } }); } else if ( !oldValue && newValue ) { // Gained leadership, was false, now true listeners.forEach(new Function() { @Override public Void apply(LeaderLatchListener input) { input.isLeader(); return null; } }); } notifyAll(); } private void setNode(String newValue) throws Exception { String oldPath = ourPath.getAndSet(newValue); if ( oldPath != null ) { client.delete().guaranteed().inBackground().forPath(oldPath); } } } LeaderLatchListener.java000066400000000000000000000040331245521677600406720ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.leader; /** * A LeaderLatchListener can be used to be notified asynchronously about when the state of the LeaderLatch has changed. * * Note that just because you are in the middle of one of these method calls, it does not necessarily mean that * hasLeadership() is the corresponding true/false value. It is possible for the state to change behind the scenes * before these methods get called. The contract is that if that happens, you should see another call to the other * method pretty quickly. */ public interface LeaderLatchListener { /** * This is called when the LeaderLatch's state goes from hasLeadership = false to hasLeadership = true. * * Note that it is possible that by the time this method call happens, hasLeadership has fallen back to false. If * this occurs, you can expect {@link #notLeader()} to also be called. */ public void isLeader(); /** * This is called when the LeaderLatch's state goes from hasLeadership = true to hasLeadership = false. * * Note that it is possible that by the time this method call happens, hasLeadership has become true. If * this occurs, you can expect {@link #isLeader()} to also be called. */ public void notLeader(); } LeaderSelector.java000066400000000000000000000421461245521677600377200ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.leader; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.utils.CloseableExecutorService; import org.apache.curator.utils.ThreadUtils; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.List; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.utils.PathUtils; /** *

* Abstraction to select a "leader" amongst multiple contenders in a group of JMVs connected * to a Zookeeper cluster. If a group of N thread/processes contends for leadership, one will * be assigned leader until it releases leadership at which time another one from the group will * be chosen. *

*

* Note that this class uses an underlying {@link InterProcessMutex} and as a result leader * election is "fair" - each user will become leader in the order originally requested * (from ZK's point of view). *

*/ public class LeaderSelector implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework client; private final LeaderSelectorListener listener; private final CloseableExecutorService executorService; private final InterProcessMutex mutex; private final AtomicReference state = new AtomicReference(State.LATENT); private final AtomicBoolean autoRequeue = new AtomicBoolean(false); private final AtomicReference> ourTask = new AtomicReference>(null); private volatile boolean hasLeadership; private volatile String id = ""; @VisibleForTesting volatile CountDownLatch debugLeadershipLatch = null; volatile CountDownLatch debugLeadershipWaitLatch = null; private enum State { LATENT, STARTED, CLOSED } // guarded by synchronization private boolean isQueued = false; private static final ThreadFactory defaultThreadFactory = ThreadUtils.newThreadFactory("LeaderSelector"); /** * @param client the client * @param leaderPath the path for this leadership group * @param listener listener */ public LeaderSelector(CuratorFramework client, String leaderPath, LeaderSelectorListener listener) { this(client, leaderPath, new CloseableExecutorService(Executors.newSingleThreadExecutor(defaultThreadFactory), true), listener); } /** * @param client the client * @param leaderPath the path for this leadership group * @param threadFactory factory to use for making internal threads * @param executor the executor to run in * @param listener listener * @deprecated This constructor was poorly thought out. Custom executor is useless. Use this version instead: {@link #LeaderSelector(CuratorFramework, String, ExecutorService, LeaderSelectorListener)} */ @SuppressWarnings("UnusedParameters") @Deprecated public LeaderSelector(CuratorFramework client, String leaderPath, ThreadFactory threadFactory, Executor executor, LeaderSelectorListener listener) { this(client, leaderPath, new CloseableExecutorService(wrapExecutor(executor), true), listener); } /** * @param client the client * @param leaderPath the path for this leadership group * @param executorService thread pool to use * @param listener listener */ public LeaderSelector(CuratorFramework client, String leaderPath, ExecutorService executorService, LeaderSelectorListener listener) { this(client, leaderPath, new CloseableExecutorService(executorService), listener); } /** * @param client the client * @param leaderPath the path for this leadership group * @param executorService thread pool to use * @param listener listener */ public LeaderSelector(CuratorFramework client, String leaderPath, CloseableExecutorService executorService, LeaderSelectorListener listener) { Preconditions.checkNotNull(client, "client cannot be null"); PathUtils.validatePath(leaderPath); Preconditions.checkNotNull(listener, "listener cannot be null"); this.client = client; this.listener = new WrappedListener(this, listener); hasLeadership = false; this.executorService = executorService; mutex = new InterProcessMutex(client, leaderPath) { @Override protected byte[] getLockNodeBytes() { return (id.length() > 0) ? getIdBytes(id) : null; } }; } static byte[] getIdBytes(String id) { try { return id.getBytes("UTF-8"); } catch ( UnsupportedEncodingException e ) { throw new Error(e); // this should never happen } } /** * By default, when {@link LeaderSelectorListener#takeLeadership(CuratorFramework)} returns, this * instance is not requeued. Calling this method puts the leader selector into a mode where it * will always requeue itself. */ public void autoRequeue() { autoRequeue.set(true); } /** * Sets the ID to store for this leader. Will be the value returned * when {@link #getParticipants()} is called. IMPORTANT: must be called * prior to {@link #start()} to have effect. * * @param id ID */ public void setId(String id) { Preconditions.checkNotNull(id, "id cannot be null"); this.id = id; } /** * Return the ID that was set via {@link #setId(String)} * * @return id */ public String getId() { return id; } /** * Attempt leadership. This attempt is done in the background - i.e. this method returns * immediately.

* IMPORTANT: previous versions allowed this method to be called multiple times. This * is no longer supported. Use {@link #requeue()} for this purpose. */ public void start() { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); Preconditions.checkState(!executorService.isShutdown(), "Already started"); Preconditions.checkState(!hasLeadership, "Already has leadership"); client.getConnectionStateListenable().addListener(listener); requeue(); } /** * Re-queue an attempt for leadership. If this instance is already queued, nothing * happens and false is returned. If the instance was not queued, it is re-qeued and true * is returned * * @return true if re-queue is successful */ public boolean requeue() { Preconditions.checkState(state.get() == State.STARTED, "close() has already been called"); return internalRequeue(); } public synchronized boolean internalRequeue() { if ( !isQueued && (state.get() == State.STARTED) ) { isQueued = true; Future task = executorService.submit(new Callable() { @Override public Void call() throws Exception { try { doWorkLoop(); } finally { clearIsQueued(); if ( autoRequeue.get() ) { internalRequeue(); } } return null; } }); ourTask.set(task); return true; } return false; } /** * Shutdown this selector and remove yourself from the leadership group */ public synchronized void close() { Preconditions.checkState(state.compareAndSet(State.STARTED, State.CLOSED), "Already closed or has not been started"); client.getConnectionStateListenable().removeListener(listener); executorService.close(); ourTask.set(null); } /** *

* Returns the set of current participants in the leader selection *

*

*

* NOTE - this method polls the ZK server. Therefore it can possibly * return a value that does not match {@link #hasLeadership()} as hasLeadership * uses a local field of the class. *

* * @return participants * @throws Exception ZK errors, interruptions, etc. */ public Collection getParticipants() throws Exception { Collection participantNodes = mutex.getParticipantNodes(); return getParticipants(client, participantNodes); } static Collection getParticipants(CuratorFramework client, Collection participantNodes) throws Exception { ImmutableList.Builder builder = ImmutableList.builder(); boolean isLeader = true; for ( String path : participantNodes ) { try { Participant participant = participantForPath(client, path, isLeader); builder.add(participant); } catch ( KeeperException.NoNodeException ignore ) { // ignore } isLeader = false; // by definition the first node is the leader } return builder.build(); } /** *

* Return the id for the current leader. If for some reason there is no * current leader, a dummy participant is returned. *

*

*

* NOTE - this method polls the ZK server. Therefore it can possibly * return a value that does not match {@link #hasLeadership()} as hasLeadership * uses a local field of the class. *

* * @return leader * @throws Exception ZK errors, interruptions, etc. */ public Participant getLeader() throws Exception { Collection participantNodes = mutex.getParticipantNodes(); return getLeader(client, participantNodes); } static Participant getLeader(CuratorFramework client, Collection participantNodes) throws Exception { if ( participantNodes.size() > 0 ) { return participantForPath(client, participantNodes.iterator().next(), true); } return new Participant(); } /** * Return true if leadership is currently held by this instance * * @return true/false */ public boolean hasLeadership() { return hasLeadership; } /** * Attempt to cancel and interrupt the current leadership if this instance has leadership */ public synchronized void interruptLeadership() { Future task = ourTask.get(); if ( task != null ) { task.cancel(true); } } private static Participant participantForPath(CuratorFramework client, String path, boolean markAsLeader) throws Exception { byte[] bytes = client.getData().forPath(path); String thisId = new String(bytes, "UTF-8"); return new Participant(thisId, markAsLeader); } @VisibleForTesting void doWork() throws Exception { hasLeadership = false; try { mutex.acquire(); hasLeadership = true; try { if ( debugLeadershipLatch != null ) { debugLeadershipLatch.countDown(); } if ( debugLeadershipWaitLatch != null ) { debugLeadershipWaitLatch.await(); } listener.takeLeadership(client); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); throw e; } catch ( Throwable e ) { log.error("The leader threw an exception", e); } finally { clearIsQueued(); } } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); throw e; } catch ( Exception e ) { throw e; } finally { hasLeadership = false; try { mutex.release(); } catch ( Exception ignore ) { // ignore errors - this is just a safety } } } private void doWorkLoop() throws Exception { KeeperException exception = null; try { doWork(); } catch ( KeeperException.ConnectionLossException e ) { exception = e; } catch ( KeeperException.SessionExpiredException e ) { exception = e; } catch ( InterruptedException ignore ) { Thread.currentThread().interrupt(); } if ( (exception != null) && !autoRequeue.get() ) // autoRequeue should ignore connection loss or session expired and just keep trying { throw exception; } } private synchronized void clearIsQueued() { isQueued = false; } // temporary wrapper for deprecated constructor private static ExecutorService wrapExecutor(final Executor executor) { return new AbstractExecutorService() { private volatile boolean isShutdown = false; private volatile boolean isTerminated = false; @Override public void shutdown() { isShutdown = true; } @Override public List shutdownNow() { return Lists.newArrayList(); } @Override public boolean isShutdown() { return isShutdown; } @Override public boolean isTerminated() { return isTerminated; } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { throw new UnsupportedOperationException(); } @Override public void execute(Runnable command) { try { executor.execute(command); } finally { isShutdown = true; isTerminated = true; } } }; } private static class WrappedListener implements LeaderSelectorListener { private final LeaderSelector leaderSelector; private final LeaderSelectorListener listener; public WrappedListener(LeaderSelector leaderSelector, LeaderSelectorListener listener) { this.leaderSelector = leaderSelector; this.listener = listener; } @Override public void takeLeadership(CuratorFramework client) throws Exception { listener.takeLeadership(client); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { try { listener.stateChanged(client, newState); } catch ( CancelLeadershipException dummy ) { leaderSelector.interruptLeadership(); } } } } LeaderSelectorListener.java000066400000000000000000000026331245521677600414230ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.leader; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.state.ConnectionStateListener; /** * Notification for leadership * * @see LeaderSelector */ public interface LeaderSelectorListener extends ConnectionStateListener { /** * Called when your instance has been granted leadership. This method * should not return until you wish to release leadership * * @param client the client * @throws Exception any errors */ public void takeLeadership(CuratorFramework client) throws Exception; } LeaderSelectorListenerAdapter.java000066400000000000000000000026741245521677600427310ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.leader; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.state.ConnectionState; /** * An implementation of {@link LeaderSelectorListener} that adds the recommended handling * for connection state problems */ public abstract class LeaderSelectorListenerAdapter implements LeaderSelectorListener { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( (newState == ConnectionState.SUSPENDED) || (newState == ConnectionState.LOST) ) { throw new CancelLeadershipException(); } } } Participant.java000066400000000000000000000046551245521677600373040ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.leader; /** * Describes a participant in a leadership selection */ @SuppressWarnings({"RedundantIfStatement"}) public class Participant { private final String id; private final boolean isLeader; /** * @param id the ID * @param leader true if the leader */ public Participant(String id, boolean leader) { this.id = id; isLeader = leader; } Participant() { this("", false); } /** * Returns the ID set via {@link LeaderSelector#setId(String)} * * @return id */ public String getId() { return id; } /** * Returns true if this participant is the current leader * * @return true/false */ public boolean isLeader() { return isLeader; } @Override public String toString() { return "Participant{" + "id='" + id + '\'' + ", isLeader=" + isLeader + '}'; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } Participant that = (Participant)o; if ( isLeader != that.isLeader ) { return false; } if ( !id.equals(that.id) ) { return false; } return true; } @Override public int hashCode() { int result = id.hashCode(); result = 31 * result + (isLeader ? 1 : 0); return result; } } 000077500000000000000000000000001245521677600340305ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locksChildReaper.java000066400000000000000000000152251245521677600370620ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import com.google.common.base.Preconditions; import com.google.common.collect.Sets; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.CloseableScheduledExecutorService; import org.apache.curator.utils.ThreadUtils; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.utils.PathUtils; /** * Utility to reap empty child nodes of a parent node. Periodically calls getChildren on * the node and adds empty nodes to an internally managed {@link Reaper} */ public class ChildReaper implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final Reaper reaper; private final AtomicReference state = new AtomicReference(State.LATENT); private final CuratorFramework client; private final Collection paths = Sets.newConcurrentHashSet(); private final Reaper.Mode mode; private final CloseableScheduledExecutorService executor; private final int reapingThresholdMs; private volatile Future task; private enum State { LATENT, STARTED, CLOSED } /** * @param client the client * @param path path to reap children from * @param mode reaping mode */ public ChildReaper(CuratorFramework client, String path, Reaper.Mode mode) { this(client, path, mode, newExecutorService(), Reaper.DEFAULT_REAPING_THRESHOLD_MS, null); } /** * @param client the client * @param path path to reap children from * @param reapingThresholdMs threshold in milliseconds that determines that a path can be deleted * @param mode reaping mode */ public ChildReaper(CuratorFramework client, String path, Reaper.Mode mode, int reapingThresholdMs) { this(client, path, mode, newExecutorService(), reapingThresholdMs, null); } /** * @param client the client * @param path path to reap children from * @param executor executor to use for background tasks * @param reapingThresholdMs threshold in milliseconds that determines that a path can be deleted * @param mode reaping mode */ public ChildReaper(CuratorFramework client, String path, Reaper.Mode mode, ScheduledExecutorService executor, int reapingThresholdMs) { this(client, path, mode, executor, reapingThresholdMs, null); } /** * @param client the client * @param path path to reap children from * @param executor executor to use for background tasks * @param reapingThresholdMs threshold in milliseconds that determines that a path can be deleted * @param mode reaping mode * @param leaderPath if not null, uses a leader selection so that only 1 reaper is active in the cluster */ public ChildReaper(CuratorFramework client, String path, Reaper.Mode mode, ScheduledExecutorService executor, int reapingThresholdMs, String leaderPath) { this.client = client; this.mode = mode; this.executor = new CloseableScheduledExecutorService(executor); this.reapingThresholdMs = reapingThresholdMs; this.reaper = new Reaper(client, executor, reapingThresholdMs, leaderPath); addPath(path); } /** * The reaper must be started * * @throws Exception errors */ public void start() throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); task = executor.scheduleWithFixedDelay ( new Runnable() { @Override public void run() { doWork(); } }, reapingThresholdMs, reapingThresholdMs, TimeUnit.MILLISECONDS ); reaper.start(); } @Override public void close() throws IOException { if ( state.compareAndSet(State.STARTED, State.CLOSED) ) { CloseableUtils.closeQuietly(reaper); task.cancel(true); } } /** * Add a path to reap children from * * @param path the path * @return this for chaining */ public ChildReaper addPath(String path) { paths.add(PathUtils.validatePath(path)); return this; } /** * Remove a path from reaping * * @param path the path * @return true if the path existed and was removed */ public boolean removePath(String path) { return paths.remove(PathUtils.validatePath(path)); } private static ScheduledExecutorService newExecutorService() { return ThreadUtils.newFixedThreadScheduledPool(2, "ChildReaper"); } private void doWork() { for ( String path : paths ) { try { List children = client.getChildren().forPath(path); for ( String name : children ) { String thisPath = ZKPaths.makePath(path, name); Stat stat = client.checkExists().forPath(thisPath); if ( (stat != null) && (stat.getNumChildren() == 0) ) { reaper.addPath(thisPath, mode); } } } catch ( Exception e ) { log.error("Could not get children for path: " + path, e); } } } } InterProcessLock.java000066400000000000000000000037331245521677600401320ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import java.util.concurrent.TimeUnit; public interface InterProcessLock { /** * Acquire the mutex - blocking until it's available. Each call to acquire must be balanced by a call * to {@link #release()} * * @throws Exception ZK errors, connection interruptions */ public void acquire() throws Exception; /** * Acquire the mutex - blocks until it's available or the given time expires. Each call to acquire that returns true must be balanced by a call * to {@link #release()} * * @param time time to wait * @param unit time unit * @return true if the mutex was acquired, false if not * @throws Exception ZK errors, connection interruptions */ public boolean acquire(long time, TimeUnit unit) throws Exception; /** * Perform one release of the mutex. * * @throws Exception ZK errors, interruptions, current thread does not own the lock */ public void release() throws Exception; /** * Returns true if the mutex is acquired by a thread in this JVM * * @return true/false */ boolean isAcquiredInThisProcess(); } InterProcessMultiLock.java000066400000000000000000000124421245521677600411420ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.apache.curator.framework.CuratorFramework; import java.util.List; import java.util.concurrent.TimeUnit; import static com.google.common.collect.Lists.reverse; /** * A container that manages multiple locks as a single entity. When {@link #acquire()} is called, * all the locks are acquired. If that fails, any paths that were acquired are released. Similarly, when * {@link #release()} is called, all locks are released (failures are ignored). */ public class InterProcessMultiLock implements InterProcessLock { private final List locks; /** * Creates a multi lock of {@link InterProcessMutex}s * * @param client the client * @param paths list of paths to manage in the order that they are to be locked */ public InterProcessMultiLock(CuratorFramework client, List paths) { // paths get checked in each individual InterProcessMutex, so trust them here this(makeLocks(client, paths)); } /** * Creates a multi lock of any type of inter process lock * * @param locks the locks */ public InterProcessMultiLock(List locks) { this.locks = ImmutableList.copyOf(locks); } private static List makeLocks(CuratorFramework client, List paths) { ImmutableList.Builder builder = ImmutableList.builder(); for ( String path : paths ) { InterProcessLock lock = new InterProcessMutex(client, path); builder.add(lock); } return builder.build(); } /** * {@inheritDoc} */ @Override public void acquire() throws Exception { acquire(-1, null); } /** * {@inheritDoc} */ @Override public boolean acquire(long time, TimeUnit unit) throws Exception { Exception exception = null; List acquired = Lists.newArrayList(); boolean success = true; for ( InterProcessLock lock : locks ) { try { if ( unit == null ) { lock.acquire(); acquired.add(lock); } else { if ( lock.acquire(time, unit) ) { acquired.add(lock); } else { success = false; break; } } } catch ( Exception e ) { success = false; exception = e; } } if ( !success ) { for ( InterProcessLock lock : reverse(acquired) ) { try { lock.release(); } catch ( Exception e ) { // ignore } } } if ( exception != null ) { throw exception; } return success; } /** * {@inheritDoc} * *

NOTE: locks are released in the reverse order that they were acquired.

*/ @Override public synchronized void release() throws Exception { Exception baseException = null; for ( InterProcessLock lock : reverse(locks) ) { try { lock.release(); } catch ( Exception e ) { if ( baseException == null ) { baseException = e; } else { baseException = new Exception(baseException); } } } if ( baseException != null ) { throw baseException; } } @Override public synchronized boolean isAcquiredInThisProcess() { // it's subjective what the correct meaning is here - I choose to return true // only if all of the locks are acquired for ( InterProcessLock lock : locks ) { if ( !lock.isAcquiredInThisProcess() ) { return false; } } return true; } } InterProcessMutex.java000066400000000000000000000172371245521677600403500ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import com.google.common.collect.Maps; import com.google.common.util.concurrent.MoreExecutors; import org.apache.curator.framework.CuratorFramework; import java.io.IOException; import java.util.Collection; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.apache.curator.utils.PathUtils; /** * A re-entrant mutex that works across JVMs. Uses Zookeeper to hold the lock. All processes in all JVMs that * use the same lock path will achieve an inter-process critical section. Further, this mutex is * "fair" - each user will get the mutex in the order requested (from ZK's point of view) */ public class InterProcessMutex implements InterProcessLock, Revocable { private final LockInternals internals; private final String basePath; private final ConcurrentMap threadData = Maps.newConcurrentMap(); private static class LockData { final Thread owningThread; final String lockPath; final AtomicInteger lockCount = new AtomicInteger(1); private LockData(Thread owningThread, String lockPath) { this.owningThread = owningThread; this.lockPath = lockPath; } } private static final String LOCK_NAME = "lock-"; /** * @param client client * @param path the path to lock */ public InterProcessMutex(CuratorFramework client, String path) { this(client, path, new StandardLockInternalsDriver()); } /** * @param client client * @param path the path to lock * @param driver lock driver */ public InterProcessMutex(CuratorFramework client, String path, LockInternalsDriver driver) { this(client, path, LOCK_NAME, 1, driver); } /** * Acquire the mutex - blocking until it's available. Note: the same thread * can call acquire re-entrantly. Each call to acquire must be balanced by a call * to {@link #release()} * * @throws Exception ZK errors, connection interruptions */ @Override public void acquire() throws Exception { if ( !internalLock(-1, null) ) { throw new IOException("Lost connection while trying to acquire lock: " + basePath); } } /** * Acquire the mutex - blocks until it's available or the given time expires. Note: the same thread * can call acquire re-entrantly. Each call to acquire that returns true must be balanced by a call * to {@link #release()} * * @param time time to wait * @param unit time unit * @return true if the mutex was acquired, false if not * @throws Exception ZK errors, connection interruptions */ @Override public boolean acquire(long time, TimeUnit unit) throws Exception { return internalLock(time, unit); } /** * Returns true if the mutex is acquired by a thread in this JVM * * @return true/false */ @Override public boolean isAcquiredInThisProcess() { return (threadData.size() > 0); } /** * Perform one release of the mutex if the calling thread is the same thread that acquired it. If the * thread had made multiple calls to acquire, the mutex will still be held when this method returns. * * @throws Exception ZK errors, interruptions, current thread does not own the lock */ @Override public void release() throws Exception { /* Note on concurrency: a given lockData instance can be only acted on by a single thread so locking isn't necessary */ Thread currentThread = Thread.currentThread(); LockData lockData = threadData.get(currentThread); if ( lockData == null ) { throw new IllegalMonitorStateException("You do not own the lock: " + basePath); } int newLockCount = lockData.lockCount.decrementAndGet(); if ( newLockCount > 0 ) { return; } if ( newLockCount < 0 ) { throw new IllegalMonitorStateException("Lock count has gone negative for lock: " + basePath); } try { internals.releaseLock(lockData.lockPath); } finally { threadData.remove(currentThread); } } /** * Return a sorted list of all current nodes participating in the lock * * @return list of nodes * @throws Exception ZK errors, interruptions, etc. */ public Collection getParticipantNodes() throws Exception { return LockInternals.getParticipantNodes(internals.getClient(), basePath, internals.getLockName(), internals.getDriver()); } @Override public void makeRevocable(RevocationListener listener) { makeRevocable(listener, MoreExecutors.sameThreadExecutor()); } @Override public void makeRevocable(final RevocationListener listener, Executor executor) { internals.makeRevocable(new RevocationSpec(executor, new Runnable() { @Override public void run() { listener.revocationRequested(InterProcessMutex.this); } })); } InterProcessMutex(CuratorFramework client, String path, String lockName, int maxLeases, LockInternalsDriver driver) { basePath = PathUtils.validatePath(path); internals = new LockInternals(client, driver, path, lockName, maxLeases); } boolean isOwnedByCurrentThread() { LockData lockData = threadData.get(Thread.currentThread()); return (lockData != null) && (lockData.lockCount.get() > 0); } protected byte[] getLockNodeBytes() { return null; } protected String getLockPath() { LockData lockData = threadData.get(Thread.currentThread()); return lockData != null ? lockData.lockPath : null; } private boolean internalLock(long time, TimeUnit unit) throws Exception { /* Note on concurrency: a given lockData instance can be only acted on by a single thread so locking isn't necessary */ Thread currentThread = Thread.currentThread(); LockData lockData = threadData.get(currentThread); if ( lockData != null ) { // re-entering lockData.lockCount.incrementAndGet(); return true; } String lockPath = internals.attemptLock(time, unit, getLockNodeBytes()); if ( lockPath != null ) { LockData newLockData = new LockData(currentThread, lockPath); threadData.put(currentThread, newLockData); return true; } return false; } } InterProcessReadWriteLock.java000066400000000000000000000164101245521677600417350ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import org.apache.curator.framework.CuratorFramework; import java.util.Arrays; import java.util.Collection; import java.util.List; /** *

* A re-entrant read/write mutex that works across JVMs. Uses Zookeeper to hold the lock. All processes * in all JVMs that use the same lock path will achieve an inter-process critical section. Further, this mutex is * "fair" - each user will get the mutex in the order requested (from ZK's point of view). *

* *

* A read write lock maintains a pair of associated locks, one for read-only operations and one * for writing. The read lock may be held simultaneously by multiple reader processes, so long as * there are no writers. The write lock is exclusive. *

* *

* Reentrancy
* This lock allows both readers and writers to reacquire read or write locks in the style of a * re-entrant lock. Non-re-entrant readers are not allowed until all write locks held by the * writing thread/process have been released. Additionally, a writer can acquire the read lock, but not * vice-versa. If a reader tries to acquire the write lock it will never succeed.

* * Lock downgrading
* Re-entrancy also allows downgrading from the write lock to a read lock, by acquiring the write * lock, then the read lock and then releasing the write lock. However, upgrading from a read * lock to the write lock is not possible. *

*/ public class InterProcessReadWriteLock { private final InterProcessMutex readMutex; private final InterProcessMutex writeMutex; // must be the same length. LockInternals depends on it private static final String READ_LOCK_NAME = "__READ__"; private static final String WRITE_LOCK_NAME = "__WRIT__"; private static class SortingLockInternalsDriver extends StandardLockInternalsDriver { @Override public final String fixForSorting(String str, String lockName) { str = super.fixForSorting(str, READ_LOCK_NAME); str = super.fixForSorting(str, WRITE_LOCK_NAME); return str; } } private static class InternalInterProcessMutex extends InterProcessMutex { private final String lockName; private final byte[] lockData; InternalInterProcessMutex(CuratorFramework client, String path, String lockName, byte[] lockData, int maxLeases, LockInternalsDriver driver) { super(client, path, lockName, maxLeases, driver); this.lockName = lockName; this.lockData = lockData; } @Override public Collection getParticipantNodes() throws Exception { Collection nodes = super.getParticipantNodes(); Iterable filtered = Iterables.filter ( nodes, new Predicate() { @Override public boolean apply(String node) { return node.contains(lockName); } } ); return ImmutableList.copyOf(filtered); } @Override protected byte[] getLockNodeBytes() { return lockData; } } /** * @param client the client * @param basePath path to use for locking */ public InterProcessReadWriteLock(CuratorFramework client, String basePath) { this(client, basePath, null); } /** * @param client the client * @param basePath path to use for locking * @param lockData the data to store in the lock nodes */ public InterProcessReadWriteLock(CuratorFramework client, String basePath, byte[] lockData) { lockData = (lockData == null) ? null : Arrays.copyOf(lockData, lockData.length); writeMutex = new InternalInterProcessMutex ( client, basePath, WRITE_LOCK_NAME, lockData, 1, new SortingLockInternalsDriver() { @Override public PredicateResults getsTheLock(CuratorFramework client, List children, String sequenceNodeName, int maxLeases) throws Exception { return super.getsTheLock(client, children, sequenceNodeName, maxLeases); } } ); readMutex = new InternalInterProcessMutex ( client, basePath, READ_LOCK_NAME, lockData, Integer.MAX_VALUE, new SortingLockInternalsDriver() { @Override public PredicateResults getsTheLock(CuratorFramework client, List children, String sequenceNodeName, int maxLeases) throws Exception { return readLockPredicate(children, sequenceNodeName); } } ); } /** * Returns the lock used for reading. * * @return read lock */ public InterProcessMutex readLock() { return readMutex; } /** * Returns the lock used for writing. * * @return write lock */ public InterProcessMutex writeLock() { return writeMutex; } private PredicateResults readLockPredicate(List children, String sequenceNodeName) throws Exception { if ( writeMutex.isOwnedByCurrentThread() ) { return new PredicateResults(null, true); } int index = 0; int firstWriteIndex = Integer.MAX_VALUE; int ourIndex = Integer.MAX_VALUE; for ( String node : children ) { if ( node.contains(WRITE_LOCK_NAME) ) { firstWriteIndex = Math.min(index, firstWriteIndex); } else if ( node.startsWith(sequenceNodeName) ) { ourIndex = index; break; } ++index; } StandardLockInternalsDriver.validateOurIndex(sequenceNodeName, ourIndex); boolean getsTheLock = (ourIndex < firstWriteIndex); String pathToWatch = getsTheLock ? null : children.get(firstWriteIndex); return new PredicateResults(pathToWatch, getsTheLock); } } InterProcessSemaphore.java000066400000000000000000000244711245521677600411670ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.shared.SharedCountListener; import org.apache.curator.framework.recipes.shared.SharedCountReader; import org.apache.curator.framework.state.ConnectionState; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Collection; import java.util.concurrent.TimeUnit; /** *

* A counting semaphore that works across JVMs. All processes * in all JVMs that use the same lock path will achieve an inter-process limited set of leases. * Further, this semaphore is mostly "fair" - each user will get a lease in the order requested * (from ZK's point of view). *

* *

* There are two modes for determining the max leases for the semaphore. In the first mode the * max leases is a convention maintained by the users of a given path. In the second mode a * {@link SharedCountReader} is used as the method for semaphores of a given path to determine * the max leases. *

* *

* If a {@link SharedCountReader} is not used, no internal checks are done to prevent * Process A acting as if there are 10 leases and Process B acting as if there are 20. Therefore, * make sure that all instances in all processes use the same numberOfLeases value. *

* *

* The various acquire methods return {@link Lease} objects that represent acquired leases. Clients * must take care to close lease objects (ideally in a finally * block) else the lease will be lost. However, if the client session drops (crash, etc.), * any leases held by the client are * automatically closed and made available to other clients. *

* * @deprecated Use {@link InterProcessSemaphoreV2} instead of this class. It uses a better algorithm. */ public class InterProcessSemaphore { private final Logger log = LoggerFactory.getLogger(getClass()); private final LockInternals internals; private static final String LOCK_NAME = "lock-"; /** * @param client the client * @param path path for the semaphore * @param maxLeases the max number of leases to allow for this instance */ public InterProcessSemaphore(CuratorFramework client, String path, int maxLeases) { this(client, path, maxLeases, null); } /** * @param client the client * @param path path for the semaphore * @param count the shared count to use for the max leases */ public InterProcessSemaphore(CuratorFramework client, String path, SharedCountReader count) { this(client, path, 0, count); } private InterProcessSemaphore(CuratorFramework client, String path, int maxLeases, SharedCountReader count) { // path verified in LockInternals internals = new LockInternals(client, new StandardLockInternalsDriver(), path, LOCK_NAME, (count != null) ? count.getCount() : maxLeases); if ( count != null ) { count.addListener ( new SharedCountListener() { @Override public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception { internals.setMaxLeases(newCount); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { // no need to handle this here - clients should set their own connection state listener } } ); } } /** * Convenience method. Closes all leases in the given collection of leases * * @param leases leases to close */ public void returnAll(Collection leases) { for ( Lease l : leases ) { CloseableUtils.closeQuietly(l); } } /** * Convenience method. Closes the lease * * @param lease lease to close */ public void returnLease(Lease lease) { CloseableUtils.closeQuietly(lease); } /** *

Acquire a lease. If no leases are available, this method blocks until either the maximum * number of leases is increased or another client/process closes a lease.

* *

The client must close the lease when it is done with it. You should do this in a * finally block.

* * @return the new lease * @throws Exception ZK errors, interruptions, etc. */ public Lease acquire() throws Exception { String path = internals.attemptLock(-1, null, null); return makeLease(path); } /** *

Acquire qty leases. If there are not enough leases available, this method * blocks until either the maximum number of leases is increased enough or other clients/processes * close enough leases.

* *

The client must close the leases when it is done with them. You should do this in a * finally block. NOTE: You can use {@link #returnAll(Collection)} for this.

* * @param qty number of leases to acquire * @return the new leases * @throws Exception ZK errors, interruptions, etc. */ public Collection acquire(int qty) throws Exception { Preconditions.checkArgument(qty > 0, "qty cannot be 0"); ImmutableList.Builder builder = ImmutableList.builder(); try { while ( qty-- > 0 ) { String path = internals.attemptLock(-1, null, null); builder.add(makeLease(path)); } } catch ( Exception e ) { returnAll(builder.build()); throw e; } return builder.build(); } /** *

Acquire a lease. If no leases are available, this method blocks until either the maximum * number of leases is increased or another client/process closes a lease. However, this method * will only block to a maximum of the time parameters given.

* *

The client must close the lease when it is done with it. You should do this in a * finally block.

* * @param time time to wait * @param unit time unit * @return the new lease or null if time ran out * @throws Exception ZK errors, interruptions, etc. */ public Lease acquire(long time, TimeUnit unit) throws Exception { String path = internals.attemptLock(time, unit, null); return (path != null) ? makeLease(path) : null; } /** *

Acquire qty leases. If there are not enough leases available, this method * blocks until either the maximum number of leases is increased enough or other clients/processes * close enough leases. However, this method will only block to a maximum of the time * parameters given. If time expires before all leases are acquired, the subset of acquired * leases are automatically closed.

* *

The client must close the leases when it is done with them. You should do this in a * finally block. NOTE: You can use {@link #returnAll(Collection)} for this.

* * @param qty number of leases to acquire * @param time time to wait * @param unit time unit * @return the new leases or null if time ran out * @throws Exception ZK errors, interruptions, etc. */ public Collection acquire(int qty, long time, TimeUnit unit) throws Exception { long startMs = System.currentTimeMillis(); long waitMs = TimeUnit.MILLISECONDS.convert(time, unit); Preconditions.checkArgument(qty > 0, "qty cannot be 0"); ImmutableList.Builder builder = ImmutableList.builder(); try { while ( qty-- > 0 ) { long elapsedMs = System.currentTimeMillis() - startMs; long thisWaitMs = waitMs - elapsedMs; String path = (thisWaitMs > 0) ? internals.attemptLock(thisWaitMs, TimeUnit.MILLISECONDS, null) : null; if ( path == null ) { returnAll(builder.build()); return null; } builder.add(makeLease(path)); } } catch ( Exception e ) { returnAll(builder.build()); throw e; } return builder.build(); } private Lease makeLease(final String path) { return new Lease() { @Override public void close() throws IOException { try { internals.releaseLock(path); } catch ( KeeperException.NoNodeException e ) { log.warn("Lease already released", e); } catch ( Exception e ) { throw new IOException(e); } } @Override public byte[] getData() throws Exception { return internals.getClient().getData().forPath(path); } }; } } InterProcessSemaphoreMutex.java000066400000000000000000000045761245521677600422160ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import com.google.common.base.Preconditions; import org.apache.curator.framework.CuratorFramework; import java.util.concurrent.TimeUnit; /** * A NON re-entrant mutex that works across JVMs. Uses Zookeeper to hold the lock. All processes in all JVMs that * use the same lock path will achieve an inter-process critical section. */ public class InterProcessSemaphoreMutex implements InterProcessLock { private final InterProcessSemaphoreV2 semaphore; private volatile Lease lease; /** * @param client the client * @param path path for the lock */ public InterProcessSemaphoreMutex(CuratorFramework client, String path) { this.semaphore = new InterProcessSemaphoreV2(client, path, 1); } @Override public void acquire() throws Exception { lease = semaphore.acquire(); } @Override public boolean acquire(long time, TimeUnit unit) throws Exception { Lease acquiredLease = semaphore.acquire(time, unit); if ( acquiredLease == null ) { return false; // important - don't overwrite lease field if couldn't be acquired } lease = acquiredLease; return true; } @Override public void release() throws Exception { Preconditions.checkState(lease != null, "Not acquired"); try { lease.close(); } finally { lease = null; } } @Override public boolean isAcquiredInThisProcess() { return (lease != null); } } InterProcessSemaphoreV2.java000066400000000000000000000362031245521677600413730ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.RetryLoop; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.PathAndBytesable; import org.apache.curator.framework.imps.CuratorFrameworkState; import org.apache.curator.framework.recipes.shared.SharedCountListener; import org.apache.curator.framework.recipes.shared.SharedCountReader; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.curator.utils.PathUtils; /** *

* A counting semaphore that works across JVMs. All processes * in all JVMs that use the same lock path will achieve an inter-process limited set of leases. * Further, this semaphore is mostly "fair" - each user will get a lease in the order requested * (from ZK's point of view). *

*

* There are two modes for determining the max leases for the semaphore. In the first mode the * max leases is a convention maintained by the users of a given path. In the second mode a * {@link SharedCountReader} is used as the method for semaphores of a given path to determine * the max leases. *

*

* If a {@link SharedCountReader} is not used, no internal checks are done to prevent * Process A acting as if there are 10 leases and Process B acting as if there are 20. Therefore, * make sure that all instances in all processes use the same numberOfLeases value. *

*

* The various acquire methods return {@link Lease} objects that represent acquired leases. Clients * must take care to close lease objects (ideally in a finally * block) else the lease will be lost. However, if the client session drops (crash, etc.), * any leases held by the client are automatically closed and made available to other clients. *

*

* Thanks to Ben Bangert (ben@groovie.org) for the algorithm used. *

*/ public class InterProcessSemaphoreV2 { private final Logger log = LoggerFactory.getLogger(getClass()); private final InterProcessMutex lock; private final CuratorFramework client; private final String leasesPath; private final Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { notifyFromWatcher(); } }; private volatile byte[] nodeData; private volatile int maxLeases; private static final String LOCK_PARENT = "locks"; private static final String LEASE_PARENT = "leases"; private static final String LEASE_BASE_NAME = "lease-"; /** * @param client the client * @param path path for the semaphore * @param maxLeases the max number of leases to allow for this instance */ public InterProcessSemaphoreV2(CuratorFramework client, String path, int maxLeases) { this(client, path, maxLeases, null); } /** * @param client the client * @param path path for the semaphore * @param count the shared count to use for the max leases */ public InterProcessSemaphoreV2(CuratorFramework client, String path, SharedCountReader count) { this(client, path, 0, count); } private InterProcessSemaphoreV2(CuratorFramework client, String path, int maxLeases, SharedCountReader count) { this.client = client; path = PathUtils.validatePath(path); lock = new InterProcessMutex(client, ZKPaths.makePath(path, LOCK_PARENT)); this.maxLeases = (count != null) ? count.getCount() : maxLeases; leasesPath = ZKPaths.makePath(path, LEASE_PARENT); if ( count != null ) { count.addListener ( new SharedCountListener() { @Override public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception { InterProcessSemaphoreV2.this.maxLeases = newCount; notifyFromWatcher(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { // no need to handle this here - clients should set their own connection state listener } } ); } } /** * Set the data to put for the node created by this semaphore. This must be called prior to calling one * of the acquire() methods. * * @param nodeData node data */ public void setNodeData(byte[] nodeData) { this.nodeData = (nodeData != null) ? Arrays.copyOf(nodeData, nodeData.length) : null; } /** * Return a list of all current nodes participating in the semaphore * * @return list of nodes * @throws Exception ZK errors, interruptions, etc. */ public Collection getParticipantNodes() throws Exception { return client.getChildren().forPath(leasesPath); } /** * Convenience method. Closes all leases in the given collection of leases * * @param leases leases to close */ public void returnAll(Collection leases) { for ( Lease l : leases ) { CloseableUtils.closeQuietly(l); } } /** * Convenience method. Closes the lease * * @param lease lease to close */ public void returnLease(Lease lease) { CloseableUtils.closeQuietly(lease); } /** *

Acquire a lease. If no leases are available, this method blocks until either the maximum * number of leases is increased or another client/process closes a lease.

*

The client must close the lease when it is done with it. You should do this in a * finally block.

* * @return the new lease * @throws Exception ZK errors, interruptions, etc. */ public Lease acquire() throws Exception { Collection leases = acquire(1, 0, null); return leases.iterator().next(); } /** *

Acquire qty leases. If there are not enough leases available, this method * blocks until either the maximum number of leases is increased enough or other clients/processes * close enough leases.

*

The client must close the leases when it is done with them. You should do this in a * finally block. NOTE: You can use {@link #returnAll(Collection)} for this.

* * @param qty number of leases to acquire * @return the new leases * @throws Exception ZK errors, interruptions, etc. */ public Collection acquire(int qty) throws Exception { return acquire(qty, 0, null); } /** *

Acquire a lease. If no leases are available, this method blocks until either the maximum * number of leases is increased or another client/process closes a lease. However, this method * will only block to a maximum of the time parameters given.

*

The client must close the lease when it is done with it. You should do this in a * finally block.

* * @param time time to wait * @param unit time unit * @return the new lease or null if time ran out * @throws Exception ZK errors, interruptions, etc. */ public Lease acquire(long time, TimeUnit unit) throws Exception { Collection leases = acquire(1, time, unit); return (leases != null) ? leases.iterator().next() : null; } /** *

Acquire qty leases. If there are not enough leases available, this method * blocks until either the maximum number of leases is increased enough or other clients/processes * close enough leases. However, this method will only block to a maximum of the time * parameters given. If time expires before all leases are acquired, the subset of acquired * leases are automatically closed.

*

The client must close the leases when it is done with them. You should do this in a * finally block. NOTE: You can use {@link #returnAll(Collection)} for this.

* * @param qty number of leases to acquire * @param time time to wait * @param unit time unit * @return the new leases or null if time ran out * @throws Exception ZK errors, interruptions, etc. */ public Collection acquire(int qty, long time, TimeUnit unit) throws Exception { long startMs = System.currentTimeMillis(); boolean hasWait = (unit != null); long waitMs = hasWait ? TimeUnit.MILLISECONDS.convert(time, unit) : 0; Preconditions.checkArgument(qty > 0, "qty cannot be 0"); ImmutableList.Builder builder = ImmutableList.builder(); boolean success = false; try { while ( qty-- > 0 ) { int retryCount = 0; long startMillis = System.currentTimeMillis(); boolean isDone = false; while ( !isDone ) { switch ( internalAcquire1Lease(builder, startMs, hasWait, waitMs) ) { case CONTINUE: { isDone = true; break; } case RETURN_NULL: { return null; } case RETRY_DUE_TO_MISSING_NODE: { // gets thrown by internalAcquire1Lease when it can't find the lock node // this can happen when the session expires, etc. So, if the retry allows, just try it all again if ( !client.getZookeeperClient().getRetryPolicy().allowRetry(retryCount++, System.currentTimeMillis() - startMillis, RetryLoop.getDefaultRetrySleeper()) ) { throw new KeeperException.NoNodeException("Sequential path not found - possible session loss"); } // try again break; } } } } success = true; } finally { if ( !success ) { returnAll(builder.build()); } } return builder.build(); } private enum InternalAcquireResult { CONTINUE, RETURN_NULL, RETRY_DUE_TO_MISSING_NODE } private InternalAcquireResult internalAcquire1Lease(ImmutableList.Builder builder, long startMs, boolean hasWait, long waitMs) throws Exception { if ( client.getState() != CuratorFrameworkState.STARTED ) { return InternalAcquireResult.RETURN_NULL; } if ( hasWait ) { long thisWaitMs = getThisWaitMs(startMs, waitMs); if ( !lock.acquire(thisWaitMs, TimeUnit.MILLISECONDS) ) { return InternalAcquireResult.RETURN_NULL; } } else { lock.acquire(); } try { PathAndBytesable createBuilder = client.create().creatingParentsIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL); String path = (nodeData != null) ? createBuilder.forPath(ZKPaths.makePath(leasesPath, LEASE_BASE_NAME), nodeData) : createBuilder.forPath(ZKPaths.makePath(leasesPath, LEASE_BASE_NAME)); String nodeName = ZKPaths.getNodeFromPath(path); builder.add(makeLease(path)); synchronized(this) { for(;;) { List children = client.getChildren().usingWatcher(watcher).forPath(leasesPath); if ( !children.contains(nodeName) ) { log.error("Sequential path not found: " + path); return InternalAcquireResult.RETRY_DUE_TO_MISSING_NODE; } if ( children.size() <= maxLeases ) { break; } if ( hasWait ) { long thisWaitMs = getThisWaitMs(startMs, waitMs); if ( thisWaitMs <= 0 ) { return InternalAcquireResult.RETURN_NULL; } wait(thisWaitMs); } else { wait(); } } } } finally { lock.release(); } return InternalAcquireResult.CONTINUE; } private long getThisWaitMs(long startMs, long waitMs) { long elapsedMs = System.currentTimeMillis() - startMs; return waitMs - elapsedMs; } private Lease makeLease(final String path) { return new Lease() { @Override public void close() throws IOException { try { client.delete().guaranteed().forPath(path); } catch ( KeeperException.NoNodeException e ) { log.warn("Lease already released", e); } catch ( Exception e ) { throw new IOException(e); } } @Override public byte[] getData() throws Exception { return client.getData().forPath(path); } }; } private synchronized void notifyFromWatcher() { notifyAll(); } } Lease.java000066400000000000000000000031411245521677600357230ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import java.io.Closeable; import java.io.IOException; /** * Represents an acquired lease from an {@link InterProcessSemaphore}. It is the client's responsibility * to close this lease when it is no longer needed so that other blocked clients can use it. If the * client crashes (or its session expires, etc.) the lease will automatically be closed. */ public interface Lease extends Closeable { /** * Releases the lease so that other clients/processes can acquire it * * @throws IOException errors */ @Override public void close() throws IOException; /** * Return the data stored in the node for this lease * * @return data * @throws Exception errors */ public byte[] getData() throws Exception; } LockInternals.java000066400000000000000000000266171245521677600374570ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.apache.curator.RetryLoop; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.curator.framework.imps.CuratorFrameworkState; import org.apache.curator.utils.PathUtils; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; public class LockInternals { private final CuratorFramework client; private final String path; private final String basePath; private final LockInternalsDriver driver; private final String lockName; private final AtomicReference revocable = new AtomicReference(null); private final CuratorWatcher revocableWatcher = new CuratorWatcher() { @Override public void process(WatchedEvent event) throws Exception { if ( event.getType() == Watcher.Event.EventType.NodeDataChanged ) { checkRevocableWatcher(event.getPath()); } } }; private final Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { notifyFromWatcher(); } }; private volatile int maxLeases; static final byte[] REVOKE_MESSAGE = "__REVOKE__".getBytes(); /** * Attempt to delete the lock node so that sequence numbers get reset * * @throws Exception errors */ public void clean() throws Exception { try { client.delete().forPath(basePath); } catch ( KeeperException.BadVersionException ignore ) { // ignore - another thread/process got the lock } catch ( KeeperException.NotEmptyException ignore ) { // ignore - other threads/processes are waiting } } LockInternals(CuratorFramework client, LockInternalsDriver driver, String path, String lockName, int maxLeases) { this.driver = driver; this.lockName = lockName; this.maxLeases = maxLeases; this.client = client; this.basePath = PathUtils.validatePath(path); this.path = ZKPaths.makePath(path, lockName); } synchronized void setMaxLeases(int maxLeases) { this.maxLeases = maxLeases; notifyAll(); } void makeRevocable(RevocationSpec entry) { revocable.set(entry); } void releaseLock(String lockPath) throws Exception { revocable.set(null); deleteOurPath(lockPath); } CuratorFramework getClient() { return client; } public static Collection getParticipantNodes(CuratorFramework client, final String basePath, String lockName, LockInternalsSorter sorter) throws Exception { List names = getSortedChildren(client, basePath, lockName, sorter); Iterable transformed = Iterables.transform ( names, new Function() { @Override public String apply(String name) { return ZKPaths.makePath(basePath, name); } } ); return ImmutableList.copyOf(transformed); } public static List getSortedChildren(CuratorFramework client, String basePath, final String lockName, final LockInternalsSorter sorter) throws Exception { List children = client.getChildren().forPath(basePath); List sortedList = Lists.newArrayList(children); Collections.sort ( sortedList, new Comparator() { @Override public int compare(String lhs, String rhs) { return sorter.fixForSorting(lhs, lockName).compareTo(sorter.fixForSorting(rhs, lockName)); } } ); return sortedList; } public static List getSortedChildren(final String lockName, final LockInternalsSorter sorter, List children) { List sortedList = Lists.newArrayList(children); Collections.sort ( sortedList, new Comparator() { @Override public int compare(String lhs, String rhs) { return sorter.fixForSorting(lhs, lockName).compareTo(sorter.fixForSorting(rhs, lockName)); } } ); return sortedList; } List getSortedChildren() throws Exception { return getSortedChildren(client, basePath, lockName, driver); } String getLockName() { return lockName; } LockInternalsDriver getDriver() { return driver; } String attemptLock(long time, TimeUnit unit, byte[] lockNodeBytes) throws Exception { final long startMillis = System.currentTimeMillis(); final Long millisToWait = (unit != null) ? unit.toMillis(time) : null; final byte[] localLockNodeBytes = (revocable.get() != null) ? new byte[0] : lockNodeBytes; int retryCount = 0; String ourPath = null; boolean hasTheLock = false; boolean isDone = false; while ( !isDone ) { isDone = true; try { ourPath = driver.createsTheLock(client, path, localLockNodeBytes); hasTheLock = internalLockLoop(startMillis, millisToWait, ourPath); } catch ( KeeperException.NoNodeException e ) { // gets thrown by StandardLockInternalsDriver when it can't find the lock node // this can happen when the session expires, etc. So, if the retry allows, just try it all again if ( client.getZookeeperClient().getRetryPolicy().allowRetry(retryCount++, System.currentTimeMillis() - startMillis, RetryLoop.getDefaultRetrySleeper()) ) { isDone = false; } else { throw e; } } } if ( hasTheLock ) { return ourPath; } return null; } private void checkRevocableWatcher(String path) throws Exception { RevocationSpec entry = revocable.get(); if ( entry != null ) { try { byte[] bytes = client.getData().usingWatcher(revocableWatcher).forPath(path); if ( Arrays.equals(bytes, REVOKE_MESSAGE) ) { entry.getExecutor().execute(entry.getRunnable()); } } catch ( KeeperException.NoNodeException ignore ) { // ignore } } } private boolean internalLockLoop(long startMillis, Long millisToWait, String ourPath) throws Exception { boolean haveTheLock = false; boolean doDelete = false; try { if ( revocable.get() != null ) { client.getData().usingWatcher(revocableWatcher).forPath(ourPath); } while ( (client.getState() == CuratorFrameworkState.STARTED) && !haveTheLock ) { List children = getSortedChildren(); String sequenceNodeName = ourPath.substring(basePath.length() + 1); // +1 to include the slash PredicateResults predicateResults = driver.getsTheLock(client, children, sequenceNodeName, maxLeases); if ( predicateResults.getsTheLock() ) { haveTheLock = true; } else { String previousSequencePath = basePath + "/" + predicateResults.getPathToWatch(); synchronized(this) { try { // use getData() instead of exists() to avoid leaving unneeded watchers which is a type of resource leak client.getData().usingWatcher(watcher).forPath(previousSequencePath); if ( millisToWait != null ) { millisToWait -= (System.currentTimeMillis() - startMillis); startMillis = System.currentTimeMillis(); if ( millisToWait <= 0 ) { doDelete = true; // timed out - delete our node break; } wait(millisToWait); } else { wait(); } } catch ( KeeperException.NoNodeException e ) { // it has been deleted (i.e. lock released). Try to acquire again } } } } } catch ( Exception e ) { doDelete = true; throw e; } finally { if ( doDelete ) { deleteOurPath(ourPath); } } return haveTheLock; } private void deleteOurPath(String ourPath) throws Exception { try { client.delete().guaranteed().forPath(ourPath); } catch ( KeeperException.NoNodeException e ) { // ignore - already deleted (possibly expired session, etc.) } } private synchronized void notifyFromWatcher() { notifyAll(); } } LockInternalsDriver.java000066400000000000000000000023641245521677600406240ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import org.apache.curator.framework.CuratorFramework; import java.util.List; public interface LockInternalsDriver extends LockInternalsSorter { public PredicateResults getsTheLock(CuratorFramework client, List children, String sequenceNodeName, int maxLeases) throws Exception; public String createsTheLock(CuratorFramework client, String path, byte[] lockNodeBytes) throws Exception; } LockInternalsSorter.java000066400000000000000000000017171245521677600406500ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; public interface LockInternalsSorter { public String fixForSorting(String str, String lockName); } PredicateResults.java000066400000000000000000000024121245521677600401540ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; public class PredicateResults { private final boolean getsTheLock; private final String pathToWatch; public PredicateResults(String pathToWatch, boolean getsTheLock) { this.pathToWatch = pathToWatch; this.getsTheLock = getsTheLock; } public String getPathToWatch() { return pathToWatch; } public boolean getsTheLock() { return getsTheLock; } } Reaper.java000066400000000000000000000250461245521677600361200ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.leader.LeaderLatch; import org.apache.curator.framework.recipes.leader.LeaderLatchListener; import org.apache.curator.utils.CloseableScheduledExecutorService; import org.apache.curator.utils.ThreadUtils; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * Utility to clean up parent lock nodes so that they don't stay around as garbage */ public class Reaper implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework client; private final CloseableScheduledExecutorService executor; private final int reapingThresholdMs; private final Map activePaths = Maps.newConcurrentMap(); private final AtomicReference state = new AtomicReference(State.LATENT); private final LeaderLatch leaderLatch; private final AtomicBoolean reapingIsActive = new AtomicBoolean(true); private enum State { LATENT, STARTED, CLOSED } static final int DEFAULT_REAPING_THRESHOLD_MS = (int)TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES); @VisibleForTesting static final int EMPTY_COUNT_THRESHOLD = 3; @VisibleForTesting class PathHolder implements Runnable { final String path; final Mode mode; final int emptyCount; @Override public void run() { reap(this); } private PathHolder(String path, Mode mode, int emptyCount) { this.path = path; this.mode = mode; this.emptyCount = emptyCount; } } public enum Mode { /** * Reap forever, or until removePath is called for the path */ REAP_INDEFINITELY, /** * Reap until the Reaper succeeds in deleting the path */ REAP_UNTIL_DELETE, /** * Reap until the path no longer exists */ REAP_UNTIL_GONE } /** * Uses the default reaping threshold of 5 minutes and creates an internal thread pool * * @param client client */ public Reaper(CuratorFramework client) { this(client, newExecutorService(), DEFAULT_REAPING_THRESHOLD_MS, null); } /** * Uses the given reaping threshold and creates an internal thread pool * * @param client client * @param reapingThresholdMs threshold in milliseconds that determines that a path can be deleted */ public Reaper(CuratorFramework client, int reapingThresholdMs) { this(client, newExecutorService(), reapingThresholdMs, null); } /** * @param client client * @param executor thread pool * @param reapingThresholdMs threshold in milliseconds that determines that a path can be deleted */ public Reaper(CuratorFramework client, ScheduledExecutorService executor, int reapingThresholdMs) { this(client, executor, reapingThresholdMs, null); } /** * @param client client * @param executor thread pool * @param reapingThresholdMs threshold in milliseconds that determines that a path can be deleted * @param leaderPath if not null, uses a leader selection so that only 1 reaper is active in the cluster */ public Reaper(CuratorFramework client, ScheduledExecutorService executor, int reapingThresholdMs, String leaderPath) { this.client = client; this.executor = new CloseableScheduledExecutorService(executor); this.reapingThresholdMs = reapingThresholdMs / EMPTY_COUNT_THRESHOLD; LeaderLatch localLeaderLatch = null; if ( leaderPath != null ) { localLeaderLatch = makeLeaderLatch(client, leaderPath); } leaderLatch = localLeaderLatch; } /** * Add a path (using Mode.REAP_INDEFINITELY) to be checked by the reaper. The path will be checked periodically * until the reaper is closed. * * @param path path to check */ public void addPath(String path) { addPath(path, Mode.REAP_INDEFINITELY); } /** * Add a path to be checked by the reaper. The path will be checked periodically * until the reaper is closed, or until the point specified by the Mode * * @param path path to check * @param mode reaping mode */ public void addPath(String path, Mode mode) { PathHolder pathHolder = new PathHolder(path, mode, 0); activePaths.put(path, pathHolder); schedule(pathHolder, reapingThresholdMs); } /** * Stop reaping the given path * * @param path path to remove * @return true if the path was removed */ public boolean removePath(String path) { return activePaths.remove(path) != null; } /** * The reaper must be started * * @throws Exception errors */ public void start() throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); if ( leaderLatch != null ) { leaderLatch.start(); } } @Override public void close() throws IOException { if ( state.compareAndSet(State.STARTED, State.CLOSED) ) { executor.close(); if ( leaderLatch != null ) { leaderLatch.close(); } } } @VisibleForTesting protected Future schedule(PathHolder pathHolder, int reapingThresholdMs) { if ( reapingIsActive.get() ) { return executor.schedule(pathHolder, reapingThresholdMs, TimeUnit.MILLISECONDS); } return null; } @VisibleForTesting protected void reap(PathHolder holder) { if ( !activePaths.containsKey(holder.path) ) { return; } boolean addBack = true; int newEmptyCount = 0; try { Stat stat = client.checkExists().forPath(holder.path); if ( stat != null ) // otherwise already deleted { if ( stat.getNumChildren() == 0 ) { if ( (holder.emptyCount + 1) >= EMPTY_COUNT_THRESHOLD ) { try { client.delete().forPath(holder.path); log.info("Reaping path: " + holder.path); if ( holder.mode == Mode.REAP_UNTIL_DELETE || holder.mode == Mode.REAP_UNTIL_GONE ) { addBack = false; } } catch ( KeeperException.NoNodeException ignore ) { // Node must have been deleted by another process/thread if ( holder.mode == Mode.REAP_UNTIL_GONE ) { addBack = false; } } catch ( KeeperException.NotEmptyException ignore ) { // ignore - it must have been re-used } } else { newEmptyCount = holder.emptyCount + 1; } } } else { if ( holder.mode == Mode.REAP_UNTIL_GONE ) { addBack = false; } } } catch ( Exception e ) { log.error("Trying to reap: " + holder.path, e); } if ( !addBack ) { activePaths.remove(holder.path); } else if ( !Thread.currentThread().isInterrupted() && (state.get() == State.STARTED) && activePaths.containsKey(holder.path) ) { activePaths.put(holder.path, holder); schedule(new PathHolder(holder.path, holder.mode, newEmptyCount), reapingThresholdMs); } } /** * Allocate an executor service for the reaper * * @return service */ public static ScheduledExecutorService newExecutorService() { return ThreadUtils.newSingleThreadScheduledExecutor("Reaper"); } private LeaderLatch makeLeaderLatch(CuratorFramework client, String leaderPath) { reapingIsActive.set(false); LeaderLatch localLeaderLatch = new LeaderLatch(client, leaderPath); LeaderLatchListener listener = new LeaderLatchListener() { @Override public void isLeader() { reapingIsActive.set(true); for ( PathHolder holder : activePaths.values() ) { schedule(holder, reapingThresholdMs); } } @Override public void notLeader() { reapingIsActive.set(false); } }; localLeaderLatch.addListener(listener); return localLeaderLatch; } } Revocable.java000066400000000000000000000031151245521677600365750ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import java.util.concurrent.Executor; /** * Specifies locks that can be revoked */ public interface Revocable { /** * Make the lock revocable. Your listener will get called when another process/thread * wants you to release the lock. Revocation is cooperative. * * @param listener the listener */ public void makeRevocable(RevocationListener listener); /** * Make the lock revocable. Your listener will get called when another process/thread * wants you to release the lock. Revocation is cooperative. * * @param listener the listener * @param executor executor for the listener */ public void makeRevocable(RevocationListener listener, Executor executor); } RevocationListener.java000066400000000000000000000022311245521677600405100ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; public interface RevocationListener { /** * Called when a revocation request has been received. You should release the lock as soon * as possible. Revocation is cooperative. * * @param forLock the lock that should release */ public void revocationRequested(T forLock); } RevocationSpec.java000066400000000000000000000023761245521677600376270ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import java.util.concurrent.Executor; class RevocationSpec { private final Runnable runnable; private final Executor executor; RevocationSpec(Executor executor, Runnable runnable) { this.runnable = runnable; this.executor = executor; } Runnable getRunnable() { return runnable; } Executor getExecutor() { return executor; } } Revoker.java000066400000000000000000000033651245521677600363170ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.KeeperException; public class Revoker { /** * Utility to mark a lock for revocation. Assuming that the lock has been registered with * a {@link RevocationListener}, it will get called and the lock should be released. Note, * however, that revocation is cooperative. * * @param client the client * @param path the path of the lock - usually from something like * {@link InterProcessMutex#getParticipantNodes()} * @throws Exception errors */ public static void attemptRevoke(CuratorFramework client, String path) throws Exception { try { client.setData().forPath(path, LockInternals.REVOKE_MESSAGE); } catch ( KeeperException.NoNodeException ignore ) { // ignore } } private Revoker() { } } StandardLockInternalsDriver.java000066400000000000000000000057561245521677600423150ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; public class StandardLockInternalsDriver implements LockInternalsDriver { static private final Logger log = LoggerFactory.getLogger(StandardLockInternalsDriver.class); @Override public PredicateResults getsTheLock(CuratorFramework client, List children, String sequenceNodeName, int maxLeases) throws Exception { int ourIndex = children.indexOf(sequenceNodeName); validateOurIndex(sequenceNodeName, ourIndex); boolean getsTheLock = ourIndex < maxLeases; String pathToWatch = getsTheLock ? null : children.get(ourIndex - maxLeases); return new PredicateResults(pathToWatch, getsTheLock); } @Override public String createsTheLock(CuratorFramework client, String path, byte[] lockNodeBytes) throws Exception { String ourPath; if ( lockNodeBytes != null ) { ourPath = client.create().creatingParentsIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(path, lockNodeBytes); } else { ourPath = client.create().creatingParentsIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(path); } return ourPath; } @Override public String fixForSorting(String str, String lockName) { return standardFixForSorting(str, lockName); } public static String standardFixForSorting(String str, String lockName) { int index = str.lastIndexOf(lockName); if ( index >= 0 ) { index += lockName.length(); return index <= str.length() ? str.substring(index) : ""; } return str; } static void validateOurIndex(String sequenceNodeName, int ourIndex) throws KeeperException { if ( ourIndex < 0 ) { throw new KeeperException.NoNodeException("Sequential path not found: " + sequenceNodeName); } } } 000077500000000000000000000000001245521677600340255ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodesPersistentEphemeralNode.java000066400000000000000000000267621245521677600414760ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodes/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.nodes; import com.google.common.base.Preconditions; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.ACLBackgroundPathAndBytesable; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CreateModable; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.utils.PathUtils; /** *

* A persistent ephemeral node is an ephemeral node that attempts to stay present in * ZooKeeper, even through connection and session interruptions. *

*

* Thanks to bbeck (https://github.com/bbeck) for the initial coding and design *

*/ public class PersistentEphemeralNode implements Closeable { private final AtomicReference initialCreateLatch = new AtomicReference(new CountDownLatch(1)); private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework client; private final CreateModable> createMethod; private final AtomicReference nodePath = new AtomicReference(null); private final String basePath; private final Mode mode; private final AtomicReference data = new AtomicReference(); private final AtomicReference state = new AtomicReference(State.LATENT); private final BackgroundCallback backgroundCallback; private final Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { createNode(); } }; private final BackgroundCallback checkExistsCallback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getResultCode() == KeeperException.Code.NONODE.intValue() ) { createNode(); } } }; private final ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState == ConnectionState.RECONNECTED ) { createNode(); } } }; private enum State { LATENT, STARTED, CLOSED } /** * The mode for node creation */ public enum Mode { /** * Same as {@link CreateMode#EPHEMERAL} */ EPHEMERAL() { @Override protected CreateMode getCreateMode(boolean pathIsSet) { return CreateMode.EPHEMERAL; } @Override protected boolean isProtected() { return false; } }, /** * Same as {@link CreateMode#EPHEMERAL_SEQUENTIAL} */ EPHEMERAL_SEQUENTIAL() { @Override protected CreateMode getCreateMode(boolean pathIsSet) { return pathIsSet ? CreateMode.EPHEMERAL : CreateMode.EPHEMERAL_SEQUENTIAL; } @Override protected boolean isProtected() { return false; } }, /** * Same as {@link CreateMode#EPHEMERAL} with protection */ PROTECTED_EPHEMERAL() { @Override protected CreateMode getCreateMode(boolean pathIsSet) { return CreateMode.EPHEMERAL; } @Override protected boolean isProtected() { return true; } }, /** * Same as {@link CreateMode#EPHEMERAL_SEQUENTIAL} with protection */ PROTECTED_EPHEMERAL_SEQUENTIAL() { @Override protected CreateMode getCreateMode(boolean pathIsSet) { return pathIsSet ? CreateMode.EPHEMERAL : CreateMode.EPHEMERAL_SEQUENTIAL; } @Override protected boolean isProtected() { return true; } }; protected abstract CreateMode getCreateMode(boolean pathIsSet); protected abstract boolean isProtected(); } /** * @param client client instance * @param mode creation/protection mode * @param basePath the base path for the node * @param data data for the node */ public PersistentEphemeralNode(CuratorFramework client, Mode mode, String basePath, byte[] data) { this.client = Preconditions.checkNotNull(client, "client cannot be null"); this.basePath = PathUtils.validatePath(basePath); this.mode = Preconditions.checkNotNull(mode, "mode cannot be null"); data = Preconditions.checkNotNull(data, "data cannot be null"); backgroundCallback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { String path = null; if ( event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue() ) { path = event.getPath(); } else if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) { path = event.getName(); } if ( path != null ) { nodePath.set(path); watchNode(); CountDownLatch localLatch = initialCreateLatch.getAndSet(null); if ( localLatch != null ) { localLatch.countDown(); } } else { createNode(); } } }; createMethod = mode.isProtected() ? client.create().creatingParentsIfNeeded().withProtection() : client.create().creatingParentsIfNeeded(); this.data.set(Arrays.copyOf(data, data.length)); } /** * You must call start() to initiate the persistent ephemeral node. An attempt to create the node * in the background will be started */ public void start() { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Already started"); client.getConnectionStateListenable().addListener(connectionStateListener); createNode(); } /** * Block until the either initial node creation initiated by {@link #start()} succeeds or * the timeout elapses. * * @param timeout the maximum time to wait * @param unit time unit * @return if the node was created before timeout * @throws InterruptedException if the thread is interrupted */ public boolean waitForInitialCreate(long timeout, TimeUnit unit) throws InterruptedException { Preconditions.checkState(state.get() == State.STARTED, "Not started"); CountDownLatch localLatch = initialCreateLatch.get(); return (localLatch == null) || localLatch.await(timeout, unit); } @Override public void close() throws IOException { if ( !state.compareAndSet(State.STARTED, State.CLOSED) ) { return; } client.getConnectionStateListenable().removeListener(connectionStateListener); try { deleteNode(); } catch ( Exception e ) { throw new IOException(e); } } /** * Returns the currently set path or null if the node does not exist * * @return node path or null */ public String getActualPath() { return nodePath.get(); } /** * Set data that ephemeral node should set in ZK also writes the data to the node * * @param data new data value * @throws Exception errors */ public void setData(byte[] data) throws Exception { data = Preconditions.checkNotNull(data, "data cannot be null"); this.data.set(Arrays.copyOf(data, data.length)); if ( isActive() ) { client.setData().inBackground().forPath(getActualPath(), this.data.get()); } } private void deleteNode() throws Exception { String localNodePath = nodePath.getAndSet(null); if ( localNodePath != null ) { try { client.delete().guaranteed().forPath(localNodePath); } catch ( KeeperException.NoNodeException ignore ) { // ignore } catch ( Exception e ) { throw e; } } } private void createNode() { if ( !isActive() ) { return; } try { String existingPath = nodePath.get(); String createPath = (existingPath != null) ? existingPath : basePath; createMethod.withMode(mode.getCreateMode(existingPath != null)).inBackground(backgroundCallback).forPath(createPath, data.get()); } catch ( Exception e ) { throw new RuntimeException("Creating node. BasePath: " + basePath, e); // should never happen unless there's a programming error - so throw RuntimeException } } private void watchNode() throws Exception { if ( !isActive() ) { return; } String localNodePath = nodePath.get(); if ( localNodePath != null ) { try { client.checkExists().usingWatcher(watcher).inBackground(checkExistsCallback).forPath(localNodePath); } catch ( Exception e ) { throw e; } } } private boolean isActive() { return (state.get() == State.STARTED); } }000077500000000000000000000000001245521677600340415ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queueBlockingQueueConsumer.java000066400000000000000000000125661245521677600411670ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import com.google.common.collect.ImmutableList; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import java.util.Collection; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; /** * Utility - a queue consumer that provides behavior similar to a {@link BlockingQueue} */ public class BlockingQueueConsumer implements QueueConsumer { private final ConnectionStateListener connectionStateListener; private final BlockingQueue items; /** * Creates with capacity of {@link Integer#MAX_VALUE} * @param connectionStateListener listener for connection state changes */ public BlockingQueueConsumer(ConnectionStateListener connectionStateListener) { this(connectionStateListener, new LinkedBlockingQueue()); } /** * @param capacity max capacity (i.e. puts block if full) * @param connectionStateListener listener for connection state changes */ public BlockingQueueConsumer(ConnectionStateListener connectionStateListener, int capacity) { this(connectionStateListener, new ArrayBlockingQueue(capacity)); } /** * Wrap the given blocking queue * * @param queue queue to use * @param connectionStateListener listener for connection state changes */ public BlockingQueueConsumer(ConnectionStateListener connectionStateListener, BlockingQueue queue) { this.connectionStateListener = connectionStateListener; this.items = queue; } @Override public void consumeMessage(T message) throws Exception { items.add(message); } /** * Return any currently queued items without removing them from the queue * * @return items (can be empty) */ public List getItems() { return ImmutableList.copyOf(items); } /** * Returns the number of currently queue items * * @return currently queue item count or 0 */ public int size() { return items.size(); } /** * Take the next item from the queue, blocking until there is an item available * * @return the item * @throws InterruptedException thread interruption */ public T take() throws InterruptedException { return items.take(); } /** * Take the next item from the queue, waiting up to the specified time for * an available item. If the time elapses, null is returned. * * @param time amount of time to block * @param unit time unit * @return next item or null * @throws InterruptedException thread interruption */ public T take(int time, TimeUnit unit) throws InterruptedException { return items.poll(time, unit); } /** * Removes all available elements from this queue and adds them * to the given collection. This operation may be more * efficient than repeatedly polling this queue. A failure * encountered while attempting to add elements to * collection c may result in elements being in neither, * either or both collections when the associated exception is * thrown. Attempts to drain a queue to itself result in * IllegalArgumentException. Further, the behavior of * this operation is undefined if the specified collection is * modified while the operation is in progress. * * @param c the collection to transfer elements into * @return the number of elements transferred * @throws UnsupportedOperationException if addition of elements * is not supported by the specified collection * @throws ClassCastException if the class of an element of this queue * prevents it from being added to the specified collection * @throws NullPointerException if the specified collection is null * @throws IllegalArgumentException if the specified collection is this * queue, or some property of an element of this queue prevents * it from being added to the specified collection */ public int drainTo(Collection c) { return items.drainTo(c); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { connectionStateListener.stateChanged(client, newState); } } ChildrenCache.java000066400000000000000000000114101245521677600373550ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.utils.PathUtils; class ChildrenCache implements Closeable { private final CuratorFramework client; private final String path; private final AtomicReference children = new AtomicReference(new Data(Lists.newArrayList(), 0)); private final AtomicBoolean isClosed = new AtomicBoolean(false); private final CuratorWatcher watcher = new CuratorWatcher() { @Override public void process(WatchedEvent event) throws Exception { if ( !isClosed.get() ) { sync(true); } } }; private final BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) { setNewChildren(event.getChildren()); } } }; static class Data { final List children; final long version; private Data(List children, long version) { this.children = ImmutableList.copyOf(children); this.version = version; } } ChildrenCache(CuratorFramework client, String path) { this.client = client; this.path = PathUtils.validatePath(path); } void start() throws Exception { sync(true); } @Override public void close() throws IOException { isClosed.set(true); notifyFromCallback(); } Data getData() { return children.get(); } Data blockingNextGetData(long startVersion) throws InterruptedException { return blockingNextGetData(startVersion, 0, null); } synchronized Data blockingNextGetData(long startVersion, long maxWait, TimeUnit unit) throws InterruptedException { long startMs = System.currentTimeMillis(); boolean hasMaxWait = (unit != null); long maxWaitMs = hasMaxWait ? unit.toMillis(maxWait) : -1; while ( startVersion == children.get().version ) { if ( hasMaxWait ) { long elapsedMs = System.currentTimeMillis() - startMs; long thisWaitMs = maxWaitMs - elapsedMs; if ( thisWaitMs <= 0 ) { break; } wait(thisWaitMs); } else { wait(); } } return children.get(); } private synchronized void notifyFromCallback() { notifyAll(); } private synchronized void sync(boolean watched) throws Exception { if ( watched ) { client.getChildren().usingWatcher(watcher).inBackground(callback).forPath(path); } else { client.getChildren().inBackground(callback).forPath(path); } } private synchronized void setNewChildren(List newChildren) { if ( newChildren != null ) { Data currentData = children.get(); children.set(new Data(newChildren, currentData.version + 1)); notifyFromCallback(); } } } DistributedDelayQueue.java000066400000000000000000000205411245521677600411540ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.listen.ListenerContainer; import java.io.Closeable; import java.io.IOException; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; /** *

* A variation of the DistributedPriorityQueue that uses time as the priority. When items * are added to the queue, a delay value is given. The item will not be sent to a consumer * until the time elapses. *

*/ public class DistributedDelayQueue implements Closeable, QueueBase { private final DistributedQueue queue; private static final String SEPARATOR = "|"; DistributedDelayQueue ( CuratorFramework client, QueueConsumer consumer, QueueSerializer serializer, String queuePath, ThreadFactory threadFactory, Executor executor, int minItemsBeforeRefresh, String lockPath, int maxItems, boolean putInBackground, int finalFlushMs ) { Preconditions.checkArgument(minItemsBeforeRefresh >= 0, "minItemsBeforeRefresh cannot be negative"); queue = new DistributedQueue ( client, consumer, serializer, queuePath, threadFactory, executor, minItemsBeforeRefresh, true, lockPath, maxItems, putInBackground, finalFlushMs ) { @Override protected long getDelay(String itemNode) { return getDelay(itemNode, System.currentTimeMillis()); } private long getDelay(String itemNode, long sortTime) { long epoch = getEpoch(itemNode); return epoch - sortTime; } @Override protected void sortChildren(List children) { final long sortTime = System.currentTimeMillis(); Collections.sort ( children, new Comparator() { @Override public int compare(String o1, String o2) { long diff = getDelay(o1, sortTime) - getDelay(o2, sortTime); return (diff < 0) ? -1 : ((diff > 0) ? 1 : 0); } } ); } }; } /** * Start the queue. No other methods work until this is called * * @throws Exception startup errors */ @Override public void start() throws Exception { queue.start(); } @Override public void close() throws IOException { queue.close(); } /** * Add an item into the queue. Adding is done in the background - thus, this method will * return quickly.

* NOTE: if an upper bound was set via {@link QueueBuilder#maxItems}, this method will * block until there is available space in the queue. * * @param item item to add * @param delayUntilEpoch future epoch (milliseconds) when this item will be available to consumers * @throws Exception connection issues */ public void put(T item, long delayUntilEpoch) throws Exception { put(item, delayUntilEpoch, 0, null); } /** * Same as {@link #put(Object, long)} but allows a maximum wait time if an upper bound was set * via {@link QueueBuilder#maxItems}. * * @param item item to add * @param delayUntilEpoch future epoch (milliseconds) when this item will be available to consumers * @param maxWait maximum wait * @param unit wait unit * @return true if items was added, false if timed out * @throws Exception */ public boolean put(T item, long delayUntilEpoch, int maxWait, TimeUnit unit) throws Exception { Preconditions.checkArgument(delayUntilEpoch > 0, "delayUntilEpoch cannot be negative"); queue.checkState(); return queue.internalPut(item, null, queue.makeItemPath() + epochToString(delayUntilEpoch), maxWait, unit); } /** * Add a set of items with the same priority into the queue. Adding is done in the background - thus, this method will * return quickly.

* NOTE: if an upper bound was set via {@link QueueBuilder#maxItems}, this method will * block until there is available space in the queue. * * @param items items to add * @param delayUntilEpoch future epoch (milliseconds) when this item will be available to consumers * @throws Exception connection issues */ public void putMulti(MultiItem items, long delayUntilEpoch) throws Exception { putMulti(items, delayUntilEpoch, 0, null); } /** * Same as {@link #putMulti(MultiItem, long)} but allows a maximum wait time if an upper bound was set * via {@link QueueBuilder#maxItems}. * * @param items items to add * @param delayUntilEpoch future epoch (milliseconds) when this item will be available to consumers * @param maxWait maximum wait * @param unit wait unit * @return true if items was added, false if timed out * @throws Exception */ public boolean putMulti(MultiItem items, long delayUntilEpoch, int maxWait, TimeUnit unit) throws Exception { Preconditions.checkArgument(delayUntilEpoch > 0, "delayUntilEpoch cannot be negative"); queue.checkState(); return queue.internalPut(null, items, queue.makeItemPath() + epochToString(delayUntilEpoch), maxWait, unit); } @Override public void setErrorMode(ErrorMode newErrorMode) { queue.setErrorMode(newErrorMode); } @Override public boolean flushPuts(long waitTime, TimeUnit timeUnit) throws InterruptedException { return queue.flushPuts(waitTime, timeUnit); } /** * Return the manager for put listeners * * @return put listener container */ @Override public ListenerContainer> getPutListenerContainer() { return queue.getPutListenerContainer(); } /** * Return the most recent message count from the queue. This is useful for debugging/information * purposes only. * * @return count (can be 0) */ @Override public int getLastMessageCount() { return queue.getLastMessageCount(); } @VisibleForTesting static String epochToString(long epoch) { return SEPARATOR + String.format("%08X", epoch) + SEPARATOR; } private static long getEpoch(String itemNode) { int index2 = itemNode.lastIndexOf(SEPARATOR); int index1 = (index2 > 0) ? itemNode.lastIndexOf(SEPARATOR, index2 - 1) : -1; if ( (index1 > 0) && (index2 > (index1 + 1)) ) { try { String epochStr = itemNode.substring(index1 + 1, index2); return Long.parseLong(epochStr, 16); } catch ( NumberFormatException ignore ) { // ignore } } return 0; } } DistributedIdQueue.java000066400000000000000000000147541245521677600404630ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import com.google.common.base.Preconditions; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.listen.ListenerContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; /** * A version of {@link DistributedQueue} that allows IDs to be associated with queue items. Items * can then be removed from the queue if needed */ public class DistributedIdQueue implements QueueBase { private final Logger log = LoggerFactory.getLogger(getClass()); private final DistributedQueue queue; private static final char SEPARATOR = '|'; private static class Parts { final String id; final String cleaned; private Parts(String id, String cleaned) { this.id = id; this.cleaned = cleaned; } } DistributedIdQueue ( CuratorFramework client, QueueConsumer consumer, QueueSerializer serializer, String queuePath, ThreadFactory threadFactory, Executor executor, int minItemsBeforeRefresh, boolean refreshOnWatch, String lockPath, int maxItems, boolean putInBackground, int finalFlushMs ) { queue = new DistributedQueue(client, consumer, serializer, queuePath, threadFactory, executor, minItemsBeforeRefresh, refreshOnWatch, lockPath, maxItems, putInBackground, finalFlushMs) { @Override protected void sortChildren(List children) { internalSortChildren(children); } }; if ( queue.makeItemPath().contains(Character.toString(SEPARATOR)) ) { throw new IllegalStateException("DistributedQueue can't use " + SEPARATOR); } } @Override public void start() throws Exception { queue.start(); } @Override public void close() throws IOException { queue.close(); } @Override public ListenerContainer> getPutListenerContainer() { return queue.getPutListenerContainer(); } @Override public void setErrorMode(ErrorMode newErrorMode) { queue.setErrorMode(newErrorMode); } @Override public boolean flushPuts(long waitTime, TimeUnit timeUnit) throws InterruptedException { return queue.flushPuts(waitTime, timeUnit); } @Override public int getLastMessageCount() { return queue.getLastMessageCount(); } /** * Put an item into the queue with the given Id

* NOTE: if an upper bound was set via {@link QueueBuilder#maxItems}, this method will * block until there is available space in the queue. * * @param item item * @param itemId item Id * @throws Exception errors */ public void put(T item, String itemId) throws Exception { put(item, itemId, 0, null); } /** * Same as {@link #put(Object, String)} but allows a maximum wait time if an upper bound was set * via {@link QueueBuilder#maxItems}. * * @param item item * @param itemId item Id * @param maxWait maximum wait * @param unit wait unit * @return true if items was added, false if timed out * @throws Exception */ public boolean put(T item, String itemId, int maxWait, TimeUnit unit) throws Exception { Preconditions.checkArgument(isValidId(itemId), "Invalid id: " + itemId); queue.checkState(); return queue.internalPut(item, null, queue.makeItemPath() + SEPARATOR + fixId(itemId) + SEPARATOR, maxWait, unit); } /** * Remove any items with the given Id * * @param id item Id to remove * @return number of items removed * @throws Exception errors */ public int remove(String id) throws Exception { id = Preconditions.checkNotNull(id, "id cannot be null"); queue.checkState(); int count = 0; for ( String name : queue.getChildren() ) { if ( parseId(name).id.equals(id) ) { if ( queue.tryRemove(name) ) { ++count; } } } return count; } private void internalSortChildren(List children) { Collections.sort ( children, new Comparator() { @Override public int compare(String o1, String o2) { return parseId(o1).cleaned.compareTo(parseId(o2).cleaned); } } ); } private boolean isValidId(String id) { return (id != null) && (id.length() > 0); } private static String fixId(String id) { String fixed = id.replace('/', '_'); return fixed.replace(SEPARATOR, '_'); } private Parts parseId(String name) { int firstIndex = name.indexOf(SEPARATOR); int secondIndex = name.indexOf(SEPARATOR, firstIndex + 1); if ( (firstIndex < 0) || (secondIndex < 0) ) { log.error("Bad node in queue: " + name); return new Parts(name, name); } return new Parts ( name.substring(firstIndex + 1, secondIndex), name.substring(0, firstIndex) + name.substring(secondIndex + 1) ); } } DistributedPriorityQueue.java000066400000000000000000000154571245521677600417510ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.listen.ListenerContainer; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.Executor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; /** *

An implementation of the Distributed Priority Queue ZK recipe.

*

Internally, this uses a {@link DistributedQueue}. The only difference is that you specify a * priority when putting into the queue.

*

IMPORTANT NOTE: The priority queue will perform far worse than a standard queue. Every time an * item is added to/removed from the queue, every watcher must re-get all the nodes

*/ public class DistributedPriorityQueue implements Closeable, QueueBase { private final DistributedQueue queue; DistributedPriorityQueue ( CuratorFramework client, QueueConsumer consumer, QueueSerializer serializer, String queuePath, ThreadFactory threadFactory, Executor executor, int minItemsBeforeRefresh, String lockPath, int maxItems, boolean putInBackground, int finalFlushMs ) { Preconditions.checkArgument(minItemsBeforeRefresh >= 0, "minItemsBeforeRefresh cannot be negative"); queue = new DistributedQueue ( client, consumer, serializer, queuePath, threadFactory, executor, minItemsBeforeRefresh, true, lockPath, maxItems, putInBackground, finalFlushMs ); } /** * Start the queue. No other methods work until this is called * * @throws Exception startup errors */ @Override public void start() throws Exception { queue.start(); } @Override public void close() throws IOException { queue.close(); } /** * Add an item into the queue. Adding is done in the background - thus, this method will * return quickly.

* NOTE: if an upper bound was set via {@link QueueBuilder#maxItems}, this method will * block until there is available space in the queue. * * @param item item to add * @param priority item's priority - lower numbers come out of the queue first * @throws Exception connection issues */ public void put(T item, int priority) throws Exception { put(item, priority, 0, null); } /** * Same as {@link #put(Object, int)} but allows a maximum wait time if an upper bound was set * via {@link QueueBuilder#maxItems}. * * @param item item to add * @param priority item's priority - lower numbers come out of the queue first * @param maxWait maximum wait * @param unit wait unit * @return true if items was added, false if timed out * @throws Exception */ public boolean put(T item, int priority, int maxWait, TimeUnit unit) throws Exception { queue.checkState(); String priorityHex = priorityToString(priority); return queue.internalPut(item, null, queue.makeItemPath() + priorityHex, maxWait, unit); } /** * Add a set of items with the same priority into the queue. Adding is done in the background - thus, this method will * return quickly.

* NOTE: if an upper bound was set via {@link QueueBuilder#maxItems}, this method will * block until there is available space in the queue. * * @param items items to add * @param priority item priority - lower numbers come out of the queue first * @throws Exception connection issues */ public void putMulti(MultiItem items, int priority) throws Exception { putMulti(items, priority, 0, null); } /** * Same as {@link #putMulti(MultiItem, int)} but allows a maximum wait time if an upper bound was set * via {@link QueueBuilder#maxItems}. * * @param items items to add * @param priority item priority - lower numbers come out of the queue first * @param maxWait maximum wait * @param unit wait unit * @return true if items was added, false if timed out * @throws Exception */ public boolean putMulti(MultiItem items, int priority, int maxWait, TimeUnit unit) throws Exception { queue.checkState(); String priorityHex = priorityToString(priority); return queue.internalPut(null, items, queue.makeItemPath() + priorityHex, maxWait, unit); } @Override public void setErrorMode(ErrorMode newErrorMode) { queue.setErrorMode(newErrorMode); } @Override public boolean flushPuts(long waitTime, TimeUnit timeUnit) throws InterruptedException { return queue.flushPuts(waitTime, timeUnit); } /** * Return the manager for put listeners * * @return put listener container */ @Override public ListenerContainer> getPutListenerContainer() { return queue.getPutListenerContainer(); } /** * Return the most recent message count from the queue. This is useful for debugging/information * purposes only. * * @return count (can be 0) */ @Override public int getLastMessageCount() { return queue.getLastMessageCount(); } @VisibleForTesting ChildrenCache getCache() { return queue.getCache(); } @VisibleForTesting static String priorityToString(int priority) { // the padded hex val of the number prefixed with a 0 for negative numbers // and a 1 for positive (so that it sorts correctly) long l = (long)priority & 0xFFFFFFFFL; return String.format("%s%08X", (priority >= 0) ? "1" : "0", l); } } DistributedQueue.java000066400000000000000000000613541245521677600402040ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.framework.imps.CuratorFrameworkState; import org.apache.curator.framework.listen.ListenerContainer; import org.apache.curator.framework.recipes.leader.LeaderSelector; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.utils.PathUtils; /** *

An implementation of the Distributed Queue ZK recipe. Items put into the queue * are guaranteed to be ordered (by means of ZK's PERSISTENT_SEQUENTIAL node).

* *

* Guarantees:

*
    *
  • If a single consumer takes items out of the queue, they will be ordered FIFO. i.e. if ordering is important, * use a {@link LeaderSelector} to nominate a single consumer.
  • *
  • Unless a {@link QueueBuilder#lockPath(String)} is used, there is only guaranteed processing of each message to the point of receipt by a given instance. *
  • If an instance receives an item from the queue but dies while processing it, the item will be lost. If you need message recoverability, use * a {@link QueueBuilder#lockPath(String)}
  • *
*/ public class DistributedQueue implements QueueBase { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework client; private final QueueSerializer serializer; private final String queuePath; private final Executor executor; private final ExecutorService service; private final AtomicReference state = new AtomicReference(State.LATENT); private final QueueConsumer consumer; private final int minItemsBeforeRefresh; private final boolean refreshOnWatch; private final boolean isProducerOnly; private final String lockPath; private final AtomicReference errorMode = new AtomicReference(ErrorMode.REQUEUE); private final ListenerContainer> putListenerContainer = new ListenerContainer>(); private final AtomicInteger lastChildCount = new AtomicInteger(0); private final int maxItems; private final int finalFlushMs; private final boolean putInBackground; private final ChildrenCache childrenCache; private final AtomicInteger putCount = new AtomicInteger(0); private enum State { LATENT, STARTED, STOPPED } @VisibleForTesting protected enum ProcessType { NORMAL, REMOVE } private static final String QUEUE_ITEM_NAME = "queue-"; DistributedQueue ( CuratorFramework client, QueueConsumer consumer, QueueSerializer serializer, String queuePath, ThreadFactory threadFactory, Executor executor, int minItemsBeforeRefresh, boolean refreshOnWatch, String lockPath, int maxItems, boolean putInBackground, int finalFlushMs ) { Preconditions.checkNotNull(client, "client cannot be null"); Preconditions.checkNotNull(serializer, "serializer cannot be null"); Preconditions.checkNotNull(threadFactory, "threadFactory cannot be null"); Preconditions.checkNotNull(executor, "executor cannot be null"); Preconditions.checkArgument(maxItems > 0, "maxItems must be a positive number"); isProducerOnly = (consumer == null); this.lockPath = (lockPath == null) ? null : PathUtils.validatePath(lockPath); this.putInBackground = putInBackground; this.consumer = consumer; this.minItemsBeforeRefresh = minItemsBeforeRefresh; this.refreshOnWatch = refreshOnWatch; this.client = client; this.serializer = serializer; this.queuePath = PathUtils.validatePath(queuePath); this.executor = executor; this.maxItems = maxItems; this.finalFlushMs = finalFlushMs; service = Executors.newFixedThreadPool(2, threadFactory); childrenCache = new ChildrenCache(client, queuePath); if ( (maxItems != QueueBuilder.NOT_SET) && putInBackground ) { log.warn("Bounded queues should set putInBackground(false) in the builder. Putting in the background will result in spotty maxItem consistency."); } } /** * Start the queue. No other methods work until this is called * * @throws Exception startup errors */ @Override public void start() throws Exception { if ( !state.compareAndSet(State.LATENT, State.STARTED) ) { throw new IllegalStateException(); } try { client.create().creatingParentsIfNeeded().forPath(queuePath); } catch ( KeeperException.NodeExistsException ignore ) { // this is OK } if ( lockPath != null ) { try { client.create().creatingParentsIfNeeded().forPath(lockPath); } catch ( KeeperException.NodeExistsException ignore ) { // this is OK } } if ( !isProducerOnly || (maxItems != QueueBuilder.NOT_SET) ) { childrenCache.start(); } if ( !isProducerOnly ) { service.submit ( new Callable() { @Override public Object call() { runLoop(); return null; } } ); } } @Override public void close() throws IOException { if ( state.compareAndSet(State.STARTED, State.STOPPED) ) { if ( finalFlushMs > 0 ) { try { flushPuts(finalFlushMs, TimeUnit.MILLISECONDS); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } } CloseableUtils.closeQuietly(childrenCache); putListenerContainer.clear(); service.shutdownNow(); } } /** * Return the manager for put listeners * * @return put listener container */ @Override public ListenerContainer> getPutListenerContainer() { return putListenerContainer; } /** * Used when the queue is created with a {@link QueueBuilder#lockPath(String)}. Determines * the behavior when the queue consumer throws an exception * * @param newErrorMode the new error mode (the default is {@link ErrorMode#REQUEUE} */ @Override public void setErrorMode(ErrorMode newErrorMode) { Preconditions.checkNotNull(lockPath, "lockPath cannot be null"); if ( newErrorMode == ErrorMode.REQUEUE ) { log.warn("ErrorMode.REQUEUE requires ZooKeeper version 3.4.x+ - make sure you are not using a prior version"); } errorMode.set(newErrorMode); } /** * Wait until any pending puts are committed * * @param waitTime max wait time * @param timeUnit time unit * @return true if the flush was successful, false if it timed out first * @throws InterruptedException if thread was interrupted */ @Override public boolean flushPuts(long waitTime, TimeUnit timeUnit) throws InterruptedException { long msWaitRemaining = TimeUnit.MILLISECONDS.convert(waitTime, timeUnit); synchronized(putCount) { while ( putCount.get() > 0 ) { if ( msWaitRemaining <= 0 ) { return false; } long startMs = System.currentTimeMillis(); putCount.wait(msWaitRemaining); long elapsedMs = System.currentTimeMillis() - startMs; msWaitRemaining -= elapsedMs; } } return true; } /** * Add an item into the queue. Adding is done in the background - thus, this method will * return quickly.

* NOTE: if an upper bound was set via {@link QueueBuilder#maxItems}, this method will * block until there is available space in the queue. * * @param item item to add * @throws Exception connection issues */ public void put(T item) throws Exception { put(item, 0, null); } /** * Same as {@link #put(Object)} but allows a maximum wait time if an upper bound was set * via {@link QueueBuilder#maxItems}. * * @param item item to add * @param maxWait maximum wait * @param unit wait unit * @return true if items was added, false if timed out * @throws Exception */ public boolean put(T item, int maxWait, TimeUnit unit) throws Exception { checkState(); String path = makeItemPath(); return internalPut(item, null, path, maxWait, unit); } /** * Add a set of items into the queue. Adding is done in the background - thus, this method will * return quickly.

* NOTE: if an upper bound was set via {@link QueueBuilder#maxItems}, this method will * block until there is available space in the queue. * * @param items items to add * @throws Exception connection issues */ public void putMulti(MultiItem items) throws Exception { putMulti(items, 0, null); } /** * Same as {@link #putMulti(MultiItem)} but allows a maximum wait time if an upper bound was set * via {@link QueueBuilder#maxItems}. * * @param items items to add * @param maxWait maximum wait * @param unit wait unit * @return true if items was added, false if timed out * @throws Exception */ public boolean putMulti(MultiItem items, int maxWait, TimeUnit unit) throws Exception { checkState(); String path = makeItemPath(); return internalPut(null, items, path, maxWait, unit); } /** * Return the most recent message count from the queue. This is useful for debugging/information * purposes only. * * @return count (can be 0) */ @Override public int getLastMessageCount() { return lastChildCount.get(); } boolean internalPut(final T item, MultiItem multiItem, String path, int maxWait, TimeUnit unit) throws Exception { if ( !blockIfMaxed(maxWait, unit) ) { return false; } final MultiItem givenMultiItem = multiItem; if ( item != null ) { final AtomicReference ref = new AtomicReference(item); multiItem = new MultiItem() { @Override public T nextItem() throws Exception { return ref.getAndSet(null); } }; } putCount.incrementAndGet(); byte[] bytes = ItemSerializer.serialize(multiItem, serializer); if ( putInBackground ) { doPutInBackground(item, path, givenMultiItem, bytes); } else { doPutInForeground(item, path, givenMultiItem, bytes); } return true; } private void doPutInForeground(final T item, String path, final MultiItem givenMultiItem, byte[] bytes) throws Exception { client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath(path, bytes); synchronized(putCount) { putCount.decrementAndGet(); putCount.notifyAll(); } putListenerContainer.forEach ( new Function, Void>() { @Override public Void apply(QueuePutListener listener) { if ( item != null ) { listener.putCompleted(item); } else { listener.putMultiCompleted(givenMultiItem); } return null; } } ); } private void doPutInBackground(final T item, String path, final MultiItem givenMultiItem, byte[] bytes) throws Exception { BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getResultCode() != KeeperException.Code.OK.intValue() ) { return; } if ( event.getType() == CuratorEventType.CREATE ) { synchronized(putCount) { putCount.decrementAndGet(); putCount.notifyAll(); } } putListenerContainer.forEach ( new Function, Void>() { @Override public Void apply(QueuePutListener listener) { if ( item != null ) { listener.putCompleted(item); } else { listener.putMultiCompleted(givenMultiItem); } return null; } } ); } }; internalCreateNode(path, bytes, callback); } @VisibleForTesting void internalCreateNode(String path, byte[] bytes, BackgroundCallback callback) throws Exception { client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).inBackground(callback).forPath(path, bytes); } void checkState() throws Exception { if ( state.get() != State.STARTED ) { throw new IllegalStateException(); } } String makeItemPath() { return ZKPaths.makePath(queuePath, QUEUE_ITEM_NAME); } @VisibleForTesting ChildrenCache getCache() { return childrenCache; } protected void sortChildren(List children) { Collections.sort(children); } protected List getChildren() throws Exception { return client.getChildren().forPath(queuePath); } protected long getDelay(String itemNode) { return 0; } protected boolean tryRemove(String itemNode) throws Exception { boolean isUsingLockSafety = (lockPath != null); if ( isUsingLockSafety ) { return processWithLockSafety(itemNode, ProcessType.REMOVE); } return processNormally(itemNode, ProcessType.REMOVE); } private boolean blockIfMaxed(int maxWait, TimeUnit unit) throws Exception { ChildrenCache.Data data = childrenCache.getData(); while ( data.children.size() >= maxItems ) { long previousVersion = data.version; data = childrenCache.blockingNextGetData(data.version, maxWait, unit); if ( data.version == previousVersion ) { return false; } } return true; } private void runLoop() { long currentVersion = -1; long maxWaitMs = -1; try { while ( !Thread.currentThread().isInterrupted() ) { ChildrenCache.Data data = (maxWaitMs > 0) ? childrenCache.blockingNextGetData(currentVersion, maxWaitMs, TimeUnit.MILLISECONDS) : childrenCache.blockingNextGetData(currentVersion); currentVersion = data.version; List children = Lists.newArrayList(data.children); sortChildren(children); // makes sure items are processed in the correct order if ( children.size() > 0 ) { maxWaitMs = getDelay(children.get(0)); if ( maxWaitMs > 0 ) { continue; } } else { continue; } processChildren(children, currentVersion); } } catch ( InterruptedException ignore ) { Thread.currentThread().interrupt(); } catch ( Exception e ) { log.error("Exception caught in background handler", e); } } private void processChildren(List children, long currentVersion) throws Exception { final Semaphore processedLatch = new Semaphore(0); final boolean isUsingLockSafety = (lockPath != null); int min = minItemsBeforeRefresh; for ( final String itemNode : children ) { if ( Thread.currentThread().isInterrupted() ) { processedLatch.release(children.size()); break; } if ( !itemNode.startsWith(QUEUE_ITEM_NAME) ) { log.warn("Foreign node in queue path: " + itemNode); processedLatch.release(); continue; } if ( min-- <= 0 ) { if ( refreshOnWatch && (currentVersion != childrenCache.getData().version) ) { processedLatch.release(children.size()); break; } } if ( getDelay(itemNode) > 0 ) { processedLatch.release(); continue; } executor.execute ( new Runnable() { @Override public void run() { try { if ( isUsingLockSafety ) { processWithLockSafety(itemNode, ProcessType.NORMAL); } else { processNormally(itemNode, ProcessType.NORMAL); } } catch ( Exception e ) { log.error("Error processing message at " + itemNode, e); } finally { processedLatch.release(); } } } ); } processedLatch.acquire(children.size()); } private enum ProcessMessageBytesCode { NORMAL, REQUEUE } private ProcessMessageBytesCode processMessageBytes(String itemNode, byte[] bytes) throws Exception { ProcessMessageBytesCode resultCode = ProcessMessageBytesCode.NORMAL; MultiItem items; try { items = ItemSerializer.deserialize(bytes, serializer); } catch ( Throwable e ) { log.error("Corrupted queue item: " + itemNode, e); return resultCode; } for(;;) { T item = items.nextItem(); if ( item == null ) { break; } try { consumer.consumeMessage(item); } catch ( Throwable e ) { log.error("Exception processing queue item: " + itemNode, e); if ( errorMode.get() == ErrorMode.REQUEUE ) { resultCode = ProcessMessageBytesCode.REQUEUE; break; } } } return resultCode; } private boolean processNormally(String itemNode, ProcessType type) throws Exception { try { String itemPath = ZKPaths.makePath(queuePath, itemNode); Stat stat = new Stat(); byte[] bytes = null; if ( type == ProcessType.NORMAL ) { bytes = client.getData().storingStatIn(stat).forPath(itemPath); } if ( client.getState() == CuratorFrameworkState.STARTED ) { client.delete().withVersion(stat.getVersion()).forPath(itemPath); } if ( type == ProcessType.NORMAL ) { processMessageBytes(itemNode, bytes); } return true; } catch ( KeeperException.NodeExistsException ignore ) { // another process got it } catch ( KeeperException.NoNodeException ignore ) { // another process got it } catch ( KeeperException.BadVersionException ignore ) { // another process got it } return false; } @VisibleForTesting protected boolean processWithLockSafety(String itemNode, ProcessType type) throws Exception { String lockNodePath = ZKPaths.makePath(lockPath, itemNode); boolean lockCreated = false; try { client.create().withMode(CreateMode.EPHEMERAL).forPath(lockNodePath); lockCreated = true; String itemPath = ZKPaths.makePath(queuePath, itemNode); boolean requeue = false; byte[] bytes = null; if ( type == ProcessType.NORMAL ) { bytes = client.getData().forPath(itemPath); requeue = (processMessageBytes(itemNode, bytes) == ProcessMessageBytesCode.REQUEUE); } if ( requeue ) { client.inTransaction() .delete().forPath(itemPath) .and() .create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath(makeItemPath(), bytes) .and() .commit(); } else { client.delete().forPath(itemPath); } return true; } catch ( KeeperException.NodeExistsException ignore ) { // another process got it } catch ( KeeperException.NoNodeException ignore ) { // another process got it } catch ( KeeperException.BadVersionException ignore ) { // another process got it } finally { if ( lockCreated ) { client.delete().guaranteed().forPath(lockNodePath); } } return false; } } ErrorMode.java000066400000000000000000000023451245521677600366060ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; /** * Used when the queue is created with a {@link QueueBuilder#lockPath(String)}. Determines * the behavior when the queue consumer throws an exception */ public enum ErrorMode { /** * If the consumer throws an exception, requeue the message. This is the default. */ REQUEUE, /** * If the consumer throws an exception, delete the message */ DELETE } ItemSerializer.java000066400000000000000000000072011245521677600376340ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import com.google.common.collect.Lists; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.List; class ItemSerializer { private static final int VERSION = 0x00010001; private static final byte ITEM_OPCODE = 0x01; private static final byte EOF_OPCODE = 0x02; private static final int INITIAL_BUFFER_SIZE = 0x1000; static MultiItem deserialize(byte[] bytes, QueueSerializer serializer) throws Exception { DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes)); int version = in.readInt(); if ( version != VERSION ) { throw new IOException(String.format("Incorrect version. Expected %d - Found: %d", VERSION, version)); } List items = Lists.newArrayList(); for(;;) { byte opcode = in.readByte(); if ( opcode == EOF_OPCODE ) { break; } if ( opcode != ITEM_OPCODE ) { throw new IOException(String.format("Incorrect opcode. Expected %d - Found: %d", ITEM_OPCODE, opcode)); } int size = in.readInt(); if ( size < 0 ) { throw new IOException(String.format("Bad size: %d", size)); } byte[] itemBytes = new byte[size]; if ( size > 0 ) { in.readFully(itemBytes); } items.add(serializer.deserialize(itemBytes)); } final Iterator iterator = items.iterator(); return new MultiItem() { @Override public T nextItem() { return iterator.hasNext() ? iterator.next() : null; } }; } static byte[] serialize(MultiItem items, QueueSerializer serializer) throws Exception { ByteArrayOutputStream bytes = new ByteArrayOutputStream(INITIAL_BUFFER_SIZE); DataOutputStream out = new DataOutputStream(bytes); out.writeInt(VERSION); for(;;) { T item = items.nextItem(); if ( item == null ) { break; } byte[] itemBytes = serializer.serialize(item); out.writeByte(ITEM_OPCODE); out.writeInt(itemBytes.length); if ( itemBytes.length > 0 ) { out.write(itemBytes); } } out.writeByte(EOF_OPCODE); out.close(); return bytes.toByteArray(); } private ItemSerializer() { } } MultiItem.java000066400000000000000000000024551245521677600366230ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; /** * Abstraction for multiple items. * @see DistributedQueue#putMulti(MultiItem) * @see DistributedPriorityQueue#putMulti(MultiItem, int) */ public interface MultiItem { /** * Called repeatedly to get the items to add to the queue. This method * should return null when there are no more items to add. * * @return item or null * @throws Exception any errors */ public T nextItem() throws Exception; } QueueAllocator.java000066400000000000000000000020361245521677600376320ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import org.apache.curator.framework.CuratorFramework; public interface QueueAllocator> { public T allocateQueue(CuratorFramework client, String queuePath); } QueueBase.java000066400000000000000000000043551245521677600365720ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import org.apache.curator.framework.listen.ListenerContainer; import java.io.Closeable; import java.util.concurrent.TimeUnit; public interface QueueBase extends Closeable { /** * Start the queue. No other methods work until this is called * * @throws Exception startup errors */ void start() throws Exception; /** * Return the manager for put listeners * * @return put listener container */ ListenerContainer> getPutListenerContainer(); /** * Used when the queue is created with a {@link QueueBuilder#lockPath(String)}. Determines * the behavior when the queue consumer throws an exception * * @param newErrorMode the new error mode (the default is {@link ErrorMode#REQUEUE} */ void setErrorMode(ErrorMode newErrorMode); /** * Wait until any pending puts are committed * * @param waitTime max wait time * @param timeUnit time unit * @return true if the flush was successful, false if it timed out first * @throws InterruptedException if thread was interrupted */ boolean flushPuts(long waitTime, TimeUnit timeUnit) throws InterruptedException; /** * Return the most recent message count from the queue. This is useful for debugging/information * purposes only. * * @return count (can be 0) */ int getLastMessageCount(); } QueueBuilder.java000066400000000000000000000221141245521677600372770ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.MoreExecutors; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.ThreadUtils; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.apache.curator.utils.PathUtils; /** * The builder for both {@link DistributedQueue} and {@link DistributedPriorityQueue} */ public class QueueBuilder { private final CuratorFramework client; private final QueueConsumer consumer; private final QueueSerializer serializer; private final String queuePath; private ThreadFactory factory; private Executor executor; private String lockPath; private int maxItems = NOT_SET; private boolean putInBackground = true; private int finalFlushMs = 5000; static final ThreadFactory defaultThreadFactory = ThreadUtils.newThreadFactory("QueueBuilder"); static final int NOT_SET = Integer.MAX_VALUE; /** * Allocate a new builder * * * @param client the curator client * @param consumer functor to consume messages - NOTE: pass null to make this a producer-only queue * @param serializer serializer to use for items * @param queuePath path to store queue * @return builder */ public static QueueBuilder builder(CuratorFramework client, QueueConsumer consumer, QueueSerializer serializer, String queuePath) { return new QueueBuilder(client, consumer, serializer, queuePath); } /** * Build a {@link DistributedQueue} from the current builder values * * @return distributed queue */ public DistributedQueue buildQueue() { return new DistributedQueue ( client, consumer, serializer, queuePath, factory, executor, Integer.MAX_VALUE, false, lockPath, maxItems, putInBackground, finalFlushMs ); } /** * Build a {@link DistributedIdQueue} from the current builder values * * @return distributed id queue */ public DistributedIdQueue buildIdQueue() { return new DistributedIdQueue ( client, consumer, serializer, queuePath, factory, executor, Integer.MAX_VALUE, false, lockPath, maxItems, putInBackground, finalFlushMs ); } /** *

Build a {@link DistributedPriorityQueue} from the current builder values.

* *

When the priority * queue detects an item addition/removal, it will stop processing its current list of items and * refresh the list. minItemsBeforeRefresh modifies this. It determines the minimum * number of items from the active list that will get processed before a refresh.

* *

Due to a quirk in the way ZooKeeper notifies changes, the queue will get an item addition/remove * notification after every item is processed. This can lead to poor performance. Set * minItemsBeforeRefresh to the value your application can tolerate being out of sync.

* *

For example: if the queue sees 10 items to process, it will end up making 10 calls to ZooKeeper * to check status. You can control this by setting minItemsBeforeRefresh to 10 (or more) * and the queue will only refresh with ZooKeeper after 10 items are processed

* * @param minItemsBeforeRefresh minimum items to process before refreshing the item list * @return distributed priority queue */ public DistributedPriorityQueue buildPriorityQueue(int minItemsBeforeRefresh) { return new DistributedPriorityQueue ( client, consumer, serializer, queuePath, factory, executor, minItemsBeforeRefresh, lockPath, maxItems, putInBackground, finalFlushMs ); } /** *

Build a {@link DistributedDelayQueue} from the current builder values.

* * @return distributed delay queue */ public DistributedDelayQueue buildDelayQueue() { return new DistributedDelayQueue ( client, consumer, serializer, queuePath, factory, executor, Integer.MAX_VALUE, lockPath, maxItems, putInBackground, finalFlushMs ); } /** * Change the thread factory used. The default is {@link Executors#defaultThreadFactory()} * * @param factory new thread factory to use * @return this */ public QueueBuilder threadFactory(ThreadFactory factory) { Preconditions.checkNotNull(factory, "factory cannot be null"); this.factory = factory; return this; } /** * Change the executor used. The default is {@link MoreExecutors#sameThreadExecutor()} * * @param executor new executor to use * @return this */ public QueueBuilder executor(Executor executor) { Preconditions.checkNotNull(executor, "executor cannot be null"); this.executor = executor; return this; } /** *

Without a lock set, queue items are removed before being sent to the queue consumer. This can result in message * loss if the consumer fails to complete the message or the process dies.

* *

Use a lock to make the message recoverable. A lock is held while * the message is being processed - this prevents other processes from taking the message. The message will not be removed * from the queue until the consumer functor returns. Thus, if there is a failure or the process dies, * the message will get sent to another process. There is a small performance penalty for this behavior however. * * @param path path for the lock * @return this */ public QueueBuilder lockPath(String path) { lockPath = PathUtils.validatePath(path); return this; } /** * By default, the various queues are unbounded. This method allows setting a max number of items * to have in the queue. With this value set, the various put methods will block when the * number of items in the queue approaches maxItems. NOTE: maxItems cannot * be exactly achieved. The only guarantee is that approximately maxItems will cause * puts to block. * * @param maxItems the upper bound for the queue * @return this */ public QueueBuilder maxItems(int maxItems) { this.maxItems = maxItems; putInBackground = false; return this; } /** * By default, messages are added in the background. However, this can flood the background thread. * * @param putInBackground true to put in the background (default). false to put in the foreground. * @return this */ public QueueBuilder putInBackground(boolean putInBackground) { this.putInBackground = putInBackground; return this; } /** * Sets an amount of time to call {@link DistributedQueue#flushPuts(long, TimeUnit)} when the * queue is closed. The default is 5 seconds. Pass 0 to turn flushing on close off. * * @param time time * @param unit the unit * @return this */ public QueueBuilder finalFlushTime(int time, TimeUnit unit) { finalFlushMs = (int)unit.toMillis(time); return this; } private QueueBuilder(CuratorFramework client, QueueConsumer consumer, QueueSerializer serializer, String queuePath) { this.client = client; this.consumer = consumer; this.serializer = serializer; this.queuePath = PathUtils.validatePath(queuePath); factory = defaultThreadFactory; executor = MoreExecutors.sameThreadExecutor(); } } QueueConsumer.java000066400000000000000000000023241245521677600375050ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import org.apache.curator.framework.state.ConnectionStateListener; /** * Message Consumer */ public interface QueueConsumer extends ConnectionStateListener { /** * Process a message from the queue * * @param message message to process * @throws Exception any errors */ public void consumeMessage(T message) throws Exception; } QueuePutListener.java000066400000000000000000000024731245521677600401750ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; /** * Queue puts are done in the background. Use this listener to * be notified when the put completes */ public interface QueuePutListener { /** * Notification that a single item put has completed * * @param item the item */ public void putCompleted(T item); /** * Notification that a multi item put has completed * * @param items the items */ public void putMultiCompleted(MultiItem items); } QueueSafety.java000066400000000000000000000036241245521677600371510ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import java.util.concurrent.BlockingQueue; import org.apache.curator.utils.PathUtils; /** * Parameter block for specifying queue safety with either {@link DistributedQueue} or * {@link DistributedPriorityQueue} */ public class QueueSafety { private final String lockPath; private final QueueConsumer consumer; private final BlockingQueue queue; /** * @param lockPath ZKPath to use for locking purposes * @param consumer the message consumer */ public QueueSafety(String lockPath, QueueConsumer consumer) { this.lockPath = PathUtils.validatePath(lockPath); this.consumer = consumer; this.queue = null; } QueueSafety(String lockPath, BlockingQueue queue) { this.lockPath = PathUtils.validatePath(lockPath); this.consumer = null; this.queue = queue; } String getLockPath() { return lockPath; } QueueConsumer getConsumer() { return consumer; } BlockingQueue getQueue() { return queue; } } QueueSerializer.java000066400000000000000000000024241245521677600400240ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; /** * Helper to serialize/deserialize queue items */ public interface QueueSerializer { /** * Turn a queue item into bytes * * @param item the item * @return byte representation */ public byte[] serialize(T item); /** * Deserialize bytes into a queue item * * @param bytes byte representation * @return item */ public T deserialize(byte[] bytes); } QueueSharder.java000066400000000000000000000227701245521677600373110ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.leader.LeaderLatch; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Random; import java.util.Set; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; /** *

* A utility for shard a distributed queue. *

* *

* Due to limitations in ZooKeeper's transport layer, * a single queue will break if it has more than 10K-ish items in it. This class * provides a facade over multiple distributed queues. It monitors the queues and if * any one of them goes over a threshold, a new queue is added. Puts are distributed * amongst the queues. *

* *

* NOTE: item ordering is maintained within each managed queue but cannot be maintained across * queues. i.e. items might get consumed out of order if they are in different managed * queues. *

*/ public class QueueSharder> implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework client; private final QueueAllocator queueAllocator; private final String queuePath; private final QueueSharderPolicies policies; private final ConcurrentMap queues = Maps.newConcurrentMap(); private final Set preferredQueues = Sets.newSetFromMap(Maps.newConcurrentMap()); private final AtomicReference state = new AtomicReference(State.LATENT); private final LeaderLatch leaderLatch; private final Random random = new Random(); private final ExecutorService service; private static final String QUEUE_PREFIX = "queue-"; private enum State { LATENT, STARTED, CLOSED } /** * @param client client * @param queueAllocator allocator for new queues * @param queuePath path for the queues * @param leaderPath path for the leader that monitors queue sizes (must be different than queuePath) * @param policies sharding policies */ public QueueSharder(CuratorFramework client, QueueAllocator queueAllocator, String queuePath, String leaderPath, QueueSharderPolicies policies) { this.client = client; this.queueAllocator = queueAllocator; this.queuePath = queuePath; this.policies = policies; leaderLatch = new LeaderLatch(client, leaderPath); service = Executors.newSingleThreadExecutor(policies.getThreadFactory()); } /** * The sharder must be started * * @throws Exception errors */ public void start() throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); client.newNamespaceAwareEnsurePath(queuePath).ensure(client.getZookeeperClient()); getInitialQueues(); leaderLatch.start(); service.submit ( new Callable() { @Override public Void call() throws Exception { try { while ( !Thread.currentThread().isInterrupted() && (state.get() == State.STARTED) ) { Thread.sleep(policies.getThresholdCheckMs()); checkThreshold(); } } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } return null; } } ); } @Override public void close() { if ( state.compareAndSet(State.STARTED, State.CLOSED) ) { service.shutdownNow(); CloseableUtils.closeQuietly(leaderLatch); for ( T queue : queues.values() ) { try { queue.close(); } catch ( IOException e ) { log.error("Closing a queue", e); } } } } /** * Return one of the managed queues - the selection method cannot be relied on. It should * be considered a random managed queue. * * @return a queue */ public T getQueue() { Preconditions.checkState(state.get() == State.STARTED, "Not started"); List localPreferredQueues = Lists.newArrayList(preferredQueues); if ( localPreferredQueues.size() > 0 ) { String key = localPreferredQueues.get(random.nextInt(localPreferredQueues.size())); return queues.get(key); } List keys = Lists.newArrayList(queues.keySet()); String key = keys.get(random.nextInt(keys.size())); return queues.get(key); } /** * Return the current number of mananged queues * * @return qty */ public int getShardQty() { return queues.size(); } /** * Return the current set of shard paths * * @return paths */ public Collection getQueuePaths() { return ImmutableSet.copyOf(queues.keySet()); } private void getInitialQueues() throws Exception { List children = client.getChildren().forPath(queuePath); for ( String child : children ) { String queuePath = ZKPaths.makePath(this.queuePath, child); addNewQueueIfNeeded(queuePath); } if ( children.size() == 0 ) { addNewQueueIfNeeded(null); } } private void addNewQueueIfNeeded(String newQueuePath) throws Exception { if ( newQueuePath == null ) { newQueuePath = ZKPaths.makePath(queuePath, QUEUE_PREFIX + UUID.randomUUID().toString()); } if ( !queues.containsKey(newQueuePath) ) { T queue = queueAllocator.allocateQueue(client, newQueuePath); if ( queues.putIfAbsent(newQueuePath, queue) == null ) { queue.start(); preferredQueues.add(newQueuePath); } } } private void checkThreshold() { try { boolean addAQueueIfLeader = false; int size = 0; List children = client.getChildren().forPath(queuePath); for ( String child : children ) { String queuePath = ZKPaths.makePath(this.queuePath, child); addNewQueueIfNeeded(queuePath); Stat stat = client.checkExists().forPath(queuePath); if ( stat.getNumChildren() >= policies.getNewQueueThreshold() ) { size = stat.getNumChildren(); addAQueueIfLeader = true; preferredQueues.remove(queuePath); } else if ( stat.getNumChildren() <= (policies.getNewQueueThreshold() / 2) ) { preferredQueues.add(queuePath); } } if ( addAQueueIfLeader && leaderLatch.hasLeadership() ) { if ( queues.size() < policies.getMaxQueues() ) { log.info(String.format("Adding a queue due to exceeded threshold. Queue Size: %d - Threshold: %d", size, policies.getNewQueueThreshold())); addNewQueueIfNeeded(null); } else { log.warn(String.format("Max number of queues (%d) reached. Consider increasing the max.", policies.getMaxQueues())); } } } catch ( Exception e ) { log.error("Checking queue counts against threshold", e); } } } QueueSharderPolicies.java000066400000000000000000000110231245521677600407660ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import com.google.common.base.Preconditions; import java.util.concurrent.ThreadFactory; /** * Various policies/options for sharding. Usage: * QueueSharderPolicies.builder().foo().bar().build(); */ public class QueueSharderPolicies { private int newQueueThreshold; private int thresholdCheckMs; private int maxQueues; private ThreadFactory threadFactory; private static final int DEFAULT_QUEUE_THRESHOLD = 10000; private static final int DEFAULT_THRESHOLD_CHECK_MS = 30000; private static final int DEFAULT_MAX_QUEUES = 10; public static class Builder { private QueueSharderPolicies policies = new QueueSharderPolicies(); /** * Change the queue threshold. This is the number of items that causes * a new queue to be added. The default is {@link QueueSharderPolicies#DEFAULT_QUEUE_THRESHOLD} * * @param newQueueThreshold new value * @return this */ public Builder newQueueThreshold(int newQueueThreshold) { Preconditions.checkArgument(newQueueThreshold > 0, "newQueueThreshold must be a positive number"); policies.newQueueThreshold = newQueueThreshold; return this; } /** * Change the threshold check. This is how often the queue sizes are checked. The default * is {@link QueueSharderPolicies#DEFAULT_THRESHOLD_CHECK_MS} * * @param thresholdCheckMs period in milliseconds * @return this */ public Builder thresholdCheckMs(int thresholdCheckMs) { Preconditions.checkArgument(thresholdCheckMs > 0, "thresholdCheckMs must be a positive number"); policies.thresholdCheckMs = thresholdCheckMs; return this; } /** * Change the maximum number of queues to create. The default value is {@link QueueSharderPolicies#DEFAULT_MAX_QUEUES} * * @param maxQueues the new max * @return this */ public Builder maxQueues(int maxQueues) { Preconditions.checkArgument(maxQueues > 0, "thresholdCheckMs must be a positive number"); policies.maxQueues = maxQueues; return this; } /** * Change the thread factory that's used to create the sharder's thread * * @param threadFactory new factory * @return this */ public Builder threadFactory(ThreadFactory threadFactory) { policies.threadFactory = Preconditions.checkNotNull(threadFactory, "threadFactory cannot be null"); return this; } public QueueSharderPolicies build() { try { return policies; } finally { policies = new QueueSharderPolicies(); } } private Builder() { } } /** * Allocate a new builder * * @return builder */ public static Builder builder() { return new Builder(); } int getNewQueueThreshold() { return newQueueThreshold; } int getThresholdCheckMs() { return thresholdCheckMs; } int getMaxQueues() { return maxQueues; } ThreadFactory getThreadFactory() { return threadFactory; } private QueueSharderPolicies() { this.newQueueThreshold = DEFAULT_QUEUE_THRESHOLD; this.thresholdCheckMs = DEFAULT_THRESHOLD_CHECK_MS; this.maxQueues = DEFAULT_MAX_QUEUES; this.threadFactory = QueueBuilder.defaultThreadFactory; } } SimpleDistributedQueue.java000066400000000000000000000175161245521677600413570ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.EnsurePath; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.curator.utils.PathUtils; /** *

* Drop in replacement for: org.apache.zookeeper.recipes.queue.DistributedQueue that is part of * the ZooKeeper distribution *

* *

* This class is data compatible with the ZK version. i.e. it uses the same naming scheme so * it can read from an existing queue *

*/ public class SimpleDistributedQueue { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework client; private final String path; private final EnsurePath ensurePath; private final String PREFIX = "qn-"; /** * @param client the client * @param path path to store queue nodes */ public SimpleDistributedQueue(CuratorFramework client, String path) { this.client = client; this.path = PathUtils.validatePath(path); ensurePath = client.newNamespaceAwareEnsurePath(path); } /** * Return the head of the queue without modifying the queue. * * @return the data at the head of the queue. * @throws Exception errors * @throws NoSuchElementException if the queue is empty */ public byte[] element() throws Exception { byte[] bytes = internalElement(false, null); if ( bytes == null ) { throw new NoSuchElementException(); } return bytes; } /** * Attempts to remove the head of the queue and return it. * * @return The former head of the queue * @throws Exception errors * @throws NoSuchElementException if the queue is empty */ public byte[] remove() throws Exception { byte[] bytes = internalElement(true, null); if ( bytes == null ) { throw new NoSuchElementException(); } return bytes; } /** * Removes the head of the queue and returns it, blocks until it succeeds. * * @return The former head of the queue * @throws Exception errors */ public byte[] take() throws Exception { return internalPoll(0, null); } /** * Inserts data into queue. * * @param data the data * @return true if data was successfully added * @throws Exception errors */ public boolean offer(byte[] data) throws Exception { ensurePath.ensure(client.getZookeeperClient()); String thisPath = ZKPaths.makePath(path, PREFIX); client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath(thisPath, data); return true; } /** * Returns the data at the first element of the queue, or null if the queue is empty. * * @return data at the first element of the queue, or null. * @throws Exception errors */ public byte[] peek() throws Exception { try { return element(); } catch ( NoSuchElementException e ) { return null; } } /** * Retrieves and removes the head of this queue, waiting up to the * specified wait time if necessary for an element to become available. * * @param timeout how long to wait before giving up, in units of * unit * @param unit a TimeUnit determining how to interpret the * timeout parameter * @return the head of this queue, or null if the * specified waiting time elapses before an element is available * @throws Exception errors */ public byte[] poll(long timeout, TimeUnit unit) throws Exception { return internalPoll(timeout, unit); } /** * Attempts to remove the head of the queue and return it. Returns null if the queue is empty. * * @return Head of the queue or null. * @throws Exception errors */ public byte[] poll() throws Exception { try { return remove(); } catch ( NoSuchElementException e ) { return null; } } private byte[] internalPoll(long timeout, TimeUnit unit) throws Exception { ensurePath.ensure(client.getZookeeperClient()); long startMs = System.currentTimeMillis(); boolean hasTimeout = (unit != null); long maxWaitMs = hasTimeout ? TimeUnit.MILLISECONDS.convert(timeout, unit) : Long.MAX_VALUE; for(;;) { final CountDownLatch latch = new CountDownLatch(1); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { latch.countDown(); } }; byte[] bytes = internalElement(true, watcher); if ( bytes != null ) { return bytes; } if ( hasTimeout ) { long elapsedMs = System.currentTimeMillis() - startMs; long thisWaitMs = maxWaitMs - elapsedMs; if ( thisWaitMs <= 0 ) { return null; } latch.await(thisWaitMs, TimeUnit.MILLISECONDS); } else { latch.await(); } } } private byte[] internalElement(boolean removeIt, Watcher watcher) throws Exception { ensurePath.ensure(client.getZookeeperClient()); List nodes; try { nodes = (watcher != null) ? client.getChildren().usingWatcher(watcher).forPath(path) : client.getChildren().forPath(path); } catch ( KeeperException.NoNodeException dummy ) { return null; } Collections.sort(nodes); for ( String node : nodes ) { if ( !node.startsWith(PREFIX) ) { log.warn("Foreign node in queue path: " + node); continue; } String thisPath = ZKPaths.makePath(path, node); try { byte[] bytes = client.getData().forPath(thisPath); if ( removeIt ) { client.delete().forPath(thisPath); } return bytes; } catch ( KeeperException.NoNodeException ignore ) { //Another client removed the node first, try next } } return null; } } 000077500000000000000000000000001245521677600341635ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/sharedSharedCount.java000066400000000000000000000145221245521677600372510ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.shared; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Maps; import com.google.common.util.concurrent.MoreExecutors; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.listen.Listenable; import org.apache.curator.framework.state.ConnectionState; import java.io.Closeable; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Map; import java.util.concurrent.Executor; /** * Manages a shared integer. All clients watching the same path will have the up-to-date * value of the shared integer (considering ZK's normal consistency guarantees). */ public class SharedCount implements Closeable, SharedCountReader, Listenable { private final Map listeners = Maps.newConcurrentMap(); private final SharedValue sharedValue; /** * @param client the client * @param path the shared path - i.e. where the shared count is stored * @param seedValue the initial value for the count if/f the path has not yet been created */ public SharedCount(CuratorFramework client, String path, int seedValue) { sharedValue = new SharedValue(client, path, toBytes(seedValue)); } @Override public int getCount() { return fromBytes(sharedValue.getValue()); } @Override public VersionedValue getVersionedValue() { VersionedValue localValue = sharedValue.getVersionedValue(); return new VersionedValue(localValue.getVersion(), fromBytes(localValue.getValue())); } /** * Change the shared count value irrespective of its previous state * * @param newCount new value * @throws Exception ZK errors, interruptions, etc. */ public void setCount(int newCount) throws Exception { sharedValue.setValue(toBytes(newCount)); } /** * Changes the shared count only if its value has not changed since this client last * read it. If the count has changed, the value is not set and this client's view of the * value is updated. i.e. if the count is not successful you can get the updated value * by calling {@link #getCount()}. * * @deprecated use {@link #trySetCount(VersionedValue, int)} for stronger atomicity * guarantees. Even if this object's internal state is up-to-date, the caller has no way to * ensure that they've read the most recently seen count. * * @param newCount the new value to attempt * @return true if the change attempt was successful, false if not. If the change * was not successful, {@link #getCount()} will return the updated value * @throws Exception ZK errors, interruptions, etc. */ @Deprecated public boolean trySetCount(int newCount) throws Exception { return sharedValue.trySetValue(toBytes(newCount)); } /** * Changes the shared count only if its value has not changed since the version specified by * newCount. If the count has changed, the value is not set and this client's view of the * value is updated. i.e. if the count is not successful you can get the updated value * by calling {@link #getCount()}. * * @param newCount the new value to attempt * @return true if the change attempt was successful, false if not. If the change * was not successful, {@link #getCount()} will return the updated value * @throws Exception ZK errors, interruptions, etc. */ public boolean trySetCount(VersionedValue previous, int newCount) throws Exception { VersionedValue previousCopy = new VersionedValue(previous.getVersion(), toBytes(previous.getValue())); return sharedValue.trySetValue(previousCopy, toBytes(newCount)); } @Override public void addListener(SharedCountListener listener) { addListener(listener, MoreExecutors.sameThreadExecutor()); } @Override public void addListener(final SharedCountListener listener, Executor executor) { SharedValueListener valueListener = new SharedValueListener() { @Override public void valueHasChanged(SharedValueReader sharedValue, byte[] newValue) throws Exception { listener.countHasChanged(SharedCount.this, fromBytes(newValue)); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { listener.stateChanged(client, newState); } }; sharedValue.getListenable().addListener(valueListener, executor); listeners.put(listener, valueListener); } @Override public void removeListener(SharedCountListener listener) { listeners.remove(listener); } /** * The shared count must be started before it can be used. Call {@link #close()} when you are * finished with the shared count * * @throws Exception ZK errors, interruptions, etc. */ public void start() throws Exception { sharedValue.start(); } @Override public void close() throws IOException { sharedValue.close(); } @VisibleForTesting static byte[] toBytes(int value) { byte[] bytes = new byte[4]; ByteBuffer.wrap(bytes).putInt(value); return bytes; } private static int fromBytes(byte[] bytes) { return ByteBuffer.wrap(bytes).getInt(); } } SharedCountListener.java000066400000000000000000000025051245521677600407550ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.shared; import org.apache.curator.framework.state.ConnectionStateListener; /** * Listener for changes to a shared count */ public interface SharedCountListener extends ConnectionStateListener { /** * Called when the shared value has changed * * @param sharedCount the shared count instance * @param newCount the new count * @throws Exception errors */ public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception; } SharedCountReader.java000066400000000000000000000025201245521677600403670ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.shared; import org.apache.curator.framework.listen.Listenable; /** * Abstracts a shared integer and allows listening for changes to its value */ public interface SharedCountReader extends Listenable { /** * Return the current value of the count * * @return count */ public int getCount(); /** * Return the current count and version * * @return count and version */ public VersionedValue getVersionedValue(); } SharedValue.java000066400000000000000000000236321245521677600372370ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.shared; import com.google.common.base.Function; import com.google.common.base.Preconditions; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.curator.framework.listen.ListenerContainer; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.utils.PathUtils; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.atomic.AtomicReference; /** * Manages a shared value. All clients watching the same path will have the up-to-date * value (considering ZK's normal consistency guarantees). */ public class SharedValue implements Closeable, SharedValueReader { private final Logger log = LoggerFactory.getLogger(getClass()); private final ListenerContainer listeners = new ListenerContainer(); private final CuratorFramework client; private final String path; private final byte[] seedValue; private final AtomicReference state = new AtomicReference(State.LATENT); private final AtomicReference> currentValue; private final CuratorWatcher watcher = new CuratorWatcher() { @Override public void process(WatchedEvent event) throws Exception { if ( state.get() == State.STARTED ) { readValue(); notifyListeners(); } } }; private final ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { notifyListenerOfStateChanged(newState); } }; private enum State { LATENT, STARTED, CLOSED } /** * @param client the client * @param path the shared path - i.e. where the shared value is stored * @param seedValue the initial value for the value if/f the path has not yet been created */ public SharedValue(CuratorFramework client, String path, byte[] seedValue) { this.client = client; this.path = PathUtils.validatePath(path); this.seedValue = Arrays.copyOf(seedValue, seedValue.length); currentValue = new AtomicReference>(new VersionedValue(0, Arrays.copyOf(seedValue, seedValue.length))); } @Override public byte[] getValue() { VersionedValue localCopy = currentValue.get(); return Arrays.copyOf(localCopy.getValue(), localCopy.getValue().length); } @Override public VersionedValue getVersionedValue() { VersionedValue localCopy = currentValue.get(); return new VersionedValue(localCopy.getVersion(), Arrays.copyOf(localCopy.getValue(), localCopy.getValue().length)); } /** * Change the shared value value irrespective of its previous state * * @param newValue new value * @throws Exception ZK errors, interruptions, etc. */ public void setValue(byte[] newValue) throws Exception { Preconditions.checkState(state.get() == State.STARTED, "not started"); Stat result = client.setData().forPath(path, newValue); updateValue(result.getVersion(), Arrays.copyOf(newValue, newValue.length)); } /** * Changes the shared value only if its value has not changed since this client last * read it. If the value has changed, the value is not set and this client's view of the * value is updated. i.e. if the value is not successful you can get the updated value * by calling {@link #getValue()}. * * @deprecated use {@link #trySetValue(VersionedValue, byte[])} for stronger atomicity * guarantees. Even if this object's internal state is up-to-date, the caller has no way to * ensure that they've read the most recently seen value. * * @param newValue the new value to attempt * @return true if the change attempt was successful, false if not. If the change * was not successful, {@link #getValue()} will return the updated value * @throws Exception ZK errors, interruptions, etc. */ @Deprecated public boolean trySetValue(byte[] newValue) throws Exception { return trySetValue(currentValue.get(), newValue); } /** * Changes the shared value only if its value has not changed since the version specified by * newValue. If the value has changed, the value is not set and this client's view of the * value is updated. i.e. if the value is not successful you can get the updated value * by calling {@link #getValue()}. * * @param newValue the new value to attempt * @return true if the change attempt was successful, false if not. If the change * was not successful, {@link #getValue()} will return the updated value * @throws Exception ZK errors, interruptions, etc. */ public boolean trySetValue(VersionedValue previous, byte[] newValue) throws Exception { Preconditions.checkState(state.get() == State.STARTED, "not started"); VersionedValue current = currentValue.get(); if ( previous.getVersion() != current.getVersion() || !Arrays.equals(previous.getValue(), current.getValue()) ) { return false; } try { Stat result = client.setData().withVersion(previous.getVersion()).forPath(path, newValue); updateValue(result.getVersion(), Arrays.copyOf(newValue, newValue.length)); return true; } catch ( KeeperException.BadVersionException ignore ) { // ignore } readValue(); return false; } private void updateValue(int version, byte[] bytes) { while (true) { VersionedValue current = currentValue.get(); if (current.getVersion() >= version) { // A newer version was concurrently set. return; } if ( currentValue.compareAndSet(current, new VersionedValue(version, bytes)) ) { // Successfully set. return; } // Lost a race, retry. } } /** * Returns the listenable * * @return listenable */ public ListenerContainer getListenable() { return listeners; } /** * The shared value must be started before it can be used. Call {@link #close()} when you are * finished with the shared value * * @throws Exception ZK errors, interruptions, etc. */ public void start() throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); client.getConnectionStateListenable().addListener(connectionStateListener); try { client.create().creatingParentsIfNeeded().forPath(path, seedValue); } catch ( KeeperException.NodeExistsException ignore ) { // ignore } readValue(); } @Override public void close() throws IOException { client.getConnectionStateListenable().removeListener(connectionStateListener); state.set(State.CLOSED); listeners.clear(); } private void readValue() throws Exception { Stat localStat = new Stat(); byte[] bytes = client.getData().storingStatIn(localStat).usingWatcher(watcher).forPath(path); updateValue(localStat.getVersion(), bytes); } private void notifyListeners() { final byte[] localValue = getValue(); listeners.forEach ( new Function() { @Override public Void apply(SharedValueListener listener) { try { listener.valueHasChanged(SharedValue.this, localValue); } catch ( Exception e ) { log.error("From SharedValue listener", e); } return null; } } ); } private void notifyListenerOfStateChanged(final ConnectionState newState) { listeners.forEach ( new Function() { @Override public Void apply(SharedValueListener listener) { listener.stateChanged(client, newState); return null; } } ); } } SharedValueListener.java000066400000000000000000000025001245521677600407340ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.shared; import org.apache.curator.framework.state.ConnectionStateListener; /** * Listener for changes to a shared value */ public interface SharedValueListener extends ConnectionStateListener { /** * Called when the shared value has changed * * @param sharedValue the shared value instance * @param newValue the new value * @throws Exception errors */ public void valueHasChanged(SharedValueReader sharedValue, byte[] newValue) throws Exception; } SharedValueReader.java000066400000000000000000000026731245521677600403640ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.shared; import org.apache.curator.framework.listen.ListenerContainer; /** * Abstracts a shared value and allows listening for changes to the value */ public interface SharedValueReader { /** * Return the current value of the count * * @return count */ public byte[] getValue(); /** * Return the current version and value * * @return version/value */ public VersionedValue getVersionedValue(); /** * Returns the listenable * * @return listenable */ public ListenerContainer getListenable(); } VersionedValue.java000066400000000000000000000026271245521677600377700ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.shared; import com.google.common.base.Preconditions; /** * POJO for a version and a value */ public class VersionedValue { private final int version; private final T value; /** * @param version the version * @param value the value (cannot be null) */ VersionedValue(int version, T value) { this.version = version; this.value = Preconditions.checkNotNull(value, "value cannot be null"); } public int getVersion() { return version; } public T getValue() { return value; } } curator-apache-curator-2.7.1/curator-recipes/src/site/000077500000000000000000000000001245521677600227555ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/site/confluence/000077500000000000000000000000001245521677600250765ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/site/confluence/barrier.confluence000066400000000000000000000014661245521677600305760ustar00rootroot00000000000000h1. Barrier h2. Description An implementation of the Distributed Barrier ZK recipe. Distributed systems use barriers to block processing of a set of nodes until a condition is met at which time all the nodes are allowed to proceed. h2. Participating Classes * DistributedBarrier h2. Usage h3. Creating a DistributedBarrier {code} public DistributedBarrier(CuratorFramework client, String barrierPath) Parameters: client - client barrierPath - path to use as the barrier {code} h2. General Usage To wait on the barrier: {code} public void waitOnBarrier() {code} There are utilities for setting/removing the barrier: {code} setBarrier(); removeBarrier(); {code} h2. Error Handling DistributedBarrier instances watch for connection loss and will throw an exception from {{waitOnBarrier()}}. curator-apache-curator-2.7.1/curator-recipes/src/site/confluence/distributed-atomic-long.confluence000066400000000000000000000041501245521677600336720ustar00rootroot00000000000000h1. Distributed Atomic Long h2. Description A counter that attempts atomic increments. It first tries using optimistic locking. If that fails, an optional InterProcessMutex is taken. For both optimistic and mutex, a retry policy is used to retry the increment h2. Participating Classes * DistributedAtomicLong * AtomicValue * PromotedToLock h2. Usage h3. Creating a DistributedAtomicLong Optimistic mode only: {code} public DistributedAtomicLong(CuratorFramework client, String counterPath, RetryPolicy retryPolicy) Creates the counter in optimistic mode only - i.e. the promotion to a mutex is not done Parameters: client - the client counterPath - path to hold the counter value retryPolicy - the retry policy to use {code} Mutex promotion mode: {code} public DistributedAtomicLong(CuratorFramework client, String counterPath, RetryPolicy retryPolicy, PromotedToLock promotedToLock) Creates the counter in mutex promotion mode. The optimistic lock will be tried first using the given retry policy. If the increment does not succeed, a InterProcessMutex will be tried with its own retry policy Parameters: client - the client counterPath - path to hold the counter value retryPolicy - the retry policy to use promotedToLock - the arguments for the mutex promotion {code} h2. General Usage # Perform an operation on the counter: ** {{get()}} ** {{increment()}} ** {{decrement()}} ** {{add()}} ** {{subtract()}} # Examine the result AtomicValue: ** You *must* first check {{succeeded()}} which returns true if the operation succeeded. If false is returned, the operation failed and the atomic was not updated. ** If the operation succeeded, you can get the value prior to the operation via {{preValue()}} and the value after the operation {{postValue()}} h2. Error Handling All the atomic instances access the ZooKeeper server for each method call. Therefore, the standard retry mechanism will be applied and any errors executing the operations will result in an Exception being thrown. curator-apache-curator-2.7.1/curator-recipes/src/site/confluence/distributed-delay-queue.confluence000066400000000000000000000054771245521677600337160ustar00rootroot00000000000000h1. Distributed Delay Queue h2. *IMPORTANT* \- We recommend that you do NOT use ZooKeeper for Queues. Please see [[Tech Note 4|https://cwiki.apache.org/confluence/display/CURATOR/TN4]] for details. h2. Description An implementation of a Distributed Delay Queue. A Delay Queue is similar to a Priority Queue. When items are added to the queue, a delay value is given. The item will not be sent to a consumer until the time elapses. h2. Participating Classes * QueueBuilder * QueueConsumer * QueueSerializer * DistributedDelayQueue h2. Usage h3. Creating a DistributedDelayQueue {code} public static QueueBuilder builder(CuratorFramework client, QueueConsumer consumer, QueueSerializer serializer, java.lang.String queuePath) Parameters: client - the curator client consumer - message consumer serializer - serializer to use for items queuePath - path to store queue {code} {code} QueueBuilder builder = QueueBuilder.builder(client, consumer, serializer, path); ... more builder method calls as needed ... DistributedDelayQueue queue = builder.buildDelayQueue(); {code} h2. General Usage The queue must be started via the {{start()}} method. Call {{close()}} when you are done with the queue. To add messages to the queue: {code}{code} queue.put(aMessage, delayUntilEpoch); {code} The consumer ({{QueueConsumer.consumeMessage()}}) will get called as messages arrive. {{delayUntilEpoch}} is a future epoch (milliseconds) when this item will be available to consumers. h2. Lock Safety In the general usage case, the message is removed from the queue prior to the consumer being called. A more atomic mode is provided that removes the item from the queue only after the consumer successfully returns. To enable this mode, call the {{lockPath()}} method of the Queue Builder. This uses a lock to make the message recoverable. A lock is held while the message is being processed \- this prevents other processes from taking the message. The message will not be removed from the queue until the consumer functor returns. Thus, if there is a failure or the process dies, the message will get sent to another process. There is a small performance penalty for this behavior however. h2. Data Format Same as [[Distributed Queue|distributed-queue.html]]. h2. Error Handling The {{QueueConsumer}} class extends {{ConnectionStateListener}}. When the queue is started, it adds the listener to the Curator instance. Users of the {{DistributedPriorityQueue}} must pay attention to any connection state changes. If the SUSPENDED state is reported, the instance must assume that, until it receives a RECONNECTED state, the queue is no longer being updated. If the LOST state is reported, the queue is permanently down. curator-apache-curator-2.7.1/curator-recipes/src/site/confluence/distributed-id-queue.confluence000066400000000000000000000025411245521677600332010ustar00rootroot00000000000000h1. Distributed ID Queue h2. *IMPORTANT* \- We recommend that you do NOT use ZooKeeper for Queues. Please see [[Tech Note 4|https://cwiki.apache.org/confluence/display/CURATOR/TN4]] for details. h2. Description This is an alternate version of [[Distributed Queue|distributed-queue.html]] that supports assigning IDs to the items added to the queue. Items put into the queue are guaranteed to be ordered (by means of ZK's PERSISTENT_SEQUENTIAL node). If a single consumer takes items out of the queue, they will be ordered FIFO. If ordering is important, use a LeaderSelector to nominate a single consumer. h2. Participating Classes * QueueBuilder * QueueConsumer * QueueSerializer * DistributedQueue h2. Usage h3. Creating a DistributedIdQueue See [[Distributed Queue|distributed-queue.html]] for details of using the builder, the only difference is to use the {{buildIdQueue()}} method. h2. General Usage The queue must be started via the {{start()}} method. Call {{close()}} when you are done with the queue. To add messages to the queue: {code} queue.put(aMessage, messageId); {code} To remove messages from the queue: {code} int numberRemoved = queue.remove(messageId); {code} Your consumer ({{QueueConsumer.consumeMessage()}}) will get called as messages arrive. The lock safety and error handling are the same as for [[Distributed Queue|distributed-queue.html]].distributed-priority-queue.confluence000066400000000000000000000071661245521677600344170ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/site/confluenceh1. Distributed Priority Queue h2. *IMPORTANT* \- We recommend that you do NOT use ZooKeeper for Queues. Please see [[Tech Note 4|https://cwiki.apache.org/confluence/display/CURATOR/TN4]] for details. h2. Description An implementation of the Distributed Priority Queue ZK recipe. h2. Participating Classes * QueueBuilder * QueueConsumer * QueueSerializer * DistributedPriorityQueue h2. Usage h3. Creating a DistributedPriorityQueue {code} public static QueueBuilder builder(CuratorFramework client, QueueConsumer consumer, QueueSerializer serializer, java.lang.String queuePath) Parameters: client - the curator client consumer - message consumer serializer - serializer to use for items queuePath - path to store queue {code} {code} QueueBuilder builder = QueueBuilder.builder(client, consumer, serializer, path); ... more builder method calls as needed ... DistributedPriorityQueue queue = builder.buildPriorityQueue(minItemsBeforeRefresh); {code} {code} public DistributedPriorityQueue buildPriorityQueue(int minItemsBeforeRefresh) Build a DistributedPriorityQueue from the current builder values. When the priority queue detects an item addition/removal, it will stop processing its current list of items and refresh the list. minItemsBeforeRefresh modifies this. It determines the minimum number of items from the active list that will get processed before a refresh. Due to a quirk in the way ZooKeeper notifies changes, the queue will get an item addition/remove notification after every item is processed. This can lead to poor performance. Set minItemsBeforeRefresh to the value your application can tolerate being out of sync. For example: if the queue sees 10 items to process, it will end up making 10 calls to ZooKeeper to check status. You can control this by setting minItemsBeforeRefresh to 10 (or more) and the queue will only refresh with ZooKeeper after 10 items are processed Parameters: minItemsBeforeRefresh - minimum items to process before refreshing the item list {code} h2. General Usage The queue must be started via the {{start()}} method. Call {{close()}} when you are done with the queue. To add messages to the queue: {code} queue.put(aMessage, priority); {code} The consumer ({{QueueConsumer.consumeMessage()}}) will get called as messages arrive. h2. Lock Safety In the general usage case, the message is removed from the queue prior to the consumer being called. A more atomic mode is provided that removes the item from the queue only after the consumer successfully returns. To enable this mode, call the {{lockPath()}} method of the Queue Builder. This uses a lock to make the message recoverable. A lock is held while the message is being processed \- this prevents other processes from taking the message. The message will not be removed from the queue until the consumer functor returns. Thus, if there is a failure or the process dies, the message will get sent to another process. There is a small performance penalty for this behavior however. h2. Data Format Same as [[Distributed Queue|distributed-queue.html]]. h2. Error Handling The {{QueueConsumer}} class extends {{ConnectionStateListener}}. When the queue is started, it adds the listener to the Curator instance. Users of the {{DistributedPriorityQueue}} must pay attention to any connection state changes. If the SUSPENDED state is reported, the instance must assume that, until it receives a RECONNECTED state, the queue is no longer being updated. If the LOST state is reported, the queue is permanently down. curator-apache-curator-2.7.1/curator-recipes/src/site/confluence/distributed-queue.confluence000066400000000000000000000060041245521677600326050ustar00rootroot00000000000000h1. Distributed Queue h2. *IMPORTANT* \- We recommend that you do NOT use ZooKeeper for Queues. Please see [[Tech Note 4|https://cwiki.apache.org/confluence/display/CURATOR/TN4]] for details. h2. Description An implementation of the Distributed Queue ZK recipe. Items put into the queue are guaranteed to be ordered (by means of ZK's PERSISTENT_SEQUENTIAL node). If a single consumer takes items out of the queue, they will be ordered FIFO. If ordering is important, use a LeaderSelector to nominate a single consumer. h2. Participating Classes * QueueBuilder * QueueConsumer * QueueSerializer * DistributedQueue h2. Usage h3. Creating a DistributedQueue {code} public static QueueBuilder builder(CuratorFramework client, QueueConsumer consumer, QueueSerializer serializer, java.lang.String queuePath) Parameters: client - the curator client consumer - functor to receive messages serializer - serializer to use for items queuePath - path to store queue {code} {code} QueueBuilder builder = QueueBuilder.builder(client, consumer, serializer, path); ... more builder method calls as needed ... DistributedQueue locks) Creates a multi lock of any type of inter process lock Parameters: locks - the locks {code} {code} public InterProcessMultiLock(CuratorFramework client, List paths) Creates a multi lock of InterProcessMutexes Parameters: client - client paths - list of paths to manage in the order that they are to be locked {code} h2. General Usage The usage is the same as for [[Shared Lock|shared-lock.html]]. However, When acquire() is called, all the locks are acquired. If that fails, any paths that were acquired are released. Similarly, when release() is called, all locks are released (failures are ignored). h2. Error Handling It is strongly recommended that you add a {{ConnectionStateListener}} and watch for SUSPENDED and LOST state changes. If a SUSPENDED state is reported you cannot be certain that you still hold the lock unless you subsequently receive a RECONNECTED state. If a LOST state is reported it is certain that you no longer hold the lock. curator-apache-curator-2.7.1/curator-recipes/src/site/confluence/node-cache.confluence000066400000000000000000000017551245521677600311370ustar00rootroot00000000000000h1. Node Cache h2. Description A Node Cache is used to watch a ZNode. Whenever the data is modified or the ZNode is deleted, the Node Cache will change its state to contain the current data (or null if ZNode was deleted). h2. Participating Classes * NodeCache * NodeCacheListener * ChildData h2. Usage h3. Creating a NodeChildrenCache {code} public NodeCache(CuratorFramework client, String path) Parameters: client - the client path - path to cache {code} h2. General Usage The cache must be started by calling {{start()}}. Call {{close()}} when you are through with the cache. At any time, call {{getCurrentData()}} to get the current state of the cache. You can also register to be notified when a change occurs by calling {{getListenable()}} and then: {code} public void addListener(NodeCacheListener listener) Add a change listener Parameters: listener - the listener {code} h2. Error Handling NodeCache instances internally monitor a {{ConnectionStateListener}}. curator-apache-curator-2.7.1/curator-recipes/src/site/confluence/path-cache.confluence000066400000000000000000000037451245521677600311470ustar00rootroot00000000000000h1. Path Cache h2. Description A Path Cache is used to watch a ZNode. Whenever a child is added, updated or removed, the Path Cache will change its state to contain the current set of children, the children's data and the children's state. h2. Participating Classes * PathChildrenCache * PathChildrenCacheEvent * PathChildrenCacheListener * ChildData h2. Usage h3. Creating a PathChildrenCache {code} public PathChildrenCache(CuratorFramework client, String path, boolean cacheData) Parameters: client - the client path - path to watch cacheData - if true, node contents are cached in addition to the stat {code} h2. General Usage The cache must be started by calling {{start()}}. Call {{close()}} when you are through with the cache. There are two versions of {{start()}}. The no\-arg version gives default behavior. The other version takes an enumeration that allows you to control how the initial cache is warmed: {code} public enum StartMode { /** * cache will _not_ be primed. i.e. it will start empty and you will receive * events for all nodes added, etc. */ NORMAL, /** * rebuild() will be called before this method returns in * order to get an initial view of the node. */ BUILD_INITIAL_CACHE, /** * After cache is primed with initial values (in the background) a * PathChildrenCacheEvent.Type.INITIALIZED event will be posted */ POST_INITIALIZED_EVENT } {code} At any time, call {{getCurrentData()}} to get the current state of the cache. You can also register to be notified when a change occurs by calling {{getListenable()}} and then: {code} public void addListener(PathChildrenCacheListener listener) Add a change listener Parameters: listener - the listener {code} h2. Error Handling PathChildrenCache instances internally monitor a {{ConnectionStateListener}}. If the connection state changes, the cache is reset (the {{PathChildrenCacheListener}} will receive a RESET). persistent-ephemeral-node.confluence000066400000000000000000000017671245521677600341600ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/site/confluenceh1. Persistent Ephemeral Node h2. Description A persistent ephemeral node is an ephemeral node that attempts to stay present in ZooKeeper, even through connection and session interruptions. h2. Participating Classes * PersistentEphemeralNode h2. Usage h3. Creating a PersistentEphemeralNode {code} public PersistentEphemeralNode(CuratorFramework client, PersistentEphemeralNode.Mode mode, String basePath, byte[] data) Parameters: client - client instance mode - creation/protection mode basePath - the base path for the node data - data for the node {code} h3. General Usage PersistentEphemeralNodes must be started: {code} node.start(); {code} When you are through with the PersistentEphemeralNode instance, you should call close: {code} node.close(); {code} NOTE: this will delete the node h2. Error Handling PersistentEphemeralNode instances internally handle all error states recreating the node as necessary. curator-apache-curator-2.7.1/curator-recipes/src/site/confluence/shared-counter.confluence000066400000000000000000000040421245521677600320640ustar00rootroot00000000000000h1. Shared Counter h2. Description Manages a shared integer. All clients watching the same path will have the up\-to\-date value of the shared integer (considering ZK's normal consistency guarantees). h2. Participating Classes * SharedCount * SharedCountReader * SharedCountListener h2. Usage h3. Creating a SharedCounter {code} public SharedCount(CuratorFramework client, String path, int seedValue) Parameters: client - the client path - the shared path - i.e. where the shared count is stored seedValue - the initial value for the count if/f the path has not yet been created {code} h3. General Usage SharedCounts must be started: {code} count.start(); {code} When you are through with the instance, you should call close: {code} count.close(); {code} {code} int getCount() Return the current value of the count {code} {code} void addListener(SharedCountListener listener) Add a listener for changes to the count {code} {code} public void setCount(int newCount) Change the shared count value irrespective of its previous state {code} {code} public boolean trySetCount(int newCount) Changes the shared count only if its value has not changed since this client last read it. If the count has changed, the value is not set and this client's view of the value is updated. i.e. if the count is not successful you can get the updated value by calling getCount(). Parameters: newCount - the new value to attempt Returns: true if the change attempt was successful, false if not. If the change was not successful, getCount() will return the updated value {code} h2. Error Handling The {{SharedCountListener}} class extends {{ConnectionStateListener}}. When the SharedCount is started, it adds the listener to the Curator instance. Users of the {{SharedCount}} must pay attention to any connection state changes. If the SUSPENDED state is reported, the instance must assume that, until it receives a RECONNECTED state, the count is no longer accurate and isn't being updated. If the LOST state is reported, the count is permanently down. curator-apache-curator-2.7.1/curator-recipes/src/site/confluence/shared-lock.confluence000066400000000000000000000027631245521677600313450ustar00rootroot00000000000000h1. Shared Lock h2. Description Fully distributed locks that are globally synchronous, meaning at any snapshot in time no two clients think they hold the same lock. Note: unlike InterProcessMutex this lock is *not* reentrant. h2. Participating Classes * InterProcessSemaphoreMutex h2. Usage h3. Create an InterProcessSemaphoreMutex {code} public InterProcessSemaphoreMutex(CuratorFramework client, String path) Parameters: client - client path - the path to lock {code} h3. General Usage To acquire the lock, use one of the acquire methods: {code} public void acquire() Acquire the mutex - blocking until it's available. Must be balanced by a call to release(). {code} {code} public boolean acquire(long time, TimeUnit unit) Acquire the mutex - blocks until it's available or the given time expires. Must be balanced by a call to release().   Parameters: time - time to wait unit - time unit Returns: true if the mutex was acquired, false if not {code} To release the mutex, call: {code} public void release() Perform one release of the mutex if the calling thread is the same thread that acquired it. {code} h2. Error Handling It is strongly recommended that you add a {{ConnectionStateListener}} and watch for SUSPENDED and LOST state changes. If a SUSPENDED state is reported you cannot be certain that you still hold the lock unless you subsequently receive a RECONNECTED state. If a LOST state is reported it is certain that you no longer hold the lock. curator-apache-curator-2.7.1/curator-recipes/src/site/confluence/shared-reentrant-lock.confluence000066400000000000000000000053741245521677600333460ustar00rootroot00000000000000h1. Shared Reentrant Lock h2. Description Fully distributed locks that are globally synchronous, meaning at any snapshot in time no two clients think they hold the same lock. h2. Participating Classes * InterProcessMutex h2. Usage h3. Create an InterProcessMutex {code} public InterProcessMutex(CuratorFramework client, String path) Parameters: client - client path - the path to lock {code} h3. General Usage To acquire the lock, use one of the acquire methods: {code} public void acquire() Acquire the mutex - blocking until it's available. Note: the same thread can call acquire re-entrantly. Each call to acquire must be balanced by a call to release() {code} {code} public boolean acquire(long time, TimeUnit unit) Acquire the mutex - blocks until it's available or the given time expires. Note: the same thread can call acquire re-entrantly. Each call to acquire that returns true must be balanced by a call to release() Parameters: time - time to wait unit - time unit Returns: true if the mutex was acquired, false if not {code} To release the mutex, call: {code} public void release() Perform one release of the mutex if the calling thread is the same thread that acquired it. If the thread had made multiple calls to acquire, the mutex will still be held when this method returns. {code} *NOTE:* A InterProcessMutex instance is reusable. i.e. don't create a new instance every time. Re\-use a single instance. h3. Revoking InterProcessMutex supports a cooperative revocation mechanism as described on the ZooKeeper recipes wiki. To make a mutex revocable, call: {code} public void makeRevocable(RevocationListener listener) Make the lock revocable. Your listener will get called when another process/thread wants you to release the lock. Revocation is cooperative. Parameters: listener - the listener {code} To ask for a lock to revoke/release, use the static method in the {{Revoker}} class: {code} public static void attemptRevoke(CuratorFramework client, String path) throws Exception Utility to mark a lock for revocation. Assuming that the lock has been registered with a RevocationListener, it will get called and the lock should be released. Note, however, that revocation is cooperative. Parameters: client - the client path - the path of the lock - usually from something like InterProcessMutex.getParticipantNodes() {code} h2. Error Handling It is strongly recommended that you add a {{ConnectionStateListener}} and watch for SUSPENDED and LOST state changes. If a SUSPENDED state is reported you cannot be certain that you still hold the lock unless you subsequently receive a RECONNECTED state. If a LOST state is reported it is certain that you no longer hold the lock. shared-reentrant-read-write-lock.confluence000066400000000000000000000041061245521677600353200ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/site/confluenceh1. Shared Reentrant Read Write Lock h2. Description A re\-entrant read/write mutex that works across JVMs. Uses Zookeeper to hold the lock. All processes in all JVMs that use the same lock path will achieve an inter\-process critical section. Further, this mutex is "fair" - each user will get the mutex in the order requested (from ZK's point of view). A read write lock maintains a pair of associated locks, one for read\-only operations and one for writing. The read lock may be held simultaneously by multiple reader processes, so long as there are no writers. The write lock is exclusive. _Reentrancy_ This lock allows both readers and writers to reacquire read or write locks in the style of a re\-entrant lock. Non\-re\-entrant readers are not allowed until all write locks held by the writing thread/process have been released. Additionally, a writer can acquire the read lock, but not vice\-versa. If a reader tries to acquire the write lock it will never succeed. _Lock Downgrading_ Re\-entrancy also allows downgrading from the write lock to a read lock, by acquiring the write lock, then the read lock and then releasing the write lock. However, upgrading from a read lock to the write lock is not possible. h2. Participating Classes * InterProcessReadWriteLock * InterProcessLock h2. Usage h3. Create an InterProcessReadWriteLock {code} public InterProcessReadWriteLock(CuratorFramework client, String basePath) Parameters: client - the client basePath - path to use for locking {code} h3. General Usage Access either the read lock or the write lock and then use the methods as described for [[Shared lock|shared-lock.html]]. {code} public InterProcessLock readLock() public InterProcessLock writeLock() {code} h2. Error Handling It is strongly recommended that you add a {{ConnectionStateListener}} and watch for SUSPENDED and LOST state changes. If a SUSPENDED state is reported you cannot be certain that you still hold the lock unless you subsequently receive a RECONNECTED state. If a LOST state is reported it is certain that you no longer hold the lock. curator-apache-curator-2.7.1/curator-recipes/src/site/confluence/shared-semaphore.confluence000066400000000000000000000107021245521677600323700ustar00rootroot00000000000000h1. Shared Semaphore h2. Description A counting semaphore that works across JVMs. All processes in all JVMs that use the same lock path will achieve an inter\-process limited set of leases. Further, this semaphore is mostly "fair" \- each user will get a lease in the order requested (from ZK's point of view). There are two modes for determining the max leases for the semaphore. In the first mode the max leases is a convention maintained by the users of a given path. In the second mode a SharedCountReader is used as the method for semaphores of a given path to determine the max leases. If a SharedCountReader is not used, no internal checks are done to prevent Process A acting as if there are 10 leases and Process B acting as if there are 20. Therefore, make sure that all instances in all processes use the same numberOfLeases value. The various acquire methods return Lease objects that represent acquired leases. Clients must take care to close lease objects (ideally in a {{finally}} block) else the lease will be lost. However, if the client session drops (crash, etc.), any leases held by the client are automatically closed and made available to other clients. h2. Participating Classes * InterProcessSemaphoreV2 * Lease * SharedCountReader h2. Usage h3. Creating an InterProcessSemaphoreV2 {code} public InterProcessSemaphoreV2(CuratorFramework client, String path, int numberOfLeases) Parameters: client - client path - the path to lock numberOfLeases - the number of leases allowed by this semaphore {code} {code} public InterProcessSemaphoreV2(CuratorFramework client, String path, SharedCountReader count) Parameters: client - the client path - path for the semaphore count - the shared count to use for the max leases {code} h2. General Usage To acquire one lease/usage, use one of the acquire methods: {code} public Lease acquire() Acquire a lease. If no leases are available, this method blocks until either the maximum number of leases is increased or another client/process closes a lease. The client must close the lease when it is done with it. You should do this in a finally block. Returns: the new lease {code} {code} public Collection acquire(int qty) Acquire qty leases. If there are not enough leases available, this method blocks until either the maximum number of leases is increased enough or other clients/processes close enough leases. The client must close the leases when it is done with them. You should do this in a finally block. NOTE: You can use returnAll(Collection) for this. Parameters: qty - number of leases to acquire Returns: the new leases {code} {code} public Lease acquire(long time, TimeUnit unit) Acquire a lease. If no leases are available, this method blocks until either the maximum number of leases is increased or another client/process closes a lease. However, this method will only block to a maximum of the time parameters given. The client must close the lease when it is done with it. You should do this in a finally block. Parameters: time - time to wait unit - time unit Returns: the new lease or null if time ran out {code} {code} public Collection acquire(int qty, long time, TimeUnit unit) Acquire qty leases. If there are not enough leases available, this method blocks until either the maximum number of leases is increased enough or other clients/processes close enough leases. However, this method will only block to a maximum of the time parameters given. If time expires before all leases are acquired, the subset of acquired leases are automatically closed. The client must close the leases when it is done with them. You should do this in a finally block. NOTE: You can use returnAll(Collection) for this. Parameters: qty - number of leases to acquire time - time to wait unit - time unit {code} {{Lease}} instances can either be closed directly or you can use these convenience methods: {code} public void returnAll(Collection leases) public void returnLease(Lease lease) {code} h2. Error Handling It is strongly recommended that you add a {{ConnectionStateListener}} and watch for SUSPENDED and LOST state changes. If a SUSPENDED state is reported you cannot be certain that you still hold the lock unless you subsequently receive a RECONNECTED state. If a LOST state is reported it is certain that you no longer hold the lock. curator-apache-curator-2.7.1/curator-recipes/src/site/confluence/simple-distributed-queue.confluence000066400000000000000000000022111245521677600340700ustar00rootroot00000000000000h1. Simple Distributed Queue h2. *IMPORTANT* \- We recommend that you do NOT use ZooKeeper for Queues. Please see [[Tech Note 4|https://cwiki.apache.org/confluence/display/CURATOR/TN4]] for details. h2. Description A drop\-in replacement for the DistributedQueue that comes with the ZK distribution. h2. Participating Classes * SimpleDistributedQueue h2. Usage *Creating a SimpleDistributedQueue* {code} public SimpleDistributedQueue(CuratorFramework client, String path) Parameters: client - the client path - path to store queue nodes {code} *Add to the queue* {code} public boolean offer(byte[] data) throws Exception Inserts data into queue. Parameters: data - the data Returns: true if data was successfully added {code} *Take from the queue* {code} public byte[] take() throws Exception Removes the head of the queue and returns it, blocks until it succeeds. Returns: The former head of the queue {code} NOTE: see the Javadoc for additional methods h2. Error Handling It is strongly recommended that you add a {{ConnectionStateListener}} and watch for SUSPENDED and LOST state changes. curator-apache-curator-2.7.1/curator-recipes/src/site/confluence/tree-cache.confluence000066400000000000000000000025521245521677600311450ustar00rootroot00000000000000h1. Tree Cache h2. Description A utility that attempts to keep all data from all children of a ZK path locally cached. This class will watch the ZK path, respond to update/create/delete events, pull down the data, etc. You can register a listener that will get notified when changes occur. h2. Participating Classes * TreeCache * TreeCacheListener * TreeCacheEvent * ChildData h2. Usage h3. Creating a TreeCache {code} public TreeCache(CuratorFramework client, String path, boolean cacheData) Parameters: client - the client path - path to watch cacheData - if true, node contents are cached in addition to the stat {code} h2. General Usage The cache must be started by calling {{start()}}. Call {{close()}} when you are through with the cache. At any time, call {{getCurrentChildren()}} to get the current state of the cache. Alternatively, call {{getCurrentData()}} to get the data for a given path that's being monitored. You can also register to be notified when a change occurs by calling {{getListenable()}} and then: {code} public void addListener(TreeCacheListener listener) Add a change listener Parameters: listener - the listener {code} h2. Error Handling TreeCache instances internally monitor a {{ConnectionStateListener}}. If the connection state changes, the cache will receive messages detailing the change. curator-apache-curator-2.7.1/curator-recipes/src/site/site.xml000066400000000000000000000030121245521677600244370ustar00rootroot00000000000000 curator-apache-curator-2.7.1/curator-recipes/src/test/000077500000000000000000000000001245521677600227705ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/000077500000000000000000000000001245521677600237115ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/000077500000000000000000000000001245521677600245005ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/000077500000000000000000000000001245521677600257215ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/000077500000000000000000000000001245521677600274005ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/000077500000000000000000000000001245521677600313755ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/client/000077500000000000000000000000001245521677600326535ustar00rootroot00000000000000TestBackgroundStates.java000066400000000000000000000140541245521677600375460ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/client/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.client; import com.google.common.collect.Queues; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.nodes.PersistentEphemeralNode; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.TestingServer; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; // NOTE: these tests are in Framework as they use the PersistentEphemeralNode recipe public class TestBackgroundStates extends BaseClassForTests { @Test public void testListenersReconnectedIsOK() throws Exception { server.close(); Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); PersistentEphemeralNode node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes()); node.start(); final CountDownLatch connectedLatch = new CountDownLatch(1); final CountDownLatch reconnectedLatch = new CountDownLatch(1); final AtomicReference lastState = new AtomicReference(); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { lastState.set(newState); if ( newState == ConnectionState.CONNECTED ) { connectedLatch.countDown(); } if ( newState == ConnectionState.RECONNECTED ) { reconnectedLatch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); timing.sleepABit(); server = new TestingServer(server.getPort()); Assert.assertTrue(timing.awaitLatch(connectedLatch)); timing.sleepABit(); Assert.assertTrue(node.waitForInitialCreate(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); server.close(); timing.sleepABit(); server = new TestingServer(server.getPort()); timing.sleepABit(); Assert.assertTrue(timing.awaitLatch(reconnectedLatch)); timing.sleepABit(); Assert.assertEquals(lastState.get(), ConnectionState.RECONNECTED); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testConnectionStateListener() throws Exception { server.close(); Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(timing.milliseconds())); try { client.start(); PersistentEphemeralNode node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes()); node.start(); final BlockingQueue stateVector = Queues.newLinkedBlockingQueue(1); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { stateVector.offer(newState); } }; Timing waitingTiming = timing.forWaiting(); client.getConnectionStateListenable().addListener(listener); server = new TestingServer(server.getPort()); Assert.assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED); server.close(); Assert.assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED); Assert.assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.LOST); server = new TestingServer(server.getPort()); Assert.assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.RECONNECTED); server.close(); Assert.assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED); Assert.assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.LOST); } finally { CloseableUtils.closeQuietly(client); } } }TestResetConnectionWithBackgroundFailure.java000066400000000000000000000100501245521677600435410ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/client/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.client; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.leader.LeaderSelector; import org.apache.curator.framework.recipes.leader.LeaderSelectorListener; import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.TestingServer; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestResetConnectionWithBackgroundFailure extends BaseClassForTests { private final Logger log = LoggerFactory.getLogger(getClass()); @BeforeMethod @Override public void setup() throws Exception { super.setup(); } @Test public void testConnectionStateListener() throws Exception { server.close(); final StringBuilder listenerSequence = new StringBuilder(); LeaderSelector selector = null; Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(100)); try { client.start(); timing.sleepABit(); LeaderSelectorListener listenerLeader = new LeaderSelectorListenerAdapter() { @Override public void takeLeadership(CuratorFramework client) throws Exception { Thread.currentThread().join(); } }; selector = new LeaderSelector(client, "/leader", listenerLeader); selector.autoRequeue(); selector.start(); ConnectionStateListener listener1 = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { listenerSequence.append("-").append(newState); } }; client.getConnectionStateListenable().addListener(listener1); log.debug("Starting ZK server"); server = new TestingServer(server.getPort()); timing.forWaiting().sleepABit(); log.debug("Stopping ZK server"); server.close(); timing.forWaiting().sleepABit(); log.debug("Starting ZK server"); server = new TestingServer(server.getPort()); timing.forWaiting().sleepABit(); log.debug("Stopping ZK server"); server.close(); timing.forWaiting().sleepABit(); Assert.assertEquals(listenerSequence.toString(), "-CONNECTED-SUSPENDED-LOST-RECONNECTED-SUSPENDED-LOST"); } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } }curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/000077500000000000000000000000001245521677600330275ustar00rootroot00000000000000000077500000000000000000000000001245521677600342245ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/atomicTestCachedAtomicCounter.java000066400000000000000000000116011245521677600415720ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/atomic/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.atomic; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.atomic.AtomicReference; public class TestCachedAtomicCounter extends BaseClassForTests { @Test public void testWithError() throws Exception { final int FACTOR = 100; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { AtomicValue value = new MutableAtomicValue(0L, (long)FACTOR, true); final AtomicReference> fakeValueRef = new AtomicReference>(value); DistributedAtomicLong dal = new DistributedAtomicLong(client, "/", null, null) { @Override public AtomicValue trySet(Long newValue) throws Exception { return fakeValueRef.get(); } @Override public AtomicValue get() throws Exception { return fakeValueRef.get(); } @Override public AtomicValue increment() throws Exception { return fakeValueRef.get(); } @Override public AtomicValue decrement() throws Exception { return fakeValueRef.get(); } @Override public AtomicValue add(Long delta) throws Exception { return fakeValueRef.get(); } @Override public AtomicValue subtract(Long delta) throws Exception { return fakeValueRef.get(); } @Override public void forceSet(Long newValue) throws Exception { } @Override public AtomicValue compareAndSet(Long expectedValue, Long newValue) throws Exception { return fakeValueRef.get(); } }; CachedAtomicLong cachedLong = new CachedAtomicLong(dal, FACTOR); for ( int i = 0; i < FACTOR; ++i ) { value = cachedLong.next(); Assert.assertTrue(value.succeeded()); Assert.assertEquals(value.preValue().longValue(), i); Assert.assertEquals(value.postValue().longValue(), i + 1); if ( i == 0 ) { MutableAtomicValue badValue = new MutableAtomicValue(0L, 0L); badValue.succeeded = false; fakeValueRef.set(badValue); } } value = cachedLong.next(); Assert.assertFalse(value.succeeded()); } finally { client.close(); } } @Test public void testBasic() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)); CachedAtomicLong cachedLong = new CachedAtomicLong(dal, 100); for ( long i = 0; i < 200; ++i ) { AtomicValue value = cachedLong.next(); Assert.assertTrue(value.succeeded()); Assert.assertEquals(value.preValue().longValue(), i); Assert.assertEquals(value.postValue().longValue(), i + 1); } } finally { client.close(); } } } TestDistributedAtomicLong.java000066400000000000000000000303031245521677600421650ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/atomic/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.atomic; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.retry.RetryOneTime; import org.apache.commons.math.stat.descriptive.SummaryStatistics; import org.apache.commons.math.stat.descriptive.SynchronizedSummaryStatistics; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.collections.Lists; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public class TestDistributedAtomicLong extends BaseClassForTests { @Test public void testCorruptedValue() throws Exception { final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/counter", "foo".getBytes()); DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)); try { dal.get().postValue(); } catch ( BufferUnderflowException e ) { Assert.fail("", e); } catch ( BufferOverflowException e ) { Assert.fail("", e); } catch ( RuntimeException e ) { // correct } } finally { client.close(); } } @Test public void testCompareAndSetWithFreshInstance() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)); AtomicValue result = dal.compareAndSet(0L, 1L); Assert.assertFalse(result.succeeded()); Assert.assertTrue(dal.initialize(0L)); result = dal.compareAndSet(0L, 1L); Assert.assertTrue(result.succeeded()); Assert.assertFalse(dal.initialize(0L)); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testCompareAndSet() throws Exception { final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { final AtomicBoolean doIncrement = new AtomicBoolean(false); DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)) { @Override public byte[] valueToBytes(Long newValue) { if ( doIncrement.get() ) { DistributedAtomicLong inc = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)); try { // this will force a bad version exception inc.increment(); } catch ( Exception e ) { throw new Error(e); } } return super.valueToBytes(newValue); } }; dal.forceSet(1L); Assert.assertTrue(dal.compareAndSet(1L, 5L).succeeded()); Assert.assertFalse(dal.compareAndSet(1L, 5L).succeeded()); doIncrement.set(true); Assert.assertFalse(dal.compareAndSet(5L, 10L).succeeded()); } finally { client.close(); } } @Test public void testForceSet() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { final DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)); ExecutorService executorService = Executors.newFixedThreadPool(2); executorService.submit ( new Callable() { @Override public Object call() throws Exception { for ( int i = 0; i < 1000; ++i ) { dal.increment(); Thread.sleep(10); } return null; } } ); executorService.submit ( new Callable() { @Override public Object call() throws Exception { for ( int i = 0; i < 1000; ++i ) { dal.forceSet(0L); Thread.sleep(10); } return null; } } ); Assert.assertTrue(dal.get().preValue() < 10); } finally { client.close(); } } @Test public void testSimulation() throws Exception { final int threadQty = 20; final int executionQty = 50; final AtomicInteger optimisticTries = new AtomicInteger(); final AtomicInteger promotedLockTries = new AtomicInteger(); final AtomicInteger failures = new AtomicInteger(); final AtomicInteger errors = new AtomicInteger(); final SummaryStatistics timingStats = new SynchronizedSummaryStatistics(); List> procs = Lists.newArrayList(); ExecutorService executorService = Executors.newFixedThreadPool(threadQty); for ( int i = 0; i < threadQty; ++i ) { Callable proc = new Callable() { @Override public Void call() throws Exception { doSimulation(executionQty, timingStats, optimisticTries, promotedLockTries, failures, errors); return null; } }; procs.add(executorService.submit(proc)); } for ( Future f : procs ) { f.get(); } System.out.println("OptimisticTries: " + optimisticTries.get()); System.out.println("PromotedLockTries: " + promotedLockTries.get()); System.out.println("Failures: " + failures.get()); System.out.println("Errors: " + errors.get()); System.out.println(); System.out.println("Avg time: " + timingStats.getMean()); System.out.println("Max time: " + timingStats.getMax()); System.out.println("Min time: " + timingStats.getMin()); System.out.println("Qty: " + timingStats.getN()); Assert.assertEquals(errors.get(), 0); Assert.assertTrue(optimisticTries.get() > 0); Assert.assertTrue(promotedLockTries.get() > 0); } @Test public void testBasic() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { DistributedAtomicLong dal = new DistributedAtomicLong(client, "/foo/bar/counter", new RetryOneTime(1)); AtomicValue value = dal.increment(); Assert.assertTrue(value.succeeded()); Assert.assertEquals(value.getStats().getOptimisticTries(), 1); Assert.assertEquals(value.getStats().getPromotedLockTries(), 0); Assert.assertEquals(value.preValue().longValue(), 0L); Assert.assertEquals(value.postValue().longValue(), 1L); value = dal.decrement(); Assert.assertTrue(value.succeeded()); Assert.assertEquals(value.getStats().getOptimisticTries(), 1); Assert.assertEquals(value.getStats().getPromotedLockTries(), 0); Assert.assertEquals(value.preValue().longValue(), 1L); Assert.assertEquals(value.postValue().longValue(), 0L); value = dal.add(10L); Assert.assertTrue(value.succeeded()); Assert.assertEquals(value.getStats().getOptimisticTries(), 1); Assert.assertEquals(value.getStats().getPromotedLockTries(), 0); Assert.assertEquals(value.preValue().longValue(), 0L); Assert.assertEquals(value.postValue().longValue(), 10L); value = dal.subtract(5L); Assert.assertTrue(value.succeeded()); Assert.assertEquals(value.getStats().getOptimisticTries(), 1); Assert.assertEquals(value.getStats().getPromotedLockTries(), 0); Assert.assertEquals(value.preValue().longValue(), 10L); Assert.assertEquals(value.postValue().longValue(), 5L); } finally { client.close(); } } private void doSimulation(int executionQty, SummaryStatistics timingStats, AtomicInteger optimisticTries, AtomicInteger promotedLockTries, AtomicInteger failures, AtomicInteger errors) throws Exception { Random random = new Random(); long previousValue = -1; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { RetryPolicy retryPolicy = new ExponentialBackoffRetry(3, 3); PromotedToLock.Builder builder = PromotedToLock.builder().lockPath("/lock").retryPolicy(retryPolicy); DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", retryPolicy, builder.build()); for ( int i = 0; i < executionQty; ++i ) { Thread.sleep(random.nextInt(10)); long start = System.currentTimeMillis(); AtomicValue value = dal.increment(); long elapsed = System.currentTimeMillis() - start; timingStats.addValue(elapsed); if ( value.succeeded() ) { if ( value.postValue() <= previousValue ) { errors.incrementAndGet(); } previousValue = value.postValue(); } else { failures.incrementAndGet(); } optimisticTries.addAndGet(value.getStats().getOptimisticTries()); promotedLockTries.addAndGet(value.getStats().getPromotedLockTries()); } } finally { client.close(); } } } 000077500000000000000000000000001245521677600345615ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/barriersTestDistributedBarrier.java000066400000000000000000000166661245521677600420740ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/barriers/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.barriers; import com.google.common.collect.Lists; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.apache.zookeeper.KeeperException; import org.testng.Assert; import org.testng.annotations.Test; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class TestDistributedBarrier extends BaseClassForTests { @Test public void testServerCrash() throws Exception { final int TIMEOUT = 1000; final CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).connectionTimeoutMs(TIMEOUT).retryPolicy(new RetryOneTime(1)).build(); try { client.start(); final DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); barrier.setBarrier(); final ExecutorService service = Executors.newSingleThreadExecutor(); Future future = service.submit ( new Callable() { @Override public Object call() throws Exception { Thread.sleep(TIMEOUT / 2); server.stop(); return null; } } ); barrier.waitOnBarrier(TIMEOUT * 2, TimeUnit.SECONDS); future.get(); Assert.fail(); } catch ( KeeperException.ConnectionLossException expected ) { // expected } finally { client.close(); } } @Test public void testMultiClient() throws Exception { CuratorFramework client1 = null; CuratorFramework client2 = null; try { { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); barrier.setBarrier(); } finally { CloseableUtils.closeQuietly(client); } } client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); List> futures = Lists.newArrayList(); ExecutorService service = Executors.newCachedThreadPool(); for ( final CuratorFramework c : new CuratorFramework[]{client1, client2} ) { Future future = service.submit ( new Callable() { @Override public Object call() throws Exception { c.start(); DistributedBarrier barrier = new DistributedBarrier(c, "/barrier"); barrier.waitOnBarrier(10, TimeUnit.MILLISECONDS); return null; } } ); futures.add(future); } Thread.sleep(1000); { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); barrier.removeBarrier(); } finally { CloseableUtils.closeQuietly(client); } } for ( Future f : futures ) { f.get(); } } finally { CloseableUtils.closeQuietly(client1); CloseableUtils.closeQuietly(client2); } } @Test public void testNoBarrier() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); final DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); Assert.assertTrue(barrier.waitOnBarrier(10, TimeUnit.SECONDS)); // just for grins, test the infinite wait ExecutorService service = Executors.newSingleThreadExecutor(); Future future = service.submit ( new Callable() { @Override public Object call() throws Exception { barrier.waitOnBarrier(); return ""; } } ); Assert.assertTrue(future.get(10, TimeUnit.SECONDS) != null); } finally { client.close(); } } @Test public void testBasic() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); final DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); barrier.setBarrier(); ExecutorService service = Executors.newSingleThreadExecutor(); service.submit ( new Callable() { @Override public Object call() throws Exception { Thread.sleep(1000); barrier.removeBarrier(); return null; } } ); Assert.assertTrue(barrier.waitOnBarrier(10, TimeUnit.SECONDS)); } finally { client.close(); } } } TestDistributedDoubleBarrier.java000066400000000000000000000230161245521677600432120ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/barriers/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.barriers; import com.google.common.collect.Lists; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.Timing; import org.testng.Assert; import org.testng.annotations.Test; import java.io.Closeable; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class TestDistributedDoubleBarrier extends BaseClassForTests { private static final int QTY = 5; @Test public void testMultiClient() throws Exception { final Timing timing = new Timing(); final CountDownLatch postEnterLatch = new CountDownLatch(QTY); final CountDownLatch postLeaveLatch = new CountDownLatch(QTY); final AtomicInteger count = new AtomicInteger(0); final AtomicInteger max = new AtomicInteger(0); List> futures = Lists.newArrayList(); ExecutorService service = Executors.newCachedThreadPool(); for ( int i = 0; i < QTY; ++i ) { Future future = service.submit ( new Callable() { @Override public Void call() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY); Assert.assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS)); synchronized(TestDistributedDoubleBarrier.this) { int thisCount = count.incrementAndGet(); if ( thisCount > max.get() ) { max.set(thisCount); } } postEnterLatch.countDown(); Assert.assertTrue(timing.awaitLatch(postEnterLatch)); Assert.assertEquals(count.get(), QTY); Assert.assertTrue(barrier.leave(timing.seconds(), TimeUnit.SECONDS)); count.decrementAndGet(); postLeaveLatch.countDown(); Assert.assertTrue(timing.awaitLatch(postEnterLatch)); } finally { CloseableUtils.closeQuietly(client); } return null; } } ); futures.add(future); } for ( Future f : futures ) { f.get(); } Assert.assertEquals(count.get(), 0); Assert.assertEquals(max.get(), QTY); } @Test public void testOverSubscribed() throws Exception { final Timing timing = new Timing(); final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); ExecutorService service = Executors.newCachedThreadPool(); ExecutorCompletionService completionService = new ExecutorCompletionService(service); try { client.start(); final Semaphore semaphore = new Semaphore(0); final CountDownLatch latch = new CountDownLatch(1); for ( int i = 0; i < (QTY + 1); ++i ) { completionService.submit ( new Callable() { @Override public Void call() throws Exception { DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY) { @Override protected List getChildrenForEntering() throws Exception { semaphore.release(); Assert.assertTrue(timing.awaitLatch(latch)); return super.getChildrenForEntering(); } }; Assert.assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS)); Assert.assertTrue(barrier.leave(timing.seconds(), TimeUnit.SECONDS)); return null; } } ); } Assert.assertTrue(semaphore.tryAcquire(QTY + 1, timing.seconds(), TimeUnit.SECONDS)); // wait until all QTY+1 barriers are trying to enter latch.countDown(); for ( int i = 0; i < (QTY + 1); ++i ) { completionService.take().get(); // to check for assertions } } finally { service.shutdown(); CloseableUtils.closeQuietly(client); } } @Test public void testBasic() throws Exception { final Timing timing = new Timing(); final List closeables = Lists.newArrayList(); final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { closeables.add(client); client.start(); final CountDownLatch postEnterLatch = new CountDownLatch(QTY); final CountDownLatch postLeaveLatch = new CountDownLatch(QTY); final AtomicInteger count = new AtomicInteger(0); final AtomicInteger max = new AtomicInteger(0); List> futures = Lists.newArrayList(); ExecutorService service = Executors.newCachedThreadPool(); for ( int i = 0; i < QTY; ++i ) { Future future = service.submit ( new Callable() { @Override public Void call() throws Exception { DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY); Assert.assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS)); synchronized(TestDistributedDoubleBarrier.this) { int thisCount = count.incrementAndGet(); if ( thisCount > max.get() ) { max.set(thisCount); } } postEnterLatch.countDown(); Assert.assertTrue(timing.awaitLatch(postEnterLatch)); Assert.assertEquals(count.get(), QTY); Assert.assertTrue(barrier.leave(10, TimeUnit.SECONDS)); count.decrementAndGet(); postLeaveLatch.countDown(); Assert.assertTrue(timing.awaitLatch(postLeaveLatch)); return null; } } ); futures.add(future); } for ( Future f : futures ) { f.get(); } Assert.assertEquals(count.get(), 0); Assert.assertEquals(max.get(), QTY); } finally { for ( Closeable c : closeables ) { CloseableUtils.closeQuietly(c); } } } } 000077500000000000000000000000001245521677600340135ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cacheBaseTestTreeCache.java000066400000000000000000000142611245521677600401400ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.UnhandledErrorListener; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableExecutorService; import org.apache.curator.utils.CloseableUtils; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; public class BaseTestTreeCache extends BaseClassForTests { CuratorFramework client; TreeCache cache; private final AtomicBoolean hadBackgroundException = new AtomicBoolean(false); private final BlockingQueue events = new LinkedBlockingQueue(); private final Timing timing = new Timing(); /** * Automatically records all events into an easily testable event stream. */ final TreeCacheListener eventListener = new TreeCacheListener() { @Override public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception { // Suppress any events related to /zookeeper paths if ( event.getData() != null && event.getData().getPath().startsWith("/zookeeper") ) { return; } events.add(event); } }; /** * Ensures that tests don't cause any background errors. */ final UnhandledErrorListener errorListener = new UnhandledErrorListener() { @Override public void unhandledError(String message, Throwable e) { hadBackgroundException.set(true); e.printStackTrace(System.err); } }; /** * Construct a TreeCache that records exceptions and automatically listens. */ protected TreeCache newTreeCacheWithListeners(CuratorFramework client, String path) { TreeCache result = new TreeCache(client, path); result.getListenable().addListener(eventListener); result.getUnhandledErrorListenable().addListener(errorListener); return result; } /** * Finish constructing a TreeCache that records exceptions and automatically listens. */ protected TreeCache buildWithListeners(TreeCache.Builder builder) { TreeCache result = builder.build(); result.getListenable().addListener(eventListener); result.getUnhandledErrorListenable().addListener(errorListener); return result; } @Override @BeforeMethod public void setup() throws Exception { super.setup(); initCuratorFramework(); } void initCuratorFramework() { client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); client.getUnhandledErrorListenable().addListener(errorListener); } @Override @AfterMethod public void teardown() throws Exception { try { try { Assert.assertFalse(hadBackgroundException.get(), "Background exceptions were thrown, see stderr for details"); } finally { CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(client); } } finally { super.teardown(); } } /** * Asserts the event queue is empty. */ void assertNoMoreEvents() throws InterruptedException { timing.sleepABit(); Assert.assertTrue(events.isEmpty()); } /** * Asserts the given event is next in the queue, and consumes it from the queue. */ TreeCacheEvent assertEvent(TreeCacheEvent.Type expectedType) throws InterruptedException { return assertEvent(expectedType, null); } /** * Asserts the given event is next in the queue, and consumes it from the queue. */ TreeCacheEvent assertEvent(TreeCacheEvent.Type expectedType, String expectedPath) throws InterruptedException { return assertEvent(expectedType, expectedPath, null); } /** * Asserts the given event is next in the queue, and consumes it from the queue. */ TreeCacheEvent assertEvent(TreeCacheEvent.Type expectedType, String expectedPath, byte[] expectedData) throws InterruptedException { TreeCacheEvent event = events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS); Assert.assertNotNull(event, String.format("Expected type: %s, path: %s", expectedType, expectedPath)); String message = event.toString(); Assert.assertEquals(event.getType(), expectedType, message); if ( expectedPath == null ) { Assert.assertNull(event.getData(), message); } else { Assert.assertNotNull(event.getData(), message); Assert.assertEquals(event.getData().getPath(), expectedPath, message); } if ( expectedData != null ) { Assert.assertEquals(event.getData().getData(), expectedData, message); } return event; } } TestNodeCache.java000066400000000000000000000223741245521677600373370ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.UnhandledErrorListener; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.KillSession; import org.apache.curator.test.Timing; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Exchanger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; public class TestNodeCache extends BaseClassForTests { @Test public void testDeleteThenCreate() throws Exception { NodeCache cache = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.create().creatingParentsIfNeeded().forPath("/test/foo", "one".getBytes()); final AtomicReference error = new AtomicReference(); client.getUnhandledErrorListenable().addListener ( new UnhandledErrorListener() { @Override public void unhandledError(String message, Throwable e) { error.set(e); } } ); final Semaphore semaphore = new Semaphore(0); cache = new NodeCache(client, "/test/foo"); cache.getListenable().addListener ( new NodeCacheListener() { @Override public void nodeChanged() throws Exception { semaphore.release(); } } ); cache.start(true); Assert.assertEquals(cache.getCurrentData().getData(), "one".getBytes()); client.delete().forPath("/test/foo"); Assert.assertTrue(semaphore.tryAcquire(1, 10, TimeUnit.SECONDS)); client.create().forPath("/test/foo", "two".getBytes()); Assert.assertTrue(semaphore.tryAcquire(1, 10, TimeUnit.SECONDS)); Throwable t = error.get(); if ( t != null ) { Assert.fail("Assert", t); } Assert.assertEquals(cache.getCurrentData().getData(), "two".getBytes()); cache.close(); } finally { CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(client); } } @Test public void testRebuildAgainstOtherProcesses() throws Exception { NodeCache cache = null; final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/test"); client.create().forPath("/test/snafu", "original".getBytes()); final CountDownLatch latch = new CountDownLatch(1); cache = new NodeCache(client, "/test/snafu"); cache.getListenable().addListener ( new NodeCacheListener() { @Override public void nodeChanged() throws Exception { latch.countDown(); } } ); cache.rebuildTestExchanger = new Exchanger(); ExecutorService service = Executors.newSingleThreadExecutor(); final NodeCache finalCache = cache; Future future = service.submit ( new Callable() { @Override public Object call() throws Exception { finalCache.rebuildTestExchanger.exchange(new Object(), 10, TimeUnit.SECONDS); // simulate another process updating the node while we're rebuilding client.setData().forPath("/test/snafu", "other".getBytes()); ChildData currentData = finalCache.getCurrentData(); Assert.assertNotNull(currentData); finalCache.rebuildTestExchanger.exchange(new Object(), 10, TimeUnit.SECONDS); return null; } } ); cache.start(false); future.get(); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); Assert.assertNotNull(cache.getCurrentData()); Assert.assertEquals(cache.getCurrentData().getData(), "other".getBytes()); } finally { CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(client); } } @Test public void testKilledSession() throws Exception { NodeCache cache = null; Timing timing = new Timing(); CuratorFramework client = null; try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); client.create().creatingParentsIfNeeded().forPath("/test/node", "start".getBytes()); cache = new NodeCache(client, "/test/node"); cache.start(true); final CountDownLatch latch = new CountDownLatch(1); cache.getListenable().addListener ( new NodeCacheListener() { @Override public void nodeChanged() throws Exception { latch.countDown(); } } ); KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString()); Thread.sleep(timing.multiple(1.5).session()); Assert.assertEquals(cache.getCurrentData().getData(), "start".getBytes()); client.setData().forPath("/test/node", "new data".getBytes()); Assert.assertTrue(timing.awaitLatch(latch)); } finally { CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(client); } } @Test public void testBasics() throws Exception { NodeCache cache = null; Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/test"); cache = new NodeCache(client, "/test/node"); cache.start(true); final Semaphore semaphore = new Semaphore(0); cache.getListenable().addListener ( new NodeCacheListener() { @Override public void nodeChanged() throws Exception { semaphore.release(); } } ); Assert.assertNull(cache.getCurrentData()); client.create().forPath("/test/node", "a".getBytes()); Assert.assertTrue(timing.acquireSemaphore(semaphore)); Assert.assertEquals(cache.getCurrentData().getData(), "a".getBytes()); client.setData().forPath("/test/node", "b".getBytes()); Assert.assertTrue(timing.acquireSemaphore(semaphore)); Assert.assertEquals(cache.getCurrentData().getData(), "b".getBytes()); client.delete().forPath("/test/node"); Assert.assertTrue(timing.acquireSemaphore(semaphore)); Assert.assertNull(cache.getCurrentData()); } finally { CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(client); } } } TestPathChildrenCache.java000066400000000000000000001306311245521677600410130ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.Pathable; import org.apache.curator.framework.api.UnhandledErrorListener; import org.apache.curator.framework.imps.CuratorFrameworkImpl; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.KillSession; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.apache.log4j.Appender; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.apache.log4j.spi.LoggingEvent; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Collection; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Exchanger; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; public class TestPathChildrenCache extends BaseClassForTests { @Test public void testPostInitializedForEmpty() throws Exception { Timing timing = new Timing(); PathChildrenCache cache = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); final CountDownLatch latch = new CountDownLatch(1); cache = new PathChildrenCache(client, "/test", true); cache.getListenable().addListener ( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { if ( event.getType() == PathChildrenCacheEvent.Type.INITIALIZED ) { latch.countDown(); } } } ); cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT); Assert.assertTrue(timing.awaitLatch(latch)); } finally { CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(client); } } @Test public void testClientClosedDuringRefreshErrorMessage() throws Exception { Timing timing = new Timing(); // Fiddle with logging so we can intercept the error events for org.apache.curator final List events = Lists.newArrayList(); Collection messages = Collections2.transform(events, new Function() { @Override public String apply(LoggingEvent loggingEvent) { return loggingEvent.getRenderedMessage(); } }); Appender appender = new AppenderSkeleton(true) { @Override protected void append(LoggingEvent event) { if (event.getLevel().equals(Level.ERROR)) { events.add(event); } } @Override public void close() { } @Override public boolean requiresLayout() { return false; } }; appender.setLayout(new SimpleLayout()); Logger logger = Logger.getLogger("org.apache.curator"); logger.addAppender(appender); // Check that we can intercept error log messages from the client CuratorFramework clientTestLogSetup = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clientTestLogSetup.start(); try { Pathable callback = clientTestLogSetup.getData().inBackground(new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { // ignore result } }); CloseableUtils.closeQuietly(clientTestLogSetup); callback.forPath("/test/aaa"); // this should cause an error log message } catch (IllegalStateException ise) { // ok, excpected } finally { CloseableUtils.closeQuietly(clientTestLogSetup); } Assert.assertTrue(messages.contains("Background exception was not retry-able or retry gave up"), "The expected error was not logged. This is an indication that this test could be broken due to" + " an incomplete logging setup."); // try to reproduce a bunch of times because it doesn't happen reliably for (int i = 0; i < 50; i++) { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { PathChildrenCache cache = new PathChildrenCache(client, "/test", true); cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE); client.newNamespaceAwareEnsurePath("/test/aaa").ensure(client.getZookeeperClient()); client.setData().forPath("/test/aaa", new byte[]{1, 2, 3, 4, 5}); cache.rebuildNode("/test/aaa"); CloseableUtils.closeQuietly(cache); } finally { CloseableUtils.closeQuietly(client); } } Assert.assertEquals(messages.size(), 1, "There should not be any error events except for the test message, " + "but got:\n" + Joiner.on("\n").join(messages)); } @Test public void testAsyncInitialPopulation() throws Exception { Timing timing = new Timing(); PathChildrenCache cache = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); client.create().forPath("/test"); client.create().forPath("/test/one", "hey there".getBytes()); final BlockingQueue events = new LinkedBlockingQueue(); cache = new PathChildrenCache(client, "/test", true); cache.getListenable().addListener ( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { events.offer(event); } } ); cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT); PathChildrenCacheEvent event = events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS); Assert.assertEquals(event.getType(), PathChildrenCacheEvent.Type.CHILD_ADDED); event = events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS); Assert.assertEquals(event.getType(), PathChildrenCacheEvent.Type.INITIALIZED); Assert.assertEquals(event.getInitialData().size(), 1); } finally { CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(client); } } @Test public void testChildrenInitialized() throws Exception { Timing timing = new Timing(); PathChildrenCache cache = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); client.create().forPath("/test"); cache = new PathChildrenCache(client, "/test", true); final CountDownLatch addedLatch = new CountDownLatch(3); final CountDownLatch initLatch = new CountDownLatch(1); cache.getListenable().addListener ( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) { addedLatch.countDown(); } else if ( event.getType() == PathChildrenCacheEvent.Type.INITIALIZED ) { initLatch.countDown(); } } } ); client.create().forPath("/test/1", "1".getBytes()); client.create().forPath("/test/2", "2".getBytes()); client.create().forPath("/test/3", "3".getBytes()); cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT); Assert.assertTrue(timing.awaitLatch(addedLatch)); Assert.assertTrue(timing.awaitLatch(initLatch)); Assert.assertEquals(cache.getCurrentData().size(), 3); Assert.assertEquals(cache.getCurrentData().get(0).getData(), "1".getBytes()); Assert.assertEquals(cache.getCurrentData().get(1).getData(), "2".getBytes()); Assert.assertEquals(cache.getCurrentData().get(2).getData(), "3".getBytes()); } finally { CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(client); } } @Test public void testChildrenInitializedNormal() throws Exception { Timing timing = new Timing(); PathChildrenCache cache = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); client.create().forPath("/test"); cache = new PathChildrenCache(client, "/test", true); final CountDownLatch addedLatch = new CountDownLatch(3); cache.getListenable().addListener ( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { Assert.assertNotEquals(event.getType(), PathChildrenCacheEvent.Type.INITIALIZED); if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) { addedLatch.countDown(); } } } ); client.create().forPath("/test/1", "1".getBytes()); client.create().forPath("/test/2", "2".getBytes()); client.create().forPath("/test/3", "3".getBytes()); cache.start(PathChildrenCache.StartMode.NORMAL); Assert.assertTrue(timing.awaitLatch(addedLatch)); Assert.assertEquals(cache.getCurrentData().size(), 3); Assert.assertEquals(cache.getCurrentData().get(0).getData(), "1".getBytes()); Assert.assertEquals(cache.getCurrentData().get(1).getData(), "2".getBytes()); Assert.assertEquals(cache.getCurrentData().get(2).getData(), "3".getBytes()); } finally { CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(client); } } @Test public void testUpdateWhenNotCachingData() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { final CountDownLatch updatedLatch = new CountDownLatch(1); final CountDownLatch addedLatch = new CountDownLatch(1); client.create().creatingParentsIfNeeded().forPath("/test"); PathChildrenCache cache = new PathChildrenCache(client, "/test", false); cache.getListenable().addListener ( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED ) { updatedLatch.countDown(); } else if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) { addedLatch.countDown(); } } } ); cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE); client.create().forPath("/test/foo", "first".getBytes()); Assert.assertTrue(timing.awaitLatch(addedLatch)); client.setData().forPath("/test/foo", "something new".getBytes()); Assert.assertTrue(timing.awaitLatch(updatedLatch)); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testEnsurePath() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { PathChildrenCache cache = new PathChildrenCache(client, "/one/two/three", false); cache.start(); timing.sleepABit(); try { client.create().forPath("/one/two/three/four"); } catch ( KeeperException.NoNodeException e ) { Assert.fail("Path should exist", e); } } finally { CloseableUtils.closeQuietly(client); } } @Test public void testDeleteThenCreate() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/test"); client.create().forPath("/test/foo", "one".getBytes()); final AtomicReference error = new AtomicReference(); client.getUnhandledErrorListenable().addListener ( new UnhandledErrorListener() { @Override public void unhandledError(String message, Throwable e) { error.set(e); } } ); final CountDownLatch removedLatch = new CountDownLatch(1); final CountDownLatch postRemovedLatch = new CountDownLatch(1); final CountDownLatch dataLatch = new CountDownLatch(1); PathChildrenCache cache = new PathChildrenCache(client, "/test", true); cache.getListenable().addListener ( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED ) { removedLatch.countDown(); Assert.assertTrue(postRemovedLatch.await(10, TimeUnit.SECONDS)); } else { try { Assert.assertEquals(event.getData().getData(), "two".getBytes()); } finally { dataLatch.countDown(); } } } } ); cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE); client.delete().forPath("/test/foo"); Assert.assertTrue(timing.awaitLatch(removedLatch)); client.create().forPath("/test/foo", "two".getBytes()); postRemovedLatch.countDown(); Assert.assertTrue(timing.awaitLatch(dataLatch)); Throwable t = error.get(); if ( t != null ) { Assert.fail("Assert", t); } cache.close(); } finally { client.close(); } } @Test public void testRebuildAgainstOtherProcesses() throws Exception { Timing timing = new Timing(); final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/test"); client.create().forPath("/test/foo"); client.create().forPath("/test/bar"); client.create().forPath("/test/snafu", "original".getBytes()); final CountDownLatch addedLatch = new CountDownLatch(2); final PathChildrenCache cache = new PathChildrenCache(client, "/test", true); cache.getListenable().addListener ( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) { if ( event.getData().getPath().equals("/test/test") ) { addedLatch.countDown(); } } else if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED ) { if ( event.getData().getPath().equals("/test/snafu") ) { addedLatch.countDown(); } } } } ); cache.rebuildTestExchanger = new Exchanger(); ExecutorService service = Executors.newSingleThreadExecutor(); final AtomicReference deletedPath = new AtomicReference(); Future future = service.submit ( new Callable() { @Override public Object call() throws Exception { cache.rebuildTestExchanger.exchange(new Object()); // simulate another process adding a node while we're rebuilding client.create().forPath("/test/test"); List currentData = cache.getCurrentData(); Assert.assertTrue(currentData.size() > 0); // simulate another process removing a node while we're rebuilding client.delete().forPath(currentData.get(0).getPath()); deletedPath.set(currentData.get(0).getPath()); cache.rebuildTestExchanger.exchange(new Object()); ChildData childData = null; while ( childData == null ) { childData = cache.getCurrentData("/test/snafu"); Thread.sleep(1000); } Assert.assertEquals(childData.getData(), "original".getBytes()); client.setData().forPath("/test/snafu", "grilled".getBytes()); cache.rebuildTestExchanger.exchange(new Object()); return null; } } ); cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE); future.get(); Assert.assertTrue(timing.awaitLatch(addedLatch)); Assert.assertNotNull(cache.getCurrentData("/test/test")); Assert.assertNull(cache.getCurrentData(deletedPath.get())); Assert.assertEquals(cache.getCurrentData("/test/snafu").getData(), "grilled".getBytes()); cache.close(); } finally { client.close(); } } // see https://github.com/Netflix/curator/issues/27 - was caused by not comparing old->new data @Test public void testIssue27() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/base"); client.create().forPath("/base/a"); client.create().forPath("/base/b"); client.create().forPath("/base/c"); client.getChildren().forPath("/base"); final List events = Lists.newArrayList(); final Semaphore semaphore = new Semaphore(0); PathChildrenCache cache = new PathChildrenCache(client, "/base", true); cache.getListenable().addListener ( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { events.add(event.getType()); semaphore.release(); } } ); cache.start(); Assert.assertTrue(timing.acquireSemaphore(semaphore, 3)); client.delete().forPath("/base/a"); Assert.assertTrue(timing.acquireSemaphore(semaphore, 1)); client.create().forPath("/base/a"); Assert.assertTrue(timing.acquireSemaphore(semaphore, 1)); List expected = Lists.newArrayList ( PathChildrenCacheEvent.Type.CHILD_ADDED, PathChildrenCacheEvent.Type.CHILD_ADDED, PathChildrenCacheEvent.Type.CHILD_ADDED, PathChildrenCacheEvent.Type.CHILD_REMOVED, PathChildrenCacheEvent.Type.CHILD_ADDED ); Assert.assertEquals(expected, events); } finally { client.close(); } } // test Issue 27 using new rebuild() method @Test public void testIssue27Alt() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/base"); client.create().forPath("/base/a"); client.create().forPath("/base/b"); client.create().forPath("/base/c"); client.getChildren().forPath("/base"); final List events = Lists.newArrayList(); final Semaphore semaphore = new Semaphore(0); PathChildrenCache cache = new PathChildrenCache(client, "/base", true); cache.getListenable().addListener ( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { events.add(event.getType()); semaphore.release(); } } ); cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE); client.delete().forPath("/base/a"); Assert.assertTrue(timing.acquireSemaphore(semaphore, 1)); client.create().forPath("/base/a"); Assert.assertTrue(timing.acquireSemaphore(semaphore, 1)); List expected = Lists.newArrayList ( PathChildrenCacheEvent.Type.CHILD_REMOVED, PathChildrenCacheEvent.Type.CHILD_ADDED ); Assert.assertEquals(expected, events); } finally { client.close(); } } @Test public void testKilledSession() throws Exception { Timing timing = new Timing(); CuratorFramework client = null; try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); client.create().forPath("/test"); PathChildrenCache cache = new PathChildrenCache(client, "/test", true); cache.start(); final CountDownLatch childAddedLatch = new CountDownLatch(1); final CountDownLatch lostLatch = new CountDownLatch(1); final CountDownLatch reconnectedLatch = new CountDownLatch(1); final CountDownLatch removedLatch = new CountDownLatch(1); cache.getListenable().addListener ( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) { childAddedLatch.countDown(); } else if ( event.getType() == PathChildrenCacheEvent.Type.CONNECTION_LOST ) { lostLatch.countDown(); } else if ( event.getType() == PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED ) { reconnectedLatch.countDown(); } else if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED ) { removedLatch.countDown(); } } } ); client.create().withMode(CreateMode.EPHEMERAL).forPath("/test/me", "data".getBytes()); Assert.assertTrue(timing.awaitLatch(childAddedLatch)); KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString()); Assert.assertTrue(timing.awaitLatch(lostLatch)); Assert.assertTrue(timing.awaitLatch(reconnectedLatch)); Assert.assertTrue(timing.awaitLatch(removedLatch)); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testModes() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/test"); for ( boolean cacheData : new boolean[]{false, true} ) { internalTestMode(client, cacheData); client.delete().forPath("/test/one"); client.delete().forPath("/test/two"); } } finally { client.close(); } } @Test public void testRebuildNode() throws Exception { Timing timing = new Timing(); PathChildrenCache cache = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { client.create().creatingParentsIfNeeded().forPath("/test/one", "one".getBytes()); final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger counter = new AtomicInteger(); final Semaphore semaphore = new Semaphore(1); cache = new PathChildrenCache(client, "/test", true) { @Override void getDataAndStat(String fullPath) throws Exception { semaphore.acquire(); counter.incrementAndGet(); super.getDataAndStat(fullPath); latch.countDown(); } }; cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE); latch.await(); int saveCounter = counter.get(); client.setData().forPath("/test/one", "alt".getBytes()); cache.rebuildNode("/test/one"); Assert.assertEquals(cache.getCurrentData("/test/one").getData(), "alt".getBytes()); Assert.assertEquals(saveCounter, counter.get()); semaphore.release(1000); } finally { CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(client); } } private void internalTestMode(CuratorFramework client, boolean cacheData) throws Exception { PathChildrenCache cache = new PathChildrenCache(client, "/test", cacheData); final CountDownLatch latch = new CountDownLatch(2); cache.getListenable().addListener ( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) { latch.countDown(); } } } ); cache.start(); client.create().forPath("/test/one", "one".getBytes()); client.create().forPath("/test/two", "two".getBytes()); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); for ( ChildData data : cache.getCurrentData() ) { if ( cacheData ) { Assert.assertNotNull(data.getData()); Assert.assertNotNull(data.getStat()); } else { Assert.assertNull(data.getData()); Assert.assertNotNull(data.getStat()); } } cache.close(); } @Test public void testBasics() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/test"); final BlockingQueue events = new LinkedBlockingQueue(); PathChildrenCache cache = new PathChildrenCache(client, "/test", true); cache.getListenable().addListener ( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { if ( event.getData().getPath().equals("/test/one") ) { events.offer(event.getType()); } } } ); cache.start(); client.create().forPath("/test/one", "hey there".getBytes()); Assert.assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_ADDED); client.setData().forPath("/test/one", "sup!".getBytes()); Assert.assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_UPDATED); Assert.assertEquals(new String(cache.getCurrentData("/test/one").getData()), "sup!"); client.delete().forPath("/test/one"); Assert.assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_REMOVED); cache.close(); } finally { client.close(); } } @Test public void testBasicsOnTwoCachesWithSameExecutor() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/test"); final BlockingQueue events = new LinkedBlockingQueue(); final ExecutorService exec = Executors.newSingleThreadExecutor(); PathChildrenCache cache = new PathChildrenCache(client, "/test", true, false, exec); cache.getListenable().addListener ( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { if ( event.getData().getPath().equals("/test/one") ) { events.offer(event.getType()); } } } ); cache.start(); final BlockingQueue events2 = new LinkedBlockingQueue(); PathChildrenCache cache2 = new PathChildrenCache(client, "/test", true, false, exec); cache2.getListenable().addListener( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { if ( event.getData().getPath().equals("/test/one") ) { events2.offer(event.getType()); } } } ); cache2.start(); client.create().forPath("/test/one", "hey there".getBytes()); Assert.assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_ADDED); Assert.assertEquals(events2.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_ADDED); client.setData().forPath("/test/one", "sup!".getBytes()); Assert.assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_UPDATED); Assert.assertEquals(events2.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_UPDATED); Assert.assertEquals(new String(cache.getCurrentData("/test/one").getData()), "sup!"); Assert.assertEquals(new String(cache2.getCurrentData("/test/one").getData()), "sup!"); client.delete().forPath("/test/one"); Assert.assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_REMOVED); Assert.assertEquals(events2.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_REMOVED); cache.close(); cache2.close(); } finally { client.close(); } } @Test public void testDeleteNodeAfterCloseDoesntCallExecutor() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/test"); final ExecuteCalledWatchingExecutorService exec = new ExecuteCalledWatchingExecutorService(Executors.newSingleThreadExecutor()); PathChildrenCache cache = new PathChildrenCache(client, "/test", true, false, exec); cache.start(); client.create().forPath("/test/one", "hey there".getBytes()); cache.rebuild(); Assert.assertEquals(new String(cache.getCurrentData("/test/one").getData()), "hey there"); Assert.assertTrue(exec.isExecuteCalled()); exec.setExecuteCalled(false); cache.close(); Assert.assertFalse(exec.isExecuteCalled()); client.delete().forPath("/test/one"); timing.sleepABit(); Assert.assertFalse(exec.isExecuteCalled()); } finally { client.close(); } } /** * Tests the case where there's an outstanding operation being executed when the cache is * shut down. See CURATOR-121, this was causing misleading warning messages to be logged. * @throws Exception */ @Test public void testInterruptedOperationOnShutdown() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), 30000, 30000, new RetryOneTime(1)); client.start(); try { final CountDownLatch latch = new CountDownLatch(1); final PathChildrenCache cache = new PathChildrenCache(client, "/test", false) { @Override protected void handleException(Throwable e) { latch.countDown(); } }; cache.start(); cache.offerOperation(new Operation() { @Override public void invoke() throws Exception { Thread.sleep(5000); } }); Thread.sleep(1000); cache.close(); latch.await(5, TimeUnit.SECONDS); Assert.assertTrue(latch.getCount() == 1, "Unexpected exception occurred"); } finally { CloseableUtils.closeQuietly(client); } } public static class ExecuteCalledWatchingExecutorService extends DelegatingExecutorService { boolean executeCalled = false; public ExecuteCalledWatchingExecutorService(ExecutorService delegate) { super(delegate); } @Override public synchronized void execute(Runnable command) { executeCalled = true; super.execute(command); } public synchronized boolean isExecuteCalled() { return executeCalled; } public synchronized void setExecuteCalled(boolean executeCalled) { this.executeCalled = executeCalled; } } public static class DelegatingExecutorService implements ExecutorService { private final ExecutorService delegate; public DelegatingExecutorService( ExecutorService delegate ) { this.delegate = delegate; } @Override public void shutdown() { delegate.shutdown(); } @Override public List shutdownNow() { return delegate.shutdownNow(); } @Override public boolean isShutdown() { return delegate.isShutdown(); } @Override public boolean isTerminated() { return delegate.isTerminated(); } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return delegate.awaitTermination(timeout, unit); } @Override public Future submit(Callable task) { return delegate.submit(task); } @Override public Future submit(Runnable task, T result) { return delegate.submit(task, result); } @Override public Future submit(Runnable task) { return delegate.submit(task); } @Override public List> invokeAll(Collection> tasks) throws InterruptedException { return delegate.invokeAll(tasks); } @Override public List> invokeAll(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException { return delegate.invokeAll(tasks, timeout, unit); } @Override public T invokeAny(Collection> tasks) throws InterruptedException, ExecutionException { return delegate.invokeAny(tasks); } @Override public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return delegate.invokeAny(tasks, timeout, unit); } @Override public void execute(Runnable command) { delegate.execute(command); } } } TestPathChildrenCacheInCluster.java000066400000000000000000000101311245521677600426340ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.InstanceSpec; import org.apache.curator.test.TestingCluster; import org.apache.curator.test.Timing; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; public class TestPathChildrenCacheInCluster { @Test public void testServerLoss() throws Exception { Timing timing = new Timing(); CuratorFramework client = null; PathChildrenCache cache = null; TestingCluster cluster = new TestingCluster(3); try { cluster.start(); client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); client.create().creatingParentsIfNeeded().forPath("/test"); cache = new PathChildrenCache(client, "/test", false); cache.start(); final CountDownLatch resetLatch = new CountDownLatch(1); final CountDownLatch reconnectLatch = new CountDownLatch(1); final AtomicReference latch = new AtomicReference(new CountDownLatch(3)); cache.getListenable().addListener ( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { if ( event.getType() == PathChildrenCacheEvent.Type.CONNECTION_SUSPENDED ) { resetLatch.countDown(); } else if ( event.getType() == PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED ) { reconnectLatch.countDown(); } else if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) { latch.get().countDown(); } } } ); client.create().forPath("/test/one"); client.create().forPath("/test/two"); client.create().forPath("/test/three"); Assert.assertTrue(latch.get().await(10, TimeUnit.SECONDS)); InstanceSpec connectionInstance = cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper()); cluster.killServer(connectionInstance); Assert.assertTrue(timing.awaitLatch(reconnectLatch)); Assert.assertEquals(cache.getCurrentData().size(), 3); } finally { CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(cluster); } } } TestTreeCache.java000066400000000000000000000467401245521677600373540ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; import com.google.common.collect.ImmutableSet; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.test.KillSession; import org.apache.curator.utils.CloseableUtils; import org.apache.zookeeper.CreateMode; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.Semaphore; public class TestTreeCache extends BaseTestTreeCache { @Test public void testStartup() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/1", "one".getBytes()); client.create().forPath("/test/2", "two".getBytes()); client.create().forPath("/test/3", "three".getBytes()); client.create().forPath("/test/2/sub", "two-sub".getBytes()); cache = newTreeCacheWithListeners(client, "/test"); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/1", "one".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/2", "two".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/3", "three".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/2/sub", "two-sub".getBytes()); assertEvent(TreeCacheEvent.Type.INITIALIZED); assertNoMoreEvents(); Assert.assertEquals(cache.getCurrentChildren("/test").keySet(), ImmutableSet.of("1", "2", "3")); Assert.assertEquals(cache.getCurrentChildren("/test/1").keySet(), ImmutableSet.of()); Assert.assertEquals(cache.getCurrentChildren("/test/2").keySet(), ImmutableSet.of("sub")); Assert.assertNull(cache.getCurrentChildren("/test/non_exist")); } @Test public void testStartEmpty() throws Exception { cache = newTreeCacheWithListeners(client, "/test"); cache.start(); assertEvent(TreeCacheEvent.Type.INITIALIZED); client.create().forPath("/test"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertNoMoreEvents(); } @Test public void testStartEmptyDeeper() throws Exception { cache = newTreeCacheWithListeners(client, "/test/foo/bar"); cache.start(); assertEvent(TreeCacheEvent.Type.INITIALIZED); client.create().creatingParentsIfNeeded().forPath("/test/foo"); assertNoMoreEvents(); client.create().forPath("/test/foo/bar"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/foo/bar"); assertNoMoreEvents(); } @Test public void testDepth0() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/1", "one".getBytes()); client.create().forPath("/test/2", "two".getBytes()); client.create().forPath("/test/3", "three".getBytes()); client.create().forPath("/test/2/sub", "two-sub".getBytes()); cache = buildWithListeners(TreeCache.newBuilder(client, "/test").setMaxDepth(0)); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.INITIALIZED); assertNoMoreEvents(); Assert.assertEquals(cache.getCurrentChildren("/test").keySet(), ImmutableSet.of()); Assert.assertNull(cache.getCurrentData("/test/1")); Assert.assertNull(cache.getCurrentChildren("/test/1")); Assert.assertNull(cache.getCurrentData("/test/non_exist")); } @Test public void testDepth1() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/1", "one".getBytes()); client.create().forPath("/test/2", "two".getBytes()); client.create().forPath("/test/3", "three".getBytes()); client.create().forPath("/test/2/sub", "two-sub".getBytes()); cache = buildWithListeners(TreeCache.newBuilder(client, "/test").setMaxDepth(1)); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/1", "one".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/2", "two".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/3", "three".getBytes()); assertEvent(TreeCacheEvent.Type.INITIALIZED); assertNoMoreEvents(); Assert.assertEquals(cache.getCurrentChildren("/test").keySet(), ImmutableSet.of("1", "2", "3")); Assert.assertEquals(cache.getCurrentChildren("/test/1").keySet(), ImmutableSet.of()); Assert.assertEquals(cache.getCurrentChildren("/test/2").keySet(), ImmutableSet.of()); Assert.assertNull(cache.getCurrentData("/test/2/sub")); Assert.assertNull(cache.getCurrentChildren("/test/2/sub")); Assert.assertNull(cache.getCurrentChildren("/test/non_exist")); } @Test public void testDepth1Deeper() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/foo"); client.create().forPath("/test/foo/bar"); client.create().forPath("/test/foo/bar/1", "one".getBytes()); client.create().forPath("/test/foo/bar/2", "two".getBytes()); client.create().forPath("/test/foo/bar/3", "three".getBytes()); client.create().forPath("/test/foo/bar/2/sub", "two-sub".getBytes()); cache = buildWithListeners(TreeCache.newBuilder(client, "/test/foo/bar").setMaxDepth(1)); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/foo/bar"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/foo/bar/1", "one".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/foo/bar/2", "two".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/foo/bar/3", "three".getBytes()); assertEvent(TreeCacheEvent.Type.INITIALIZED); assertNoMoreEvents(); } @Test public void testAsyncInitialPopulation() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/one", "hey there".getBytes()); cache = newTreeCacheWithListeners(client, "/test"); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/one"); assertEvent(TreeCacheEvent.Type.INITIALIZED); assertNoMoreEvents(); } @Test public void testFromRoot() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/one", "hey there".getBytes()); cache = newTreeCacheWithListeners(client, "/"); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/one"); assertEvent(TreeCacheEvent.Type.INITIALIZED); assertNoMoreEvents(); Assert.assertTrue(cache.getCurrentChildren("/").keySet().contains("test")); Assert.assertEquals(cache.getCurrentChildren("/test").keySet(), ImmutableSet.of("one")); Assert.assertEquals(cache.getCurrentChildren("/test/one").keySet(), ImmutableSet.of()); Assert.assertEquals(new String(cache.getCurrentData("/test/one").getData()), "hey there"); } @Test public void testFromRootWithDepth() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/one", "hey there".getBytes()); cache = buildWithListeners(TreeCache.newBuilder(client, "/").setMaxDepth(1)); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.INITIALIZED); assertNoMoreEvents(); Assert.assertTrue(cache.getCurrentChildren("/").keySet().contains("test")); Assert.assertEquals(cache.getCurrentChildren("/test").keySet(), ImmutableSet.of()); Assert.assertNull(cache.getCurrentData("/test/one")); Assert.assertNull(cache.getCurrentChildren("/test/one")); } @Test public void testWithNamespace() throws Exception { client.create().forPath("/outer"); client.create().forPath("/outer/foo"); client.create().forPath("/outer/test"); client.create().forPath("/outer/test/one", "hey there".getBytes()); cache = newTreeCacheWithListeners(client.usingNamespace("outer"), "/test"); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/one"); assertEvent(TreeCacheEvent.Type.INITIALIZED); assertNoMoreEvents(); Assert.assertEquals(cache.getCurrentChildren("/test").keySet(), ImmutableSet.of("one")); Assert.assertEquals(cache.getCurrentChildren("/test/one").keySet(), ImmutableSet.of()); Assert.assertEquals(new String(cache.getCurrentData("/test/one").getData()), "hey there"); } @Test public void testWithNamespaceAtRoot() throws Exception { client.create().forPath("/outer"); client.create().forPath("/outer/foo"); client.create().forPath("/outer/test"); client.create().forPath("/outer/test/one", "hey there".getBytes()); cache = newTreeCacheWithListeners(client.usingNamespace("outer"), "/"); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/foo"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/one"); assertEvent(TreeCacheEvent.Type.INITIALIZED); assertNoMoreEvents(); Assert.assertEquals(cache.getCurrentChildren("/").keySet(), ImmutableSet.of("foo", "test")); Assert.assertEquals(cache.getCurrentChildren("/foo").keySet(), ImmutableSet.of()); Assert.assertEquals(cache.getCurrentChildren("/test").keySet(), ImmutableSet.of("one")); Assert.assertEquals(cache.getCurrentChildren("/test/one").keySet(), ImmutableSet.of()); Assert.assertEquals(new String(cache.getCurrentData("/test/one").getData()), "hey there"); } @Test public void testSyncInitialPopulation() throws Exception { cache = newTreeCacheWithListeners(client, "/test"); cache.start(); assertEvent(TreeCacheEvent.Type.INITIALIZED); client.create().forPath("/test"); client.create().forPath("/test/one", "hey there".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/one"); assertNoMoreEvents(); } @Test public void testChildrenInitialized() throws Exception { client.create().forPath("/test", "".getBytes()); client.create().forPath("/test/1", "1".getBytes()); client.create().forPath("/test/2", "2".getBytes()); client.create().forPath("/test/3", "3".getBytes()); cache = newTreeCacheWithListeners(client, "/test"); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/1"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/2"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/3"); assertEvent(TreeCacheEvent.Type.INITIALIZED); assertNoMoreEvents(); } @Test public void testUpdateWhenNotCachingData() throws Exception { client.create().forPath("/test"); cache = buildWithListeners(TreeCache.newBuilder(client, "/test").setCacheData(false)); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.INITIALIZED); client.create().forPath("/test/foo", "first".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/foo"); client.setData().forPath("/test/foo", "something new".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_UPDATED, "/test/foo"); assertNoMoreEvents(); Assert.assertNotNull(cache.getCurrentData("/test/foo")); // No byte data querying the tree because we're not caching data. Assert.assertNull(cache.getCurrentData("/test/foo").getData()); } @Test public void testDeleteThenCreate() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/foo", "one".getBytes()); cache = newTreeCacheWithListeners(client, "/test"); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/foo"); assertEvent(TreeCacheEvent.Type.INITIALIZED); client.delete().forPath("/test/foo"); assertEvent(TreeCacheEvent.Type.NODE_REMOVED, "/test/foo"); client.create().forPath("/test/foo", "two".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/foo"); assertNoMoreEvents(); } @Test public void testKilledSession() throws Exception { client.create().forPath("/test"); cache = newTreeCacheWithListeners(client, "/test"); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.INITIALIZED); client.create().forPath("/test/foo", "foo".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/foo"); client.create().withMode(CreateMode.EPHEMERAL).forPath("/test/me", "data".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/me"); KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString()); assertEvent(TreeCacheEvent.Type.CONNECTION_SUSPENDED); assertEvent(TreeCacheEvent.Type.CONNECTION_LOST); assertEvent(TreeCacheEvent.Type.CONNECTION_RECONNECTED); assertEvent(TreeCacheEvent.Type.NODE_REMOVED, "/test/me"); assertNoMoreEvents(); } @Test public void testBasics() throws Exception { client.create().forPath("/test"); cache = newTreeCacheWithListeners(client, "/test"); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.INITIALIZED); Assert.assertEquals(cache.getCurrentChildren("/test").keySet(), ImmutableSet.of()); client.create().forPath("/test/one", "hey there".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/one"); Assert.assertEquals(cache.getCurrentChildren("/test").keySet(), ImmutableSet.of("one")); Assert.assertEquals(new String(cache.getCurrentData("/test/one").getData()), "hey there"); client.setData().forPath("/test/one", "sup!".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_UPDATED, "/test/one"); Assert.assertEquals(cache.getCurrentChildren("/test").keySet(), ImmutableSet.of("one")); Assert.assertEquals(new String(cache.getCurrentData("/test/one").getData()), "sup!"); client.delete().forPath("/test/one"); assertEvent(TreeCacheEvent.Type.NODE_REMOVED, "/test/one"); Assert.assertEquals(cache.getCurrentChildren("/test").keySet(), ImmutableSet.of()); assertNoMoreEvents(); } @Test public void testBasicsOnTwoCaches() throws Exception { TreeCache cache2 = newTreeCacheWithListeners(client, "/test"); cache2.getListenable().removeListener(eventListener); // Don't listen on the second cache. // Just ensures the same event count; enables test flow control on cache2. final Semaphore semaphore = new Semaphore(0); cache2.getListenable().addListener(new TreeCacheListener() { @Override public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception { semaphore.release(); } }); try { client.create().forPath("/test"); cache = newTreeCacheWithListeners(client, "/test"); cache.start(); cache2.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.INITIALIZED); semaphore.acquire(2); client.create().forPath("/test/one", "hey there".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/one"); Assert.assertEquals(new String(cache.getCurrentData("/test/one").getData()), "hey there"); semaphore.acquire(); Assert.assertEquals(new String(cache2.getCurrentData("/test/one").getData()), "hey there"); client.setData().forPath("/test/one", "sup!".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_UPDATED, "/test/one"); Assert.assertEquals(new String(cache.getCurrentData("/test/one").getData()), "sup!"); semaphore.acquire(); Assert.assertEquals(new String(cache2.getCurrentData("/test/one").getData()), "sup!"); client.delete().forPath("/test/one"); assertEvent(TreeCacheEvent.Type.NODE_REMOVED, "/test/one"); Assert.assertNull(cache.getCurrentData("/test/one")); semaphore.acquire(); Assert.assertNull(cache2.getCurrentData("/test/one")); assertNoMoreEvents(); Assert.assertEquals(semaphore.availablePermits(), 0); } finally { CloseableUtils.closeQuietly(cache2); } } @Test public void testDeleteNodeAfterCloseDoesntCallExecutor() throws Exception { client.create().forPath("/test"); cache = newTreeCacheWithListeners(client, "/test"); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.INITIALIZED); client.create().forPath("/test/one", "hey there".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/one"); Assert.assertEquals(new String(cache.getCurrentData("/test/one").getData()), "hey there"); cache.close(); assertNoMoreEvents(); client.delete().forPath("/test/one"); assertNoMoreEvents(); } /** * Make sure TreeCache gets to a sane state when we can't initially connect to server. */ @Test public void testServerNotStartedYet() throws Exception { // Stop the existing server. server.stop(); // Shutdown the existing client and re-create it started. client.close(); initCuratorFramework(); // Start the client disconnected. cache = newTreeCacheWithListeners(client, "/test"); cache.start(); assertNoMoreEvents(); // Now restart the server. server.restart(); assertEvent(TreeCacheEvent.Type.INITIALIZED); client.create().forPath("/test"); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertNoMoreEvents(); } } TestTreeCacheRandomTree.java000066400000000000000000000207531245521677600413310ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; import com.google.common.collect.Iterables; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.ZKPaths; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Random; public class TestTreeCacheRandomTree extends BaseTestTreeCache { /** * A randomly generated source-of-truth node for {@link #testGiantRandomDeepTree()} */ private static final class TestNode { String fullPath; byte[] data; Map children = new HashMap(); TestNode(String fullPath, byte[] data) { this.fullPath = fullPath; this.data = data; } } // These constants will produce a tree about 10 levels deep. private static final int ITERATIONS = 1000; private static final double DIVE_CHANCE = 0.9; private static final int TEST_DEPTH = 5; private final Random random = new Random(); private boolean withDepth = false; @Test public void testGiantRandomDeepTree() throws Exception { doTestGiantRandomDeepTree(); } @Test public void testGiantRandomDeepTreeWithDepth() throws Exception { withDepth = true; doTestGiantRandomDeepTree(); } /** * Randomly construct a large tree of test data in memory, mirror it into ZK, and then use * a TreeCache to follow the changes. At each step, assert that TreeCache matches our * source-of-truth test data, and that we see exactly the set of events we expect to see. */ private void doTestGiantRandomDeepTree() throws Exception { client.create().forPath("/tree", null); CuratorFramework cl = client.usingNamespace("tree"); if ( withDepth ) { cache = buildWithListeners(TreeCache.newBuilder(cl, "/").setMaxDepth(TEST_DEPTH)); } else { cache = newTreeCacheWithListeners(cl, "/"); } cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/"); assertEvent(TreeCacheEvent.Type.INITIALIZED); TestNode root = new TestNode("/", null); int maxDepth = 0; int adds = 0; int removals = 0; int updates = 0; for ( int i = 0; i < ITERATIONS; ++i ) { // Select a node to update, randomly navigate down through the tree int depth = 0; TestNode last = null; TestNode node = root; while ( !node.children.isEmpty() && random.nextDouble() < DIVE_CHANCE ) { // Go down a level in the tree. Select a random child for the next iteration. last = node; node = Iterables.get(node.children.values(), random.nextInt(node.children.size())); ++depth; } maxDepth = Math.max(depth, maxDepth); // Okay we found a node, let's do something interesting with it. switch ( random.nextInt(3) ) { case 0: // Try a removal if we have no children and we're not the root node. if ( node != root && node.children.isEmpty() ) { // Delete myself from parent. TestNode removed = last.children.remove(ZKPaths.getNodeFromPath(node.fullPath)); Assert.assertSame(node, removed); // Delete from ZK cl.delete().forPath(node.fullPath); // TreeCache should see the delete. if (shouldSeeEventAt(node.fullPath)) { assertEvent(TreeCacheEvent.Type.NODE_REMOVED, node.fullPath); } ++removals; } break; case 1: // Do an update. byte[] newData = new byte[10]; random.nextBytes(newData); if ( Arrays.equals(node.data, newData) ) { // Randomly generated the same data! Very small chance, just skip. continue; } // Update source-of-truth. node.data = newData; // Update in ZK. cl.setData().forPath(node.fullPath, node.data); // TreeCache should see the update. if (shouldSeeEventAt(node.fullPath)) { assertEvent(TreeCacheEvent.Type.NODE_UPDATED, node.fullPath, node.data); } ++updates; break; case 2: // Add a new child. String name = Long.toHexString(random.nextLong()); if ( node.children.containsKey(name) ) { // Randomly generated the same name! Very small chance, just skip. continue; } // Add a new child to our test tree. byte[] data = new byte[10]; random.nextBytes(data); TestNode child = new TestNode(ZKPaths.makePath(node.fullPath, name), data); node.children.put(name, child); // Add to ZK. cl.create().forPath(child.fullPath, child.data); // TreeCache should see the add. if (shouldSeeEventAt(child.fullPath)) { assertEvent(TreeCacheEvent.Type.NODE_ADDED, child.fullPath, child.data); } ++adds; break; } // Each iteration, ensure the cached state matches our source-of-truth tree. assertNodeEquals(cache.getCurrentData("/"), root); assertTreeEquals(cache, root, 0); } // Typical stats for this test: maxDepth: 10, adds: 349, removals: 198, updates: 320 // We get more adds than removals because removals only happen if we're at a leaf. System.out.println(String.format("maxDepth: %s, adds: %s, removals: %s, updates: %s", maxDepth, adds, removals, updates)); assertNoMoreEvents(); } /** * Returns true we should see an event at this path based on maxDepth, false otherwise. */ private boolean shouldSeeEventAt(String fullPath) { return !withDepth || ZKPaths.split(fullPath).size() <= TEST_DEPTH; } /** * Recursively assert that current children equal expected children. */ private void assertTreeEquals(TreeCache cache, TestNode expectedNode, int depth) { String path = expectedNode.fullPath; Map cacheChildren = cache.getCurrentChildren(path); Assert.assertNotNull(cacheChildren, path); if (withDepth && depth == TEST_DEPTH) { return; } Assert.assertEquals(cacheChildren.keySet(), expectedNode.children.keySet(), path); for ( Map.Entry entry : expectedNode.children.entrySet() ) { String nodeName = entry.getKey(); ChildData childData = cacheChildren.get(nodeName); TestNode expectedChild = entry.getValue(); assertNodeEquals(childData, expectedChild); assertTreeEquals(cache, expectedChild, depth + 1); } } /** * Assert that the given node data matches expected test node data. */ private static void assertNodeEquals(ChildData actualChild, TestNode expectedNode) { String path = expectedNode.fullPath; Assert.assertNotNull(actualChild, path); Assert.assertEquals(actualChild.getData(), expectedNode.data, path); } } 000077500000000000000000000000001245521677600342045ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leaderChaosMonkeyCnxnFactory.java000066400000000000000000000114711245521677600414520ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.leader; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.proto.CreateRequest; import org.apache.zookeeper.server.ByteBufferInputStream; import org.apache.zookeeper.server.NIOServerCnxn; import org.apache.zookeeper.server.NIOServerCnxnFactory; import org.apache.zookeeper.server.Request; import org.apache.zookeeper.server.ZooKeeperServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; /** * A connection factory that will behave like the NIOServerCnxnFactory except that * it will unexpectedly close the connection right after the first znode has * been created in Zookeeper. * Subsequent create operations will succeed. */ public class ChaosMonkeyCnxnFactory extends NIOServerCnxnFactory { public static final String CHAOS_ZNODE = "/mylock"; public static final String CHAOS_ZNODE_PREFIX = CHAOS_ZNODE + "/"; private static final Logger log = LoggerFactory.getLogger(ChaosMonkeyCnxnFactory.class); /* How long after the first error, connections are rejected */ public static final long LOCKOUT_DURATION_MS = 6000; public ChaosMonkeyCnxnFactory() throws IOException { } @Override public void startup(ZooKeeperServer zks) throws IOException, InterruptedException { super.startup(new ChaosMonkeyZookeeperServer(zks)); } /** * Build a connection with a Chaos Monkey ZookeeperServer */ protected NIOServerCnxn createConnection(SocketChannel sock, SelectionKey sk) throws IOException { return new NIOServerCnxn(zkServer, sock, sk, this); } public static class ChaosMonkeyZookeeperServer extends ZooKeeperServer { private long firstError = 0; public ChaosMonkeyZookeeperServer(ZooKeeperServer zks) { setTxnLogFactory(zks.getTxnLogFactory()); setTickTime(zks.getTickTime()); setMinSessionTimeout(zks.getMinSessionTimeout()); setMaxSessionTimeout(zks.getMaxSessionTimeout()); } @Override public void submitRequest(Request si) { long remaining = firstError != 0 ? LOCKOUT_DURATION_MS - (System.currentTimeMillis() - firstError) : 0; if ( si.type != ZooDefs.OpCode.createSession && si.type != ZooDefs.OpCode.sync && si.type != ZooDefs.OpCode.ping && firstError != 0 && remaining > 0 ) { log.debug("Rejected : " + si.toString()); // Still reject request log.debug("Still not ready for " + remaining + "ms"); ((NIOServerCnxn)si.cnxn).close(); return; } // Submit the request to the legacy Zookeeper server log.debug("Applied : " + si.toString()); super.submitRequest(si); // Raise an error if a lock is created if ( si.type == ZooDefs.OpCode.create ) { CreateRequest createRequest = new CreateRequest(); try { ByteBuffer duplicate = si.request.duplicate(); duplicate.rewind(); ByteBufferInputStream.byteBuffer2Record(duplicate, createRequest); if ( createRequest.getPath().startsWith(CHAOS_ZNODE_PREFIX) && firstError == 0 ) { firstError = System.currentTimeMillis(); // The znode has been created, close the connection and don't tell it to client log.warn("Closing connection right after " + createRequest.getPath() + " creation"); ((NIOServerCnxn)si.cnxn).close(); } } catch ( Exception e ) { // Should not happen ((NIOServerCnxn)si.cnxn).close(); } } } } } TestLeaderLatch.java000066400000000000000000000577211245521677600400730ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.leader; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryNTimes; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.TestingServer; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; public class TestLeaderLatch extends BaseClassForTests { private static final String PATH_NAME = "/one/two/me"; private static final int MAX_LOOPS = 5; @Test public void testProperCloseWithoutConnectionEstablished() throws Exception { server.stop(); Timing timing = new Timing(); LeaderLatch latch = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); final AtomicBoolean resetCalled = new AtomicBoolean(false); final CountDownLatch cancelStartTaskLatch = new CountDownLatch(1); latch = new LeaderLatch(client, PATH_NAME) { @Override void reset() throws Exception { resetCalled.set(true); super.reset(); } @Override protected boolean cancelStartTask() { if ( super.cancelStartTask() ) { cancelStartTaskLatch.countDown(); return true; } return false; } }; latch.start(); latch.close(); latch = null; Assert.assertTrue(timing.awaitLatch(cancelStartTaskLatch)); Assert.assertFalse(resetCalled.get()); } finally { CloseableUtils.closeQuietly(latch); CloseableUtils.closeQuietly(client); } } @Test public void testResetRace() throws Exception { Timing timing = new Timing(); LeaderLatch latch = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); latch = new LeaderLatch(client, PATH_NAME); latch.debugResetWaitLatch = new CountDownLatch(1); latch.start(); // will call reset() latch.reset(); // should not result in two nodes timing.sleepABit(); latch.debugResetWaitLatch.countDown(); timing.sleepABit(); Assert.assertEquals(client.getChildren().forPath(PATH_NAME).size(), 1); } finally { CloseableUtils.closeQuietly(latch); CloseableUtils.closeQuietly(client); } } @Test public void testCreateDeleteRace() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); client.create().creatingParentsIfNeeded().forPath(PATH_NAME); LeaderLatch latch = new LeaderLatch(client, PATH_NAME); latch.debugResetWaitLatch = new CountDownLatch(1); latch.start(); latch.close(); timing.sleepABit(); latch.debugResetWaitLatch.countDown(); timing.sleepABit(); Assert.assertEquals(client.getChildren().forPath(PATH_NAME).size(), 0); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testLostConnection() throws Exception { final int PARTICIPANT_QTY = 10; List latches = Lists.newArrayList(); final Timing timing = new Timing(); final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); final CountDownLatch countDownLatch = new CountDownLatch(1); client.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState == ConnectionState.LOST ) { countDownLatch.countDown(); } } }); for ( int i = 0; i < PARTICIPANT_QTY; ++i ) { LeaderLatch latch = new LeaderLatch(client, PATH_NAME); latch.start(); latches.add(latch); } waitForALeader(latches, timing); server.stop(); Assert.assertTrue(timing.awaitLatch(countDownLatch)); timing.forWaiting().sleepABit(); Assert.assertEquals(getLeaders(latches).size(), 0); server.restart(); Assert.assertEquals(waitForALeader(latches, timing).size(), 1); // should reconnect } finally { for ( LeaderLatch latch : latches ) { CloseableUtils.closeQuietly(latch); } CloseableUtils.closeQuietly(client); } } @Test public void testCorrectWatching() throws Exception { final int PARTICIPANT_QTY = 10; final int PARTICIPANT_ID = 2; List latches = Lists.newArrayList(); final Timing timing = new Timing(); final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); for ( int i = 0; i < PARTICIPANT_QTY; ++i ) { LeaderLatch latch = new LeaderLatch(client, PATH_NAME); latch.start(); latches.add(latch); } waitForALeader(latches, timing); //we need to close a Participant that doesn't be actual leader (first Participant) nor the last latches.get(PARTICIPANT_ID).close(); //As the previous algorithm assumed that if the watched node is deleted gets the leadership //we need to ensure that the PARTICIPANT_ID-1 is not getting (wrongly) elected as leader. Assert.assertTrue(!latches.get(PARTICIPANT_ID - 1).hasLeadership()); } finally { //removes the already closed participant latches.remove(PARTICIPANT_ID); for ( LeaderLatch latch : latches ) { CloseableUtils.closeQuietly(latch); } CloseableUtils.closeQuietly(client); } } @Test public void testWaiting() throws Exception { final int LOOPS = 10; for ( int i = 0; i < LOOPS; ++i ) { System.out.println("TRY #" + i); internalTestWaitingOnce(); Thread.sleep(10); } } private void internalTestWaitingOnce() throws Exception { final int PARTICIPANT_QTY = 10; ExecutorService executorService = Executors.newFixedThreadPool(PARTICIPANT_QTY); ExecutorCompletionService service = new ExecutorCompletionService(executorService); final Timing timing = new Timing(); final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); final AtomicBoolean thereIsALeader = new AtomicBoolean(false); for ( int i = 0; i < PARTICIPANT_QTY; ++i ) { service.submit(new Callable() { @Override public Void call() throws Exception { LeaderLatch latch = new LeaderLatch(client, PATH_NAME); try { latch.start(); Assert.assertTrue(latch.await(timing.forWaiting().seconds(), TimeUnit.SECONDS)); Assert.assertTrue(thereIsALeader.compareAndSet(false, true)); Thread.sleep((int)(10 * Math.random())); thereIsALeader.set(false); } finally { latch.close(); } return null; } }); } for ( int i = 0; i < PARTICIPANT_QTY; ++i ) { service.take().get(); } } finally { executorService.shutdownNow(); CloseableUtils.closeQuietly(client); } } @Test public void testBasic() throws Exception { basic(Mode.START_IMMEDIATELY); } @Test public void testBasicAlt() throws Exception { basic(Mode.START_IN_THREADS); } @Test public void testCallbackSanity() throws Exception { final int PARTICIPANT_QTY = 10; final CountDownLatch timesSquare = new CountDownLatch(PARTICIPANT_QTY); final AtomicLong masterCounter = new AtomicLong(0); final AtomicLong notLeaderCounter = new AtomicLong(0); Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); ExecutorService exec = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setDaemon(true).setNameFormat("callbackSanity-%s").build()); List latches = Lists.newArrayList(); for ( int i = 0; i < PARTICIPANT_QTY; ++i ) { final LeaderLatch latch = new LeaderLatch(client, PATH_NAME); latch.addListener(new LeaderLatchListener() { boolean beenLeader = false; @Override public void isLeader() { if ( !beenLeader ) { masterCounter.incrementAndGet(); beenLeader = true; try { latch.reset(); } catch ( Exception e ) { throw Throwables.propagate(e); } } else { masterCounter.incrementAndGet(); CloseableUtils.closeQuietly(latch); timesSquare.countDown(); } } @Override public void notLeader() { notLeaderCounter.incrementAndGet(); } }, exec); latches.add(latch); } try { client.start(); for ( LeaderLatch latch : latches ) { latch.start(); } timesSquare.await(); Assert.assertEquals(masterCounter.get(), PARTICIPANT_QTY * 2); Assert.assertEquals(notLeaderCounter.get(), PARTICIPANT_QTY); for ( LeaderLatch latch : latches ) { Assert.assertEquals(latch.getState(), LeaderLatch.State.CLOSED); } } finally { for ( LeaderLatch latch : latches ) { if ( latch.getState() != LeaderLatch.State.CLOSED ) { CloseableUtils.closeQuietly(latch); } } CloseableUtils.closeQuietly(client); } } @Test public void testCallbackNotifyLeader() throws Exception { final int PARTICIPANT_QTY = 10; final int SILENT_QTY = 3; final CountDownLatch timesSquare = new CountDownLatch(PARTICIPANT_QTY); final AtomicLong masterCounter = new AtomicLong(0); final AtomicLong notLeaderCounter = new AtomicLong(0); Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); ExecutorService exec = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setDaemon(true).setNameFormat("callbackNotifyLeader-%s").build()); List latches = Lists.newArrayList(); for ( int i = 0; i < PARTICIPANT_QTY; ++i ) { LeaderLatch.CloseMode closeMode = i < SILENT_QTY ? LeaderLatch.CloseMode.SILENT : LeaderLatch.CloseMode.NOTIFY_LEADER; final LeaderLatch latch = new LeaderLatch(client, PATH_NAME, "", closeMode); latch.addListener(new LeaderLatchListener() { boolean beenLeader = false; @Override public void isLeader() { if ( !beenLeader ) { masterCounter.incrementAndGet(); beenLeader = true; try { latch.reset(); } catch ( Exception e ) { throw Throwables.propagate(e); } } else { masterCounter.incrementAndGet(); CloseableUtils.closeQuietly(latch); timesSquare.countDown(); } } @Override public void notLeader() { notLeaderCounter.incrementAndGet(); } }, exec); latches.add(latch); } try { client.start(); for ( LeaderLatch latch : latches ) { latch.start(); } timesSquare.await(); Assert.assertEquals(masterCounter.get(), PARTICIPANT_QTY * 2); Assert.assertEquals(notLeaderCounter.get(), PARTICIPANT_QTY * 2 - SILENT_QTY); for ( LeaderLatch latch : latches ) { Assert.assertEquals(latch.getState(), LeaderLatch.State.CLOSED); } } finally { for ( LeaderLatch latch : latches ) { if ( latch.getState() != LeaderLatch.State.CLOSED ) { CloseableUtils.closeQuietly(latch); } } CloseableUtils.closeQuietly(client); } } @Test public void testCallbackDontNotify() throws Exception { final AtomicLong masterCounter = new AtomicLong(0); final AtomicLong notLeaderCounter = new AtomicLong(0); Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); final LeaderLatch leader = new LeaderLatch(client, PATH_NAME); final LeaderLatch notifiedLeader = new LeaderLatch(client, PATH_NAME, "", LeaderLatch.CloseMode.NOTIFY_LEADER); leader.addListener(new LeaderLatchListener() { @Override public void isLeader() { } @Override public void notLeader() { masterCounter.incrementAndGet(); } }); notifiedLeader.addListener(new LeaderLatchListener() { @Override public void isLeader() { } @Override public void notLeader() { notLeaderCounter.incrementAndGet(); } }); try { client.start(); leader.start(); timing.sleepABit(); notifiedLeader.start(); timing.sleepABit(); notifiedLeader.close(); timing.sleepABit(); // Test the close override leader.close(LeaderLatch.CloseMode.NOTIFY_LEADER); Assert.assertEquals(leader.getState(), LeaderLatch.State.CLOSED); Assert.assertEquals(notifiedLeader.getState(), LeaderLatch.State.CLOSED); Assert.assertEquals(masterCounter.get(), 1); Assert.assertEquals(notLeaderCounter.get(), 0); } finally { if ( leader.getState() != LeaderLatch.State.CLOSED ) { CloseableUtils.closeQuietly(leader); } if ( notifiedLeader.getState() != LeaderLatch.State.CLOSED ) { CloseableUtils.closeQuietly(notifiedLeader); } CloseableUtils.closeQuietly(client); } } @Test public void testNoServerAtStart() { CloseableUtils.closeQuietly(server); Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryNTimes(5, 1000)); client.start(); final LeaderLatch leader = new LeaderLatch(client, PATH_NAME); final CountDownLatch leaderCounter = new CountDownLatch(1); final AtomicInteger leaderCount = new AtomicInteger(0); final AtomicInteger notLeaderCount = new AtomicInteger(0); leader.addListener(new LeaderLatchListener() { @Override public void isLeader() { leaderCounter.countDown(); leaderCount.incrementAndGet(); } @Override public void notLeader() { notLeaderCount.incrementAndGet(); } }); try { leader.start(); timing.sleepABit(); // Start the new server server = new TestingServer(server.getPort(), server.getTempDirectory()); Assert.assertTrue(timing.awaitLatch(leaderCounter), "Not elected leader"); Assert.assertEquals(leaderCount.get(), 1, "Elected too many times"); Assert.assertEquals(notLeaderCount.get(), 0, "Unelected too many times"); } catch ( Exception e ) { Assert.fail("Unexpected exception", e); } finally { CloseableUtils.closeQuietly(leader); CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(server); } } private enum Mode { START_IMMEDIATELY, START_IN_THREADS } private void basic(Mode mode) throws Exception { final int PARTICIPANT_QTY = 1;//0; List latches = Lists.newArrayList(); Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); for ( int i = 0; i < PARTICIPANT_QTY; ++i ) { LeaderLatch latch = new LeaderLatch(client, PATH_NAME); if ( mode == Mode.START_IMMEDIATELY ) { latch.start(); } latches.add(latch); } if ( mode == Mode.START_IN_THREADS ) { ExecutorService service = Executors.newFixedThreadPool(latches.size()); for ( final LeaderLatch latch : latches ) { service.submit(new Callable() { @Override public Object call() throws Exception { Thread.sleep((int)(100 * Math.random())); latch.start(); return null; } }); } service.shutdown(); } while ( latches.size() > 0 ) { List leaders = waitForALeader(latches, timing); Assert.assertEquals(leaders.size(), 1); // there can only be one leader LeaderLatch theLeader = leaders.get(0); if ( mode == Mode.START_IMMEDIATELY ) { Assert.assertEquals(latches.indexOf(theLeader), 0); // assert ordering - leadership should advance in start order } theLeader.close(); latches.remove(theLeader); } } finally { for ( LeaderLatch latch : latches ) { CloseableUtils.closeQuietly(latch); } CloseableUtils.closeQuietly(client); } } private List waitForALeader(List latches, Timing timing) throws InterruptedException { for ( int i = 0; i < MAX_LOOPS; ++i ) { List leaders = getLeaders(latches); if ( leaders.size() != 0 ) { return leaders; } timing.sleepABit(); } return Lists.newArrayList(); } private List getLeaders(Collection latches) { List leaders = Lists.newArrayList(); for ( LeaderLatch latch : latches ) { if ( latch.hasLeadership() ) { leaders.add(latch); } } return leaders; } @Test(expectedExceptions = IllegalArgumentException.class) public void testRelativePath() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); LeaderLatch latch = new LeaderLatch(client, "parent"); } } TestLeaderLatchCluster.java000066400000000000000000000103441245521677600414230ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.leader; import com.google.common.collect.Lists; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.InstanceSpec; import org.apache.curator.test.TestingCluster; import org.apache.curator.test.Timing; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Collection; import java.util.List; public class TestLeaderLatchCluster { private static final int MAX_LOOPS = 5; private static class ClientAndLatch { final CuratorFramework client; final LeaderLatch latch; final int index; private ClientAndLatch(CuratorFramework client, LeaderLatch latch, int index) { this.client = client; this.latch = latch; this.index = index; } } @Test public void testInCluster() throws Exception { final int PARTICIPANT_QTY = 3; List clients = Lists.newArrayList(); Timing timing = new Timing(); TestingCluster cluster = new TestingCluster(PARTICIPANT_QTY); try { cluster.start(); List instances = Lists.newArrayList(cluster.getInstances()); for ( int i = 0; i < PARTICIPANT_QTY; ++i ) { CuratorFramework client = CuratorFrameworkFactory.newClient(instances.get(i).getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); LeaderLatch latch = new LeaderLatch(client, "/latch"); clients.add(new ClientAndLatch(client, latch, i)); client.start(); latch.start(); } ClientAndLatch leader = waitForALeader(clients, timing); Assert.assertNotNull(leader); cluster.killServer(instances.get(leader.index)); Thread.sleep(timing.multiple(2).session()); leader = waitForALeader(clients, timing); Assert.assertNotNull(leader); Assert.assertEquals(getLeaders(clients).size(), 1); } finally { for ( ClientAndLatch client : clients ) { CloseableUtils.closeQuietly(client.latch); CloseableUtils.closeQuietly(client.client); } CloseableUtils.closeQuietly(cluster); } } private ClientAndLatch waitForALeader(List latches, Timing timing) throws InterruptedException { for ( int i = 0; i < MAX_LOOPS; ++i ) { List leaders = getLeaders(latches); if ( leaders.size() != 0 ) { return leaders.get(0); } timing.sleepABit(); } return null; } private List getLeaders(Collection latches) { List leaders = Lists.newArrayList(); for ( ClientAndLatch clientAndLatch : latches ) { if ( clientAndLatch.latch.hasLeadership() ) { leaders.add(clientAndLatch); } } return leaders; } } TestLeaderSelector.java000066400000000000000000000535701245521677600406160ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.leader; import com.google.common.collect.Lists; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.KillSession; import org.apache.curator.test.TestingServer; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.internal.annotations.Sets; import java.util.List; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.testng.Assert.fail; public class TestLeaderSelector extends BaseClassForTests { private static final String PATH_NAME = "/one/two/me"; @Test public void testInterruptLeadershipWithRequeue() throws Exception { Timing timing = new Timing(); LeaderSelector selector = null; CuratorFramework client = null; try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); final Semaphore semaphore = new Semaphore(0); LeaderSelectorListener listener = new LeaderSelectorListenerAdapter() { @Override public void takeLeadership(CuratorFramework client) throws Exception { semaphore.release(); Thread.currentThread().join(); } }; selector = new LeaderSelector(client, "/leader", listener); selector.autoRequeue(); selector.start(); Assert.assertTrue(timing.acquireSemaphore(semaphore)); selector.interruptLeadership(); Assert.assertTrue(timing.acquireSemaphore(semaphore)); } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } @Test public void testInterruptLeadership() throws Exception { LeaderSelector selector = null; Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); final CountDownLatch isLeaderLatch = new CountDownLatch(1); final CountDownLatch losingLeaderLatch = new CountDownLatch(1); LeaderSelectorListener listener = new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework client) throws Exception { isLeaderLatch.countDown(); try { Thread.currentThread().join(); } finally { losingLeaderLatch.countDown(); } } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; selector = new LeaderSelector(client, "/leader", listener); selector.start(); Assert.assertTrue(timing.awaitLatch(isLeaderLatch)); selector.interruptLeadership(); Assert.assertTrue(timing.awaitLatch(losingLeaderLatch)); } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } @Test public void testRaceAtStateChanged() throws Exception { LeaderSelector selector = null; Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); final CountDownLatch takeLeadershipLatch = new CountDownLatch(1); final CountDownLatch lostLatch = new CountDownLatch(1); final CountDownLatch reconnectedLatch = new CountDownLatch(1); LeaderSelectorListener listener = new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework client) throws Exception { takeLeadershipLatch.countDown(); // should never get here } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState == ConnectionState.RECONNECTED ) { reconnectedLatch.countDown(); } else if ( newState == ConnectionState.LOST ) { lostLatch.countDown(); throw new CancelLeadershipException(); } } }; selector = new LeaderSelector(client, "/leader", listener); CountDownLatch debugLeadershipLatch = new CountDownLatch(1); CountDownLatch debugLeadershipWaitLatch = new CountDownLatch(1); selector.debugLeadershipLatch = debugLeadershipLatch; selector.debugLeadershipWaitLatch = debugLeadershipWaitLatch; selector.start(); Assert.assertTrue(timing.awaitLatch(debugLeadershipLatch)); server.stop(); Assert.assertTrue(timing.awaitLatch(lostLatch)); timing.sleepABit(); debugLeadershipWaitLatch.countDown(); server.restart(); Assert.assertTrue(timing.awaitLatch(reconnectedLatch)); Assert.assertFalse(takeLeadershipLatch.await(3, TimeUnit.SECONDS)); } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } @Test public void testAutoRequeue() throws Exception { Timing timing = new Timing(); LeaderSelector selector = null; CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).sessionTimeoutMs(timing.session()).build(); try { client.start(); final Semaphore semaphore = new Semaphore(0); LeaderSelectorListener listener = new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework client) throws Exception { Thread.sleep(10); semaphore.release(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; selector = new LeaderSelector(client, "/leader", listener); selector.autoRequeue(); selector.start(); Assert.assertTrue(timing.acquireSemaphore(semaphore, 2)); } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } @Test public void testServerDying() throws Exception { Timing timing = new Timing(); LeaderSelector selector = null; CuratorFramework client = CuratorFrameworkFactory.builder().connectionTimeoutMs(timing.connection()).connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).sessionTimeoutMs(timing.session()).build(); client.start(); try { final Semaphore semaphore = new Semaphore(0); LeaderSelectorListener listener = new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework client) throws Exception { semaphore.release(); Thread.sleep(Integer.MAX_VALUE); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState == ConnectionState.LOST ) { semaphore.release(); } } }; selector = new LeaderSelector(client, "/leader", listener); selector.start(); timing.acquireSemaphore(semaphore); server.close(); timing.acquireSemaphore(semaphore); } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } @Test public void testKillSessionThenCloseShouldElectNewLeader() throws Exception { final Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { final Semaphore semaphore = new Semaphore(0); final CountDownLatch interruptedLatch = new CountDownLatch(1); final AtomicInteger leaderCount = new AtomicInteger(0); LeaderSelectorListener listener = new LeaderSelectorListenerAdapter() { @Override public void takeLeadership(CuratorFramework client) throws Exception { leaderCount.incrementAndGet(); try { semaphore.release(); try { Thread.currentThread().join(); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); interruptedLatch.countDown(); } } finally { leaderCount.decrementAndGet(); } } }; LeaderSelector leaderSelector1 = new LeaderSelector(client, PATH_NAME, listener); LeaderSelector leaderSelector2 = new LeaderSelector(client, PATH_NAME, listener); boolean leaderSelector1Closed = false; boolean leaderSelector2Closed = false; leaderSelector1.start(); leaderSelector2.start(); Assert.assertTrue(timing.acquireSemaphore(semaphore, 1)); KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString()); Assert.assertTrue(timing.awaitLatch(interruptedLatch)); timing.sleepABit(); boolean requeued1 = leaderSelector1.requeue(); boolean requeued2 = leaderSelector2.requeue(); Assert.assertTrue(requeued1); Assert.assertTrue(requeued2); Assert.assertTrue(timing.acquireSemaphore(semaphore, 1)); Assert.assertEquals(leaderCount.get(), 1); if ( leaderSelector1.hasLeadership() ) { leaderSelector1.close(); leaderSelector1Closed = true; } else if ( leaderSelector2.hasLeadership() ) { leaderSelector2.close(); leaderSelector2Closed = true; } else { fail("No leaderselector has leadership!"); } // Verify that the other leader took over leadership. Assert.assertTrue(timing.acquireSemaphore(semaphore, 1)); Assert.assertEquals(leaderCount.get(), 1); if ( !leaderSelector1Closed ) { leaderSelector1.close(); } if ( !leaderSelector2Closed ) { leaderSelector2.close(); } } finally { client.close(); } } /** * This is similar to TestLeaderSelector.testKillSessionThenCloseShouldElectNewLeader * The differences are: * it restarts the TestingServer instead of killing the session * it uses autoRequeue instead of explicitly calling requeue */ @Test public void testKillServerThenCloseShouldElectNewLeader() throws Exception { final Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { final Semaphore semaphore = new Semaphore(0); final CountDownLatch interruptedLatch = new CountDownLatch(1); final AtomicInteger leaderCount = new AtomicInteger(0); LeaderSelectorListener listener = new LeaderSelectorListenerAdapter() { @Override public void takeLeadership(CuratorFramework client) throws Exception { leaderCount.incrementAndGet(); try { semaphore.release(); try { Thread.currentThread().join(); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); interruptedLatch.countDown(); } } finally { leaderCount.decrementAndGet(); } } }; LeaderSelector leaderSelector1 = new LeaderSelector(client, PATH_NAME, listener); LeaderSelector leaderSelector2 = new LeaderSelector(client, PATH_NAME, listener); boolean leaderSelector1Closed = false; boolean leaderSelector2Closed = false; leaderSelector1.autoRequeue(); leaderSelector2.autoRequeue(); leaderSelector1.start(); leaderSelector2.start(); Assert.assertTrue(timing.acquireSemaphore(semaphore, 1)); int port = server.getPort(); server.stop(); timing.sleepABit(); server = new TestingServer(port); Assert.assertTrue(timing.awaitLatch(interruptedLatch)); timing.sleepABit(); Assert.assertTrue(timing.acquireSemaphore(semaphore, 1)); Assert.assertEquals(leaderCount.get(), 1); if ( leaderSelector1.hasLeadership() ) { leaderSelector1.close(); leaderSelector1Closed = true; } else if ( leaderSelector2.hasLeadership() ) { leaderSelector2.close(); leaderSelector2Closed = true; } else { fail("No leaderselector has leadership!"); } // Verify that the other leader took over leadership. Assert.assertTrue(timing.acquireSemaphore(semaphore, 1)); Assert.assertEquals(leaderCount.get(), 1); if ( !leaderSelector1Closed ) { leaderSelector1.close(); } if ( !leaderSelector2Closed ) { leaderSelector2.close(); } } finally { client.close(); } } @Test public void testClosing() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { final CountDownLatch latch = new CountDownLatch(1); LeaderSelector leaderSelector1 = new LeaderSelector(client, PATH_NAME, new LeaderSelectorListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } @Override public void takeLeadership(CuratorFramework client) throws Exception { latch.await(10, TimeUnit.SECONDS); } }); LeaderSelector leaderSelector2 = new LeaderSelector(client, PATH_NAME, new LeaderSelectorListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } @Override public void takeLeadership(CuratorFramework client) throws Exception { latch.await(10, TimeUnit.SECONDS); } }); leaderSelector1.start(); leaderSelector2.start(); while ( !leaderSelector1.hasLeadership() && !leaderSelector2.hasLeadership() ) { Thread.sleep(1000); } Assert.assertNotSame(leaderSelector1.hasLeadership(), leaderSelector2.hasLeadership()); LeaderSelector positiveLeader; LeaderSelector negativeLeader; if ( leaderSelector1.hasLeadership() ) { positiveLeader = leaderSelector1; negativeLeader = leaderSelector2; } else { positiveLeader = leaderSelector2; negativeLeader = leaderSelector1; } negativeLeader.close(); Thread.sleep(1000); Assert.assertNotSame(positiveLeader.hasLeadership(), negativeLeader.hasLeadership()); Assert.assertTrue(positiveLeader.hasLeadership()); positiveLeader.close(); Thread.sleep(1000); Assert.assertFalse(positiveLeader.hasLeadership()); } finally { client.close(); } } @SuppressWarnings({"ForLoopReplaceableByForEach"}) @Test public void testRotatingLeadership() throws Exception { final int LEADER_QTY = 5; final int REPEAT_QTY = 3; final Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { final BlockingQueue leaderList = new LinkedBlockingQueue(); List selectors = Lists.newArrayList(); for ( int i = 0; i < LEADER_QTY; ++i ) { final int ourIndex = i; LeaderSelector leaderSelector = new LeaderSelector(client, PATH_NAME, new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework client) throws Exception { timing.sleepABit(); leaderList.add(ourIndex); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }); selectors.add(leaderSelector); } List localLeaderList = Lists.newArrayList(); for ( int i = 1; i <= REPEAT_QTY; ++i ) { for ( LeaderSelector leaderSelector : selectors ) { if ( i > 1 ) { leaderSelector.requeue(); } else { leaderSelector.start(); } } while ( localLeaderList.size() != (i * selectors.size()) ) { Integer polledIndex = leaderList.poll(10, TimeUnit.SECONDS); Assert.assertNotNull(polledIndex); localLeaderList.add(polledIndex); } timing.sleepABit(); } for ( LeaderSelector leaderSelector : selectors ) { leaderSelector.close(); } System.out.println(localLeaderList); for ( int i = 0; i < REPEAT_QTY; ++i ) { Set uniques = Sets.newHashSet(); for ( int j = 0; j < selectors.size(); ++j ) { Assert.assertTrue(localLeaderList.size() > 0); int thisIndex = localLeaderList.remove(0); Assert.assertFalse(uniques.contains(thisIndex)); uniques.add(thisIndex); } } } finally { client.close(); } } } TestLeaderSelectorCluster.java000066400000000000000000000162231245521677600421520ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.leader; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.InstanceSpec; import org.apache.curator.test.TestingCluster; import org.apache.curator.test.Timing; import org.apache.curator.utils.ZKPaths; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Collection; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; @SuppressWarnings("ThrowableResultOfMethodCallIgnored") public class TestLeaderSelectorCluster { @Test public void testRestart() throws Exception { final Timing timing = new Timing(); CuratorFramework client = null; TestingCluster cluster = new TestingCluster(3); cluster.start(); try { client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); final Semaphore semaphore = new Semaphore(0); LeaderSelectorListener listener = new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework client) throws Exception { List names = client.getChildren().forPath("/leader"); Assert.assertTrue(names.size() > 0); semaphore.release(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; LeaderSelector selector = new LeaderSelector(client, "/leader", listener); selector.autoRequeue(); selector.start(); Assert.assertTrue(timing.acquireSemaphore(semaphore)); InstanceSpec connectionInstance = cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper()); cluster.killServer(connectionInstance); Assert.assertTrue(timing.multiple(4).acquireSemaphore(semaphore)); } finally { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(cluster); } } @Test public void testLostRestart() throws Exception { final Timing timing = new Timing(); CuratorFramework client = null; TestingCluster cluster = new TestingCluster(3); cluster.start(); try { client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); client.sync().forPath("/"); final AtomicReference error = new AtomicReference(null); final AtomicReference lockNode = new AtomicReference(null); final Semaphore semaphore = new Semaphore(0); final CountDownLatch lostLatch = new CountDownLatch(1); final CountDownLatch internalLostLatch = new CountDownLatch(1); LeaderSelectorListener listener = new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework client) throws Exception { try { List names = client.getChildren().forPath("/leader"); if ( names.size() != 1 ) { semaphore.release(); Exception exception = new Exception("Names size isn't 1: " + names.size()); error.set(exception); return; } lockNode.set(names.get(0)); semaphore.release(); if ( !timing.multiple(4).awaitLatch(internalLostLatch) ) { error.set(new Exception("internalLostLatch await failed")); } } finally { lostLatch.countDown(); } } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState == ConnectionState.LOST ) { internalLostLatch.countDown(); } } }; LeaderSelector selector = new LeaderSelector(client, "/leader", listener); selector.start(); Assert.assertTrue(timing.multiple(4).acquireSemaphore(semaphore)); if ( error.get() != null ) { throw new AssertionError(error.get()); } Collection instances = cluster.getInstances(); cluster.stop(); Assert.assertTrue(timing.multiple(4).awaitLatch(lostLatch)); timing.sleepABit(); Assert.assertFalse(selector.hasLeadership()); Assert.assertNotNull(lockNode.get()); cluster = new TestingCluster(instances.toArray(new InstanceSpec[instances.size()])); cluster.start(); try { client.delete().forPath(ZKPaths.makePath("/leader", lockNode.get())); // simulate the lock deleting due to session expiration } catch ( Exception ignore ) { // ignore } Assert.assertTrue(semaphore.availablePermits() == 0); Assert.assertFalse(selector.hasLeadership()); selector.requeue(); Assert.assertTrue(timing.multiple(4).acquireSemaphore(semaphore)); } finally { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(cluster); } } } TestLeaderSelectorEdges.java000066400000000000000000000227401245521677600415610ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.leader; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.retry.RetryNTimes; import org.apache.curator.test.BaseClassForTests; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.server.ServerCnxnFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * Test cases designed after CURATOR-45 */ public class TestLeaderSelectorEdges extends BaseClassForTests { private final Logger log = LoggerFactory.getLogger(getClass()); @BeforeClass public static void setCNXFactory() { System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, ChaosMonkeyCnxnFactory.class.getName()); } @AfterClass public static void resetCNXFactory() { System.clearProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY); } /** * Create a LeaderSelector but close the connection right after the "lock" znode * has been created. * * @throws Exception */ @Test public void flappingTest() throws Exception { final CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(server.getConnectString()) .retryPolicy(new RetryNTimes(1, 500)) .sessionTimeoutMs(30000) .build(); final TestLeaderSelectorListener listener = new TestLeaderSelectorListener(); LeaderSelector leaderSelector1 = new LeaderSelector(client, ChaosMonkeyCnxnFactory.CHAOS_ZNODE, listener); LeaderSelector leaderSelector2 = null; client.start(); try { client.create().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE); leaderSelector1.start(); // At this point the ChaosMonkeyZookeeperServer must close the connection // right after the lock znode is created. Assert.assertTrue(listener.reconnected.await(10, TimeUnit.SECONDS), "Connection has not been lost"); // Check that leader ship has failed Assert.assertEquals(listener.takeLeadership.getCount(), 1); // Wait FailedDelete Thread.sleep(ChaosMonkeyCnxnFactory.LOCKOUT_DURATION_MS * 2); // Check that there is no znode final int children = client.getChildren().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE).size(); Assert.assertEquals(children, 0, "Still " + children + " znodes under " + ChaosMonkeyCnxnFactory.CHAOS_ZNODE + " lock"); // Check that a new LeaderSelector can be started leaderSelector2 = new LeaderSelector(client, ChaosMonkeyCnxnFactory.CHAOS_ZNODE, listener); leaderSelector2.start(); Assert.assertTrue(listener.takeLeadership.await(1, TimeUnit.SECONDS)); } finally { try { leaderSelector1.close(); } catch ( IllegalStateException e ) { Assert.fail(e.getMessage()); } try { if ( leaderSelector2 != null ) { leaderSelector2.close(); } } catch ( IllegalStateException e ) { Assert.fail(e.getMessage()); } client.close(); } } private class TestLeaderSelectorListener implements LeaderSelectorListener { final CountDownLatch takeLeadership = new CountDownLatch(1); final CountDownLatch reconnected = new CountDownLatch(1); @Override public void takeLeadership(CuratorFramework client) throws Exception { log.info("-->takeLeadership({})", client.toString()); takeLeadership.countDown(); log.info("<--takeLeadership({})", client.toString()); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState == ConnectionState.RECONNECTED ) { reconnected.countDown(); } } } /** * Create a protected node in background with a retry policy */ @Test public void createProtectedNodeInBackgroundTest() throws Exception { final CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(server.getConnectString()) .retryPolicy(new RetryNTimes(2, 1)) .connectionTimeoutMs(100) .sessionTimeoutMs(60000) .build(); final CountDownLatch latch = new CountDownLatch(1); client.start(); try { client.create().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE); client.create() .withProtection() .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) .inBackground( new BackgroundCallback() { public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { log.info("Receive event {}", event.toString()); if ( event.getResultCode() == KeeperException.Code.CONNECTIONLOSS.intValue() ) { latch.countDown(); } } } ) .forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE_PREFIX + "foo-"); Assert.assertTrue(latch.await(30, TimeUnit.SECONDS), "Callback has not been called"); // Wait for the znode to be deleted Thread.sleep(ChaosMonkeyCnxnFactory.LOCKOUT_DURATION_MS * 2); // Check that there is no znode final int children = client.getChildren().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE).size(); Assert.assertEquals(children, 0, "Still " + children + " znodes under " + ChaosMonkeyCnxnFactory.CHAOS_ZNODE + " lock"); } finally { client.close(); } } /** * Same test as above but without a retry policy */ @Test public void createProtectedNodeInBackgroundTestNoRetry() throws Exception { final CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(server.getConnectString()) .retryPolicy(new RetryNTimes(0, 0)) .connectionTimeoutMs(100) .sessionTimeoutMs(60000) .build(); final CountDownLatch latch = new CountDownLatch(1); client.start(); try { client.create().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE); client.create() .withProtection() .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) .inBackground( new BackgroundCallback() { public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { log.info("Receive event {}", event.toString()); if ( event.getResultCode() == KeeperException.Code.CONNECTIONLOSS.intValue() ) { latch.countDown(); } } } ) .forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE_PREFIX + "foo-"); Assert.assertTrue(latch.await(30, TimeUnit.SECONDS), "Callback has not been called"); // Wait for the znode to be deleted Thread.sleep(ChaosMonkeyCnxnFactory.LOCKOUT_DURATION_MS * 2); // Check that there is no znode final int children = client.getChildren().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE).size(); Assert.assertEquals(children, 0, "Still " + children + " znodes under " + ChaosMonkeyCnxnFactory.CHAOS_ZNODE + " lock"); } finally { client.close(); } } } TestLeaderSelectorParticipants.java000066400000000000000000000144141245521677600431720ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.leader; import com.google.common.collect.Lists; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.retry.RetryOneTime; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.internal.annotations.Sets; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class TestLeaderSelectorParticipants extends BaseClassForTests { @Test public void testId() throws Exception { LeaderSelector selector = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); final CountDownLatch latch = new CountDownLatch(1); LeaderSelectorListener listener = new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework client) throws Exception { latch.countDown(); Thread.currentThread().join(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; selector = new LeaderSelector(client, "/ls", listener); selector.setId("A is A"); selector.start(); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); Participant leader = selector.getLeader(); Assert.assertTrue(leader.isLeader()); Assert.assertEquals(leader.getId(), "A is A"); Collection participants = selector.getParticipants(); Assert.assertEquals(participants.size(), 1); Assert.assertEquals(participants.iterator().next().getId(), "A is A"); Assert.assertEquals(participants.iterator().next().getId(), selector.getId()); } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } @Test public void testBasic() throws Exception { final int SELECTOR_QTY = 10; List selectors = Lists.newArrayList(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); final CountDownLatch leaderLatch = new CountDownLatch(1); final CountDownLatch workingLatch = new CountDownLatch(SELECTOR_QTY); LeaderSelectorListener listener = new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework client) throws Exception { leaderLatch.countDown(); Thread.currentThread().join(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; for ( int i = 0; i < SELECTOR_QTY; ++i ) { LeaderSelector selector = new LeaderSelector(client, "/ls", listener) { @Override void doWork() throws Exception { workingLatch.countDown(); super.doWork(); } }; selector.setId(Integer.toString(i)); selectors.add(selector); } for ( LeaderSelector selector : selectors ) { selector.start(); } Assert.assertTrue(leaderLatch.await(10, TimeUnit.SECONDS)); Assert.assertTrue(workingLatch.await(10, TimeUnit.SECONDS)); Thread.sleep(1000); // some time for locks to acquire Collection participants = selectors.get(0).getParticipants(); for ( int i = 1; i < selectors.size(); ++i ) { Assert.assertEquals(participants, selectors.get(i).getParticipants()); } Set ids = Sets.newHashSet(); int leaderCount = 0; for ( Participant participant : participants ) { if ( participant.isLeader() ) { ++leaderCount; } Assert.assertFalse(ids.contains(participant.getId())); ids.add(participant.getId()); } Assert.assertEquals(leaderCount, 1); Set expectedIds = Sets.newHashSet(); for ( int i = 0; i < SELECTOR_QTY; ++i ) { expectedIds.add(Integer.toString(i)); } Assert.assertEquals(expectedIds, ids); } finally { for ( LeaderSelector selector : selectors ) { CloseableUtils.closeQuietly(selector); } CloseableUtils.closeQuietly(client); } } } TestLeaderSelectorWithExecutor.java000066400000000000000000000077751245521677600431770ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.leader; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.test.Timing; import org.apache.curator.utils.ThreadUtils; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; public class TestLeaderSelectorWithExecutor extends BaseClassForTests { private static final ThreadFactory threadFactory = ThreadUtils.newThreadFactory("FeedGenerator"); @Test public void test() throws Exception { Timing timing = new Timing(); LeaderSelector leaderSelector = null; CuratorFramework client = CuratorFrameworkFactory.builder() .retryPolicy(new ExponentialBackoffRetry(100, 3)) .connectString(server.getConnectString()) .sessionTimeoutMs(timing.session()) .connectionTimeoutMs(timing.connection()) .build(); try { client.start(); MyLeaderSelectorListener listener = new MyLeaderSelectorListener(); ExecutorService executorPool = Executors.newFixedThreadPool(20); leaderSelector = new LeaderSelector(client, "/test", threadFactory, executorPool, listener); leaderSelector.autoRequeue(); leaderSelector.start(); timing.sleepABit(); Assert.assertEquals(listener.getLeaderCount(), 1); } finally { CloseableUtils.closeQuietly(leaderSelector); CloseableUtils.closeQuietly(client); } } private class MyLeaderSelectorListener implements LeaderSelectorListener { private volatile Thread ourThread; private final AtomicInteger leaderCount = new AtomicInteger(0); public int getLeaderCount() { return leaderCount.get(); } @Override public void takeLeadership(CuratorFramework curatorFramework) throws Exception { ourThread = Thread.currentThread(); try { leaderCount.incrementAndGet(); while ( !Thread.currentThread().isInterrupted() ) { Thread.sleep(1000); } } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } finally { leaderCount.decrementAndGet(); } } @Override public void stateChanged(CuratorFramework curatorFramework, ConnectionState newState) { if ( (newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED) ) { if ( ourThread != null ) { ourThread.interrupt(); } } } } } 000077500000000000000000000000001245521677600340635ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locksCounter.java000066400000000000000000000016501245521677600363470ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; class Counter { int currentCount = 0; int maxCount = 0; } SemaphoreClient.java000066400000000000000000000110331245521677600400060ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.test.Timing; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicReference; class SemaphoreClient implements Callable, ConnectionStateListener, Closeable { private final CuratorFramework client; private final String semaphorePath; private final Callable operation; private volatile boolean shouldRun; private volatile boolean hasAcquired; private static final int CLIENT_EXCEPTION_HANDLER_SLEEP_TIME_SECS = 10; private static final int MAX_SEMAPHORE_LEASES = 1; private static final AtomicReference activeClient = new AtomicReference(null); SemaphoreClient(String connectionString, String semaphorePath, Callable operation) throws IOException { Timing timing = new Timing(); this.client = CuratorFrameworkFactory.newClient(connectionString, timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); client.start(); this.semaphorePath = semaphorePath; this.operation = operation; } @Override public void close() throws IOException { shouldRun = false; } boolean hasAcquired() { return hasAcquired; } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { hasAcquired = false; } static SemaphoreClient getActiveClient() { return activeClient.get(); } @Override public Void call() throws Exception { shouldRun = true; client.getConnectionStateListenable().addListener(this); try { while ( shouldRun ) { try { acquireAndRun(); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); // propagate up, don't sleep throw e; } catch ( Exception e ) { Thread.sleep(CLIENT_EXCEPTION_HANDLER_SLEEP_TIME_SECS * 1000L); } } } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } finally { CloseableUtils.closeQuietly(client); } return null; } private void acquireAndRun() throws Exception { InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, semaphorePath, MAX_SEMAPHORE_LEASES); Lease lease = semaphore.acquire(); try { hasAcquired = true; if ( activeClient.compareAndSet(null, this) ) { throw new Exception("Multiple acquirers"); } try { while ( hasAcquired && shouldRun ) { operation.call(); } } finally { if ( activeClient.compareAndSet(this, null) ) { //noinspection ThrowFromFinallyBlock throw new Exception("Bad release"); } } } finally { semaphore.returnLease(lease); } } } Stepper.java000066400000000000000000000022771245521677600363600ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; class Stepper { private int available = 0; synchronized void await() throws InterruptedException { while ( available == 0 ) { wait(); } --available; notifyAll(); } synchronized void countDown(int qty) { available += qty; notifyAll(); } } TestChildReaper.java000066400000000000000000000145011245521677600377510ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.Timing; import org.apache.zookeeper.data.Stat; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Random; public class TestChildReaper extends BaseClassForTests { @Test public void testSomeNodes() throws Exception { Timing timing = new Timing(); ChildReaper reaper = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); Random r = new Random(); int nonEmptyNodes = 0; for ( int i = 0; i < 10; ++i ) { client.create().creatingParentsIfNeeded().forPath("/test/" + Integer.toString(i)); if ( r.nextBoolean() ) { client.create().forPath("/test/" + Integer.toString(i) + "/foo"); ++nonEmptyNodes; } } reaper = new ChildReaper(client, "/test", Reaper.Mode.REAP_UNTIL_DELETE, 1); reaper.start(); timing.forWaiting().sleepABit(); Stat stat = client.checkExists().forPath("/test"); Assert.assertEquals(stat.getNumChildren(), nonEmptyNodes); } finally { CloseableUtils.closeQuietly(reaper); CloseableUtils.closeQuietly(client); } } @Test public void testSimple() throws Exception { Timing timing = new Timing(); ChildReaper reaper = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); for ( int i = 0; i < 10; ++i ) { client.create().creatingParentsIfNeeded().forPath("/test/" + Integer.toString(i)); } reaper = new ChildReaper(client, "/test", Reaper.Mode.REAP_UNTIL_DELETE, 1); reaper.start(); timing.forWaiting().sleepABit(); Stat stat = client.checkExists().forPath("/test"); Assert.assertEquals(stat.getNumChildren(), 0); } finally { CloseableUtils.closeQuietly(reaper); CloseableUtils.closeQuietly(client); } } @Test public void testMultiPath() throws Exception { Timing timing = new Timing(); ChildReaper reaper = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); for ( int i = 0; i < 10; ++i ) { client.create().creatingParentsIfNeeded().forPath("/test1/" + Integer.toString(i)); client.create().creatingParentsIfNeeded().forPath("/test2/" + Integer.toString(i)); client.create().creatingParentsIfNeeded().forPath("/test3/" + Integer.toString(i)); } reaper = new ChildReaper(client, "/test2", Reaper.Mode.REAP_UNTIL_DELETE, 1); reaper.start(); reaper.addPath("/test1"); timing.forWaiting().sleepABit(); Stat stat = client.checkExists().forPath("/test1"); Assert.assertEquals(stat.getNumChildren(), 0); stat = client.checkExists().forPath("/test2"); Assert.assertEquals(stat.getNumChildren(), 0); stat = client.checkExists().forPath("/test3"); Assert.assertEquals(stat.getNumChildren(), 10); } finally { CloseableUtils.closeQuietly(reaper); CloseableUtils.closeQuietly(client); } } @Test public void testNamespace() throws Exception { Timing timing = new Timing(); ChildReaper reaper = null; CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(server.getConnectString()) .sessionTimeoutMs(timing.session()) .connectionTimeoutMs(timing.connection()) .retryPolicy(new RetryOneTime(1)) .namespace("foo") .build(); try { client.start(); for ( int i = 0; i < 10; ++i ) { client.create().creatingParentsIfNeeded().forPath("/test/" + Integer.toString(i)); } reaper = new ChildReaper(client, "/test", Reaper.Mode.REAP_UNTIL_DELETE, 1); reaper.start(); timing.forWaiting().sleepABit(); Stat stat = client.checkExists().forPath("/test"); Assert.assertEquals(stat.getNumChildren(), 0); stat = client.usingNamespace(null).checkExists().forPath("/foo/test"); Assert.assertNotNull(stat); Assert.assertEquals(stat.getNumChildren(), 0); } finally { CloseableUtils.closeQuietly(reaper); CloseableUtils.closeQuietly(client); } } } TestInterProcessMultiMutex.java000066400000000000000000000121651245521677600422510ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.testng.Assert; import org.testng.annotations.Test; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; public class TestInterProcessMultiMutex extends TestInterProcessMutexBase { private static final String LOCK_PATH_1 = "/locks/our-lock-1"; private static final String LOCK_PATH_2 = "/locks/our-lock-2"; @Override protected InterProcessLock makeLock(CuratorFramework client) { return new InterProcessMultiLock(client, Arrays.asList(LOCK_PATH_1, LOCK_PATH_2)); } @Test public void testSomeReleasesFail() throws IOException { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { InterProcessLock goodLock = new InterProcessMutex(client, LOCK_PATH_1); final InterProcessLock otherGoodLock = new InterProcessMutex(client, LOCK_PATH_2); InterProcessLock badLock = new InterProcessLock() { @Override public void acquire() throws Exception { otherGoodLock.acquire(); } @Override public boolean acquire(long time, TimeUnit unit) throws Exception { return otherGoodLock.acquire(time, unit); } @Override public void release() throws Exception { throw new Exception("foo"); } @Override public boolean isAcquiredInThisProcess() { return otherGoodLock.isAcquiredInThisProcess(); } }; InterProcessMultiLock lock = new InterProcessMultiLock(Arrays.asList(goodLock, badLock)); try { lock.acquire(); lock.release(); Assert.fail(); } catch ( Exception e ) { } Assert.assertFalse(goodLock.isAcquiredInThisProcess()); Assert.assertTrue(otherGoodLock.isAcquiredInThisProcess()); } finally { client.close(); } } @Test public void testSomeLocksFailToLock() throws IOException { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { final AtomicBoolean goodLockWasLocked = new AtomicBoolean(false); final InterProcessLock goodLock = new InterProcessMutex(client, LOCK_PATH_1); InterProcessLock badLock = new InterProcessLock() { @Override public void acquire() throws Exception { if ( goodLock.isAcquiredInThisProcess() ) { goodLockWasLocked.set(true); } throw new Exception("foo"); } @Override public boolean acquire(long time, TimeUnit unit) throws Exception { throw new Exception("foo"); } @Override public void release() throws Exception { throw new Exception("foo"); } @Override public boolean isAcquiredInThisProcess() { return false; } }; InterProcessMultiLock lock = new InterProcessMultiLock(Arrays.asList(goodLock, badLock)); try { lock.acquire(); Assert.fail(); } catch ( Exception e ) { } Assert.assertFalse(goodLock.isAcquiredInThisProcess()); Assert.assertTrue(goodLockWasLocked.get()); } finally { client.close(); } } } TestInterProcessMutex.java000066400000000000000000000137221245521677600412360ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.KillSession; import org.apache.zookeeper.CreateMode; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Collection; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class TestInterProcessMutex extends TestInterProcessMutexBase { private static final String LOCK_PATH = "/locks/our-lock"; @Override protected InterProcessLock makeLock(CuratorFramework client) { return new InterProcessMutex(client, LOCK_PATH); } @Test public void testRevoking() throws Exception { final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); final InterProcessMutex lock = new InterProcessMutex(client, LOCK_PATH); ExecutorService executorService = Executors.newCachedThreadPool(); final CountDownLatch revokeLatch = new CountDownLatch(1); final CountDownLatch lockLatch = new CountDownLatch(1); Future f1 = executorService.submit ( new Callable() { @Override public Void call() throws Exception { RevocationListener listener = new RevocationListener() { @Override public void revocationRequested(InterProcessMutex lock) { revokeLatch.countDown(); } }; lock.makeRevocable(listener); lock.acquire(); lockLatch.countDown(); revokeLatch.await(); lock.release(); return null; } } ); Future f2 = executorService.submit ( new Callable() { @Override public Void call() throws Exception { Assert.assertTrue(lockLatch.await(10, TimeUnit.SECONDS)); Collection nodes = lock.getParticipantNodes(); Assert.assertEquals(nodes.size(), 1); Revoker.attemptRevoke(client, nodes.iterator().next()); InterProcessMutex l2 = new InterProcessMutex(client, LOCK_PATH); Assert.assertTrue(l2.acquire(5, TimeUnit.SECONDS)); l2.release(); return null; } } ); f2.get(); f1.get(); } finally { client.close(); } } @Test public void testPersistentLock() throws Exception { final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { final InterProcessMutex lock = new InterProcessMutex(client, LOCK_PATH, new StandardLockInternalsDriver() { @Override public String createsTheLock(CuratorFramework client, String path, byte[] lockNodeBytes) throws Exception { String ourPath; if ( lockNodeBytes != null ) { ourPath = client.create().creatingParentsIfNeeded().withProtection().withMode(CreateMode.PERSISTENT).forPath(path, lockNodeBytes); } else { ourPath = client.create().creatingParentsIfNeeded().withProtection().withMode(CreateMode.PERSISTENT).forPath(path); } return ourPath; } }); // Get a persistent lock lock.acquire(10, TimeUnit.SECONDS); Assert.assertTrue(lock.isAcquiredInThisProcess()); // Kill the session, check that lock node still exists KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString()); Assert.assertNotNull(client.checkExists().forPath(LOCK_PATH)); // Release the lock and verify that the actual lock node created no longer exists String actualLockPath = lock.getLockPath(); lock.release(); Assert.assertNull(client.checkExists().forPath(actualLockPath)); } finally { client.close(); } } } TestInterProcessMutexBase.java000066400000000000000000000422271245521677600420330ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import com.google.common.collect.Lists; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.KillSession; import org.apache.curator.test.TestingServer; import org.apache.curator.test.Timing; import org.testng.Assert; import org.testng.annotations.Test; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; public abstract class TestInterProcessMutexBase extends BaseClassForTests { private volatile CountDownLatch waitLatchForBar = null; private volatile CountDownLatch countLatchForBar = null; protected abstract InterProcessLock makeLock(CuratorFramework client); @Test public void testWaitingProcessKilledServer() throws Exception { final Timing timing = new Timing(); final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); try { client.start(); final CountDownLatch latch = new CountDownLatch(1); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState == ConnectionState.LOST ) { latch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); final AtomicBoolean isFirst = new AtomicBoolean(true); ExecutorCompletionService service = new ExecutorCompletionService(Executors.newFixedThreadPool(2)); for ( int i = 0; i < 2; ++i ) { service.submit ( new Callable() { @Override public Object call() throws Exception { InterProcessLock lock = makeLock(client); lock.acquire(); try { if ( isFirst.compareAndSet(true, false) ) { timing.sleepABit(); server.stop(); Assert.assertTrue(timing.awaitLatch(latch)); server.restart(); } } finally { try { lock.release(); } catch ( Exception e ) { // ignore } } return null; } } ); } for ( int i = 0; i < 2; ++i ) { service.take().get(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS); } } finally { CloseableUtils.closeQuietly(client); } } @Test public void testKilledSession() throws Exception { final Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); client.start(); try { final InterProcessLock mutex1 = makeLock(client); final InterProcessLock mutex2 = makeLock(client); final Semaphore semaphore = new Semaphore(0); ExecutorCompletionService service = new ExecutorCompletionService(Executors.newFixedThreadPool(2)); service.submit ( new Callable() { @Override public Object call() throws Exception { mutex1.acquire(); semaphore.release(); Thread.sleep(1000000); return null; } } ); service.submit ( new Callable() { @Override public Object call() throws Exception { mutex2.acquire(); semaphore.release(); Thread.sleep(1000000); return null; } } ); Assert.assertTrue(timing.acquireSemaphore(semaphore, 1)); KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString()); Assert.assertTrue(timing.acquireSemaphore(semaphore, 1)); } finally { client.close(); } } @Test public void testWithNamespace() throws Exception { CuratorFramework client = CuratorFrameworkFactory.builder(). connectString(server.getConnectString()). retryPolicy(new ExponentialBackoffRetry(100, 3)). namespace("test"). build(); client.start(); try { InterProcessLock mutex = makeLock(client); mutex.acquire(10, TimeUnit.SECONDS); Thread.sleep(100); mutex.release(); } finally { client.close(); } } @Test public void testReentrantSingleLock() throws Exception { final int THREAD_QTY = 10; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(100, 3)); client.start(); try { final AtomicBoolean hasLock = new AtomicBoolean(false); final AtomicBoolean isFirst = new AtomicBoolean(true); final Semaphore semaphore = new Semaphore(1); final InterProcessLock mutex = makeLock(client); List> threads = Lists.newArrayList(); ExecutorService service = Executors.newCachedThreadPool(); for ( int i = 0; i < THREAD_QTY; ++i ) { Future t = service.submit ( new Callable() { @Override public Object call() throws Exception { semaphore.acquire(); mutex.acquire(); Assert.assertTrue(hasLock.compareAndSet(false, true)); try { if ( isFirst.compareAndSet(true, false) ) { semaphore.release(THREAD_QTY - 1); while ( semaphore.availablePermits() > 0 ) { Thread.sleep(100); } } else { Thread.sleep(100); } } finally { mutex.release(); hasLock.set(false); } return null; } } ); threads.add(t); } for ( Future t : threads ) { t.get(); } } finally { client.close(); } } @Test public void testReentrant2Threads() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(100, 3)); client.start(); try { waitLatchForBar = new CountDownLatch(1); countLatchForBar = new CountDownLatch(1); final InterProcessLock mutex = makeLock(client); Executors.newSingleThreadExecutor().submit ( new Callable() { @Override public Object call() throws Exception { Assert.assertTrue(countLatchForBar.await(10, TimeUnit.SECONDS)); try { mutex.acquire(10, TimeUnit.SECONDS); Assert.fail(); } catch ( Exception e ) { // correct } finally { waitLatchForBar.countDown(); } return null; } } ); foo(mutex); Assert.assertFalse(mutex.isAcquiredInThisProcess()); } finally { client.close(); } } @Test public void testReentrant() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(100, 3)); client.start(); try { InterProcessLock mutex = makeLock(client); foo(mutex); Assert.assertFalse(mutex.isAcquiredInThisProcess()); } finally { client.close(); } } private void foo(InterProcessLock mutex) throws Exception { mutex.acquire(10, TimeUnit.SECONDS); Assert.assertTrue(mutex.isAcquiredInThisProcess()); bar(mutex); Assert.assertTrue(mutex.isAcquiredInThisProcess()); mutex.release(); } private void bar(InterProcessLock mutex) throws Exception { mutex.acquire(10, TimeUnit.SECONDS); Assert.assertTrue(mutex.isAcquiredInThisProcess()); if ( countLatchForBar != null ) { countLatchForBar.countDown(); waitLatchForBar.await(10, TimeUnit.SECONDS); } snafu(mutex); Assert.assertTrue(mutex.isAcquiredInThisProcess()); mutex.release(); } private void snafu(InterProcessLock mutex) throws Exception { mutex.acquire(10, TimeUnit.SECONDS); Assert.assertTrue(mutex.isAcquiredInThisProcess()); mutex.release(); Assert.assertTrue(mutex.isAcquiredInThisProcess()); } @Test public void test2Clients() throws Exception { CuratorFramework client1 = null; CuratorFramework client2 = null; try { client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(100, 3)); client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(100, 3)); client1.start(); client2.start(); final InterProcessLock mutexForClient1 = makeLock(client1); final InterProcessLock mutexForClient2 = makeLock(client2); final CountDownLatch latchForClient1 = new CountDownLatch(1); final CountDownLatch latchForClient2 = new CountDownLatch(1); final CountDownLatch acquiredLatchForClient1 = new CountDownLatch(1); final CountDownLatch acquiredLatchForClient2 = new CountDownLatch(1); final AtomicReference exceptionRef = new AtomicReference(); ExecutorService service = Executors.newCachedThreadPool(); Future future1 = service.submit ( new Callable() { @Override public Object call() throws Exception { try { mutexForClient1.acquire(10, TimeUnit.SECONDS); acquiredLatchForClient1.countDown(); latchForClient1.await(10, TimeUnit.SECONDS); mutexForClient1.release(); } catch ( Exception e ) { exceptionRef.set(e); } return null; } } ); Future future2 = service.submit ( new Callable() { @Override public Object call() throws Exception { try { mutexForClient2.acquire(10, TimeUnit.SECONDS); acquiredLatchForClient2.countDown(); latchForClient2.await(10, TimeUnit.SECONDS); mutexForClient2.release(); } catch ( Exception e ) { exceptionRef.set(e); } return null; } } ); while ( !mutexForClient1.isAcquiredInThisProcess() && !mutexForClient2.isAcquiredInThisProcess() ) { Thread.sleep(1000); Assert.assertFalse(future1.isDone() && future2.isDone()); } Assert.assertTrue(mutexForClient1.isAcquiredInThisProcess() != mutexForClient2.isAcquiredInThisProcess()); Thread.sleep(1000); Assert.assertTrue(mutexForClient1.isAcquiredInThisProcess() || mutexForClient2.isAcquiredInThisProcess()); Assert.assertTrue(mutexForClient1.isAcquiredInThisProcess() != mutexForClient2.isAcquiredInThisProcess()); Exception exception = exceptionRef.get(); if ( exception != null ) { throw exception; } if ( mutexForClient1.isAcquiredInThisProcess() ) { latchForClient1.countDown(); Assert.assertTrue(acquiredLatchForClient2.await(10, TimeUnit.SECONDS)); Assert.assertTrue(mutexForClient2.isAcquiredInThisProcess()); } else { latchForClient2.countDown(); Assert.assertTrue(acquiredLatchForClient1.await(10, TimeUnit.SECONDS)); Assert.assertTrue(mutexForClient1.isAcquiredInThisProcess()); } } finally { CloseableUtils.closeQuietly(client1); CloseableUtils.closeQuietly(client2); } } } TestInterProcessReadWriteLock.java000066400000000000000000000266361245521677600426430ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import com.google.common.collect.Lists; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Collection; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class TestInterProcessReadWriteLock extends BaseClassForTests { @Test public void testGetParticipantNodes() throws Exception { final int READERS = 20; final int WRITERS = 8; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); final CountDownLatch latch = new CountDownLatch(READERS + WRITERS); final CountDownLatch readLatch = new CountDownLatch(READERS); final InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock"); ExecutorService service = Executors.newCachedThreadPool(); for ( int i = 0; i < READERS; ++i ) { service.submit ( new Callable() { @Override public Void call() throws Exception { lock.readLock().acquire(); latch.countDown(); readLatch.countDown(); return null; } } ); } for ( int i = 0; i < WRITERS; ++i ) { service.submit ( new Callable() { @Override public Void call() throws Exception { Assert.assertTrue(readLatch.await(10, TimeUnit.SECONDS)); latch.countDown(); // must be before as there can only be one writer lock.writeLock().acquire(); return null; } } ); } Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); Collection readers = lock.readLock().getParticipantNodes(); Collection writers = lock.writeLock().getParticipantNodes(); Assert.assertEquals(readers.size(), READERS); Assert.assertEquals(writers.size(), WRITERS); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testThatUpgradingIsDisallowed() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock"); lock.readLock().acquire(); Assert.assertFalse(lock.writeLock().acquire(5, TimeUnit.SECONDS)); lock.readLock().release(); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testThatDowngradingRespectsThreads() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); final InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock"); ExecutorService t1 = Executors.newSingleThreadExecutor(); ExecutorService t2 = Executors.newSingleThreadExecutor(); final CountDownLatch latch = new CountDownLatch(1); Future f1 = t1.submit ( new Callable() { @Override public Object call() throws Exception { lock.writeLock().acquire(); latch.countDown(); return null; } } ); Future f2 = t2.submit ( new Callable() { @Override public Object call() throws Exception { Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); Assert.assertFalse(lock.readLock().acquire(5, TimeUnit.SECONDS)); return null; } } ); f1.get(); f2.get(); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testDowngrading() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock"); lock.writeLock().acquire(); Assert.assertTrue(lock.readLock().acquire(5, TimeUnit.SECONDS)); lock.writeLock().release(); lock.readLock().release(); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testBasic() throws Exception { final int CONCURRENCY = 8; final int ITERATIONS = 100; final Random random = new Random(); final AtomicInteger concurrentCount = new AtomicInteger(0); final AtomicInteger maxConcurrentCount = new AtomicInteger(0); final AtomicInteger writeCount = new AtomicInteger(0); final AtomicInteger readCount = new AtomicInteger(0); List> futures = Lists.newArrayList(); ExecutorService service = Executors.newCachedThreadPool(); for ( int i = 0; i < CONCURRENCY; ++i ) { Future future = service.submit ( new Callable() { @Override public Void call() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock"); for ( int i = 0; i < ITERATIONS; ++i ) { if ( random.nextInt(100) < 10 ) { doLocking(lock.writeLock(), concurrentCount, maxConcurrentCount, random, 1); writeCount.incrementAndGet(); } else { doLocking(lock.readLock(), concurrentCount, maxConcurrentCount, random, Integer.MAX_VALUE); readCount.incrementAndGet(); } } } finally { CloseableUtils.closeQuietly(client); } return null; } } ); futures.add(future); } for ( Future future : futures ) { future.get(); } System.out.println("Writes: " + writeCount.get() + " - Reads: " + readCount.get() + " - Max Reads: " + maxConcurrentCount.get()); Assert.assertTrue(writeCount.get() > 0); Assert.assertTrue(readCount.get() > 0); Assert.assertTrue(maxConcurrentCount.get() > 1); } @Test public void testSetNodeData() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); final byte[] nodeData = new byte[] { 1, 2, 3, 4 }; InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock", nodeData); // mutate passed-in node data, lock has made copy nodeData[0] = 5; lock.writeLock().acquire(); List children = client.getChildren().forPath("/lock"); Assert.assertEquals(1, children.size()); byte dataInZk[] = client.getData().forPath("/lock/" + children.get(0)); Assert.assertNotNull(dataInZk); Assert.assertEquals(new byte[] { 1, 2, 3, 4 }, dataInZk); lock.writeLock().release(); } finally { CloseableUtils.closeQuietly(client); } } private void doLocking(InterProcessLock lock, AtomicInteger concurrentCount, AtomicInteger maxConcurrentCount, Random random, int maxAllowed) throws Exception { try { Assert.assertTrue(lock.acquire(10, TimeUnit.SECONDS)); int localConcurrentCount; synchronized(this) { localConcurrentCount = concurrentCount.incrementAndGet(); if ( localConcurrentCount > maxConcurrentCount.get() ) { maxConcurrentCount.set(localConcurrentCount); } } Assert.assertTrue(localConcurrentCount <= maxAllowed, "" + localConcurrentCount); Thread.sleep(random.nextInt(9) + 1); } finally { synchronized(this) { concurrentCount.decrementAndGet(); lock.release(); } } } } TestInterProcessSemaphore.java000066400000000000000000000526671245521677600420720ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import com.google.common.collect.Lists; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.shared.SharedCount; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.Timing; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Collection; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; @SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter"}) public class TestInterProcessSemaphore extends BaseClassForTests { @Test public void testThreadedLeaseIncrease() throws Exception { final Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); final SharedCount count = new SharedCount(client, "/foo/count", 1); count.start(); final InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", count); ExecutorService service = Executors.newCachedThreadPool(); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); Future future1 = service.submit ( new Callable() { @Override public Object call() throws Exception { Lease lease = semaphore.acquire(timing.seconds(), TimeUnit.SECONDS); Assert.assertNotNull(lease); latch1.countDown(); lease = semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS); Assert.assertNotNull(lease); latch2.countDown(); return null; } } ); Future future2 = service.submit ( new Callable() { @Override public Object call() throws Exception { Assert.assertTrue(latch1.await(timing.forWaiting().seconds(), TimeUnit.SECONDS)); timing.sleepABit(); // make sure second acquire is waiting Assert.assertTrue(count.trySetCount(2)); //Make sure second acquire takes less than full waiting time: timing.sleepABit(); Assert.assertTrue(latch2.await(0, TimeUnit.SECONDS)); return null; } } ); future1.get(); future2.get(); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testClientClose() throws Exception { final Timing timing = new Timing(); CuratorFramework client1 = null; CuratorFramework client2 = null; InterProcessSemaphoreV2 semaphore1; InterProcessSemaphoreV2 semaphore2; try { client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client1.start(); client2.start(); semaphore1 = new InterProcessSemaphoreV2(client1, "/test", 1); semaphore2 = new InterProcessSemaphoreV2(client2, "/test", 1); Lease lease = semaphore2.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS); Assert.assertNotNull(lease); lease.close(); lease = semaphore1.acquire(10, TimeUnit.SECONDS); Assert.assertNotNull(lease); client1.close(); // should release any held leases client1 = null; Assert.assertNotNull(semaphore2.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS)); } finally { CloseableUtils.closeQuietly(client1); CloseableUtils.closeQuietly(client2); } } @Test public void testMaxPerSession() throws Exception { final int CLIENT_QTY = 10; final int LOOP_QTY = 100; final Random random = new Random(); final int SESSION_MAX = random.nextInt(75) + 25; final Timing timing = new Timing(); List> futures = Lists.newArrayList(); ExecutorService service = Executors.newCachedThreadPool(); final Counter counter = new Counter(); final AtomicInteger available = new AtomicInteger(SESSION_MAX); for ( int i = 0; i < CLIENT_QTY; ++i ) { futures.add ( service.submit ( new Callable() { @Override public Object call() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", SESSION_MAX); for ( int i = 0; i < LOOP_QTY; ++i ) { long start = System.currentTimeMillis(); int thisQty; synchronized(available) { if ( (System.currentTimeMillis() - start) > 10000 ) { throw new TimeoutException(); } while ( available.get() == 0 ) { available.wait(timing.forWaiting().milliseconds()); } thisQty = (available.get() > 1) ? (random.nextInt(available.get()) + 1) : 1; available.addAndGet(-1 * thisQty); Assert.assertTrue(available.get() >= 0); } Collection leases = semaphore.acquire(thisQty, timing.forWaiting().seconds(), TimeUnit.SECONDS); Assert.assertNotNull(leases); try { synchronized(counter) { counter.currentCount += thisQty; if ( counter.currentCount > counter.maxCount ) { counter.maxCount = counter.currentCount; } } Thread.sleep(random.nextInt(25)); } finally { synchronized(counter) { counter.currentCount -= thisQty; } semaphore.returnAll(leases); synchronized(available) { available.addAndGet(thisQty); available.notifyAll(); } } } } finally { client.close(); } return null; } } ) ); } for ( Future f : futures ) { f.get(); } synchronized(counter) { Assert.assertTrue(counter.currentCount == 0); Assert.assertTrue(counter.maxCount > 0); Assert.assertTrue(counter.maxCount <= SESSION_MAX); System.out.println(counter.maxCount); } } @Test public void testRelease1AtATime() throws Exception { final Timing timing = new Timing(); final int CLIENT_QTY = 10; final int MAX = CLIENT_QTY / 2; final AtomicInteger maxLeases = new AtomicInteger(0); final AtomicInteger activeQty = new AtomicInteger(0); final AtomicInteger uses = new AtomicInteger(0); List> futures = Lists.newArrayList(); ExecutorService service = Executors.newFixedThreadPool(CLIENT_QTY); for ( int i = 0; i < CLIENT_QTY; ++i ) { Future f = service.submit ( new Callable() { @Override public Object call() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", MAX); Lease lease = semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS); Assert.assertNotNull(lease); uses.incrementAndGet(); try { synchronized(maxLeases) { int qty = activeQty.incrementAndGet(); if ( qty > maxLeases.get() ) { maxLeases.set(qty); } } timing.sleepABit(); } finally { activeQty.decrementAndGet(); lease.close(); } } finally { client.close(); } return null; } } ); futures.add(f); } for ( Future f : futures ) { f.get(); } Assert.assertEquals(uses.get(), CLIENT_QTY); Assert.assertEquals(maxLeases.get(), MAX); } @Test public void testReleaseInChunks() throws Exception { final Timing timing = new Timing(); final int MAX_LEASES = 11; final int THREADS = 100; final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { final Stepper latch = new Stepper(); final Random random = new Random(); final Counter counter = new Counter(); ExecutorService service = Executors.newCachedThreadPool(); ExecutorCompletionService completionService = new ExecutorCompletionService(service); for ( int i = 0; i < THREADS; ++i ) { completionService.submit ( new Callable() { @Override public Object call() throws Exception { InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", MAX_LEASES); Lease lease = semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS); if ( lease == null ) { throw new Exception("timed out"); } try { synchronized(counter) { ++counter.currentCount; if ( counter.currentCount > counter.maxCount ) { counter.maxCount = counter.currentCount; } counter.notifyAll(); } latch.await(); } finally { synchronized(counter) { --counter.currentCount; } semaphore.returnLease(lease); } return null; } } ); } int remaining = THREADS; while ( remaining > 0 ) { int times = Math.min(random.nextInt(5) + 1, remaining); latch.countDown(times); remaining -= times; Thread.sleep(random.nextInt(100) + 1); } for ( int i = 0; i < THREADS; ++i ) { completionService.take(); } timing.sleepABit(); synchronized(counter) { Assert.assertTrue(counter.currentCount == 0); Assert.assertTrue(counter.maxCount > 0); Assert.assertTrue(counter.maxCount <= MAX_LEASES); System.out.println(counter.maxCount); } } finally { client.close(); } } @Test public void testThreads() throws Exception { final int THREAD_QTY = 10; Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { final InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", 1); ExecutorService service = Executors.newFixedThreadPool(THREAD_QTY); for ( int i = 0; i < THREAD_QTY; ++i ) { service.submit ( new Callable() { @Override public Object call() throws Exception { Lease lease = semaphore.acquire(); try { Thread.sleep(1); } finally { lease.close(); } return null; } } ); } service.shutdown(); Assert.assertTrue(service.awaitTermination(10, TimeUnit.SECONDS)); } finally { client.close(); } } @Test public void testSimple() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", 1); Assert.assertNotNull(semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS)); Assert.assertNull(semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS)); } finally { client.close(); } } @Test public void testSimple2() throws Exception { final int MAX_LEASES = 3; Timing timing = new Timing(); List leases = Lists.newArrayList(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { for ( int i = 0; i < MAX_LEASES; ++i ) { InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", MAX_LEASES); Lease lease = semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS); Assert.assertNotNull(lease); leases.add(lease); } InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", MAX_LEASES); Lease lease = semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS); Assert.assertNull(lease); leases.remove(0).close(); Assert.assertNotNull(semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS)); } finally { for ( Lease l : leases ) { CloseableUtils.closeQuietly(l); } CloseableUtils.closeQuietly(client); } } @Test public void testGetParticipantNodes() throws Exception { final int LEASES = 3; Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); List leases = Lists.newArrayList(); client.start(); try { InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", LEASES); for ( int i = 0; i < LEASES; ++i ) { leases.add(semaphore.acquire()); } Assert.assertEquals(semaphore.getParticipantNodes().size(), LEASES); } finally { for ( Lease l : leases ) { CloseableUtils.closeQuietly(l); } CloseableUtils.closeQuietly(client); } } } TestInterProcessSemaphoreCluster.java000066400000000000000000000275001245521677600434200ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import com.google.common.collect.Lists; import org.apache.curator.ensemble.EnsembleProvider; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.test.InstanceSpec; import org.apache.curator.test.TestingCluster; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.testng.Assert; import org.testng.annotations.Test; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; public class TestInterProcessSemaphoreCluster { @Test public void testKilledServerWithEnsembleProvider() throws Exception { final int CLIENT_QTY = 10; final Timing timing = new Timing(); final String PATH = "/foo/bar/lock"; ExecutorService executorService = Executors.newFixedThreadPool(CLIENT_QTY); ExecutorCompletionService completionService = new ExecutorCompletionService(executorService); TestingCluster cluster = new TestingCluster(3); try { cluster.start(); final AtomicReference connectionString = new AtomicReference(cluster.getConnectString()); final EnsembleProvider provider = new EnsembleProvider() { @Override public void start() throws Exception { } @Override public String getConnectionString() { return connectionString.get(); } @Override public void close() throws IOException { } }; final Semaphore acquiredSemaphore = new Semaphore(0); final AtomicInteger acquireCount = new AtomicInteger(0); final CountDownLatch suspendedLatch = new CountDownLatch(CLIENT_QTY); for ( int i = 0; i < CLIENT_QTY; ++i ) { completionService.submit ( new Callable() { @Override public Void call() throws Exception { CuratorFramework client = CuratorFrameworkFactory.builder() .ensembleProvider(provider) .sessionTimeoutMs(timing.session()) .connectionTimeoutMs(timing.connection()) .retryPolicy(new ExponentialBackoffRetry(100, 3)) .build(); try { final Semaphore suspendedSemaphore = new Semaphore(0); client.getConnectionStateListenable().addListener ( new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( (newState == ConnectionState.SUSPENDED) || (newState == ConnectionState.LOST) ) { suspendedLatch.countDown(); suspendedSemaphore.release(); } } } ); client.start(); InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, PATH, 1); while ( !Thread.currentThread().isInterrupted() ) { Lease lease = null; try { lease = semaphore.acquire(); acquiredSemaphore.release(); acquireCount.incrementAndGet(); suspendedSemaphore.acquire(); } catch ( Exception e ) { // just retry } finally { if ( lease != null ) { acquireCount.decrementAndGet(); CloseableUtils.closeQuietly(lease); } } } } finally { CloseableUtils.closeQuietly(client); } return null; } } ); } Assert.assertTrue(timing.acquireSemaphore(acquiredSemaphore)); Assert.assertEquals(1, acquireCount.get()); cluster.close(); timing.awaitLatch(suspendedLatch); timing.forWaiting().sleepABit(); Assert.assertEquals(0, acquireCount.get()); cluster = new TestingCluster(3); cluster.start(); connectionString.set(cluster.getConnectString()); timing.forWaiting().sleepABit(); Assert.assertTrue(timing.acquireSemaphore(acquiredSemaphore)); timing.forWaiting().sleepABit(); Assert.assertEquals(1, acquireCount.get()); } finally { executorService.shutdown(); executorService.awaitTermination(10, TimeUnit.SECONDS); executorService.shutdownNow(); CloseableUtils.closeQuietly(cluster); } } @Test public void testCluster() throws Exception { final int QTY = 20; final int OPERATION_TIME_MS = 1000; final String PATH = "/foo/bar/lock"; ExecutorService executorService = Executors.newFixedThreadPool(QTY); ExecutorCompletionService completionService = new ExecutorCompletionService(executorService); final Timing timing = new Timing(); TestingCluster cluster = new TestingCluster(3); List semaphoreClients = Lists.newArrayList(); try { cluster.start(); final AtomicInteger opCount = new AtomicInteger(0); for ( int i = 0; i < QTY; ++i ) { SemaphoreClient semaphoreClient = new SemaphoreClient ( cluster.getConnectString(), PATH, new Callable() { @Override public Void call() throws Exception { opCount.incrementAndGet(); Thread.sleep(OPERATION_TIME_MS); return null; } } ); completionService.submit(semaphoreClient); semaphoreClients.add(semaphoreClient); } timing.forWaiting().sleepABit(); Assert.assertNotNull(SemaphoreClient.getActiveClient()); final CountDownLatch latch = new CountDownLatch(1); CuratorFramework client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState == ConnectionState.LOST ) { latch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); client.start(); try { client.getZookeeperClient().blockUntilConnectedOrTimedOut(); cluster.stop(); latch.await(); } finally { CloseableUtils.closeQuietly(client); } long startTicks = System.currentTimeMillis(); for(;;) { int thisOpCount = opCount.get(); Thread.sleep(2 * OPERATION_TIME_MS); if ( thisOpCount == opCount.get() ) { break; // checking that the op count isn't increasing } Assert.assertTrue((System.currentTimeMillis() - startTicks) < timing.forWaiting().milliseconds()); } int thisOpCount = opCount.get(); Iterator iterator = cluster.getInstances().iterator(); cluster = new TestingCluster(iterator.next(), iterator.next()); cluster.start(); timing.forWaiting().sleepABit(); startTicks = System.currentTimeMillis(); for(;;) { Thread.sleep(2 * OPERATION_TIME_MS); if ( opCount.get() > thisOpCount ) { break; // checking that semaphore has started working again } Assert.assertTrue((System.currentTimeMillis() - startTicks) < timing.forWaiting().milliseconds()); } } finally { for ( SemaphoreClient semaphoreClient : semaphoreClients ) { CloseableUtils.closeQuietly(semaphoreClient); } CloseableUtils.closeQuietly(cluster); executorService.shutdownNow(); } } } TestInterProcessSemaphoreMutex.java000066400000000000000000000026761245521677600431100ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import org.apache.curator.framework.CuratorFramework; import org.testng.annotations.Test; public class TestInterProcessSemaphoreMutex extends TestInterProcessMutexBase { private static final String LOCK_PATH = "/locks/our-lock"; @Override @Test(enabled = false) public void testReentrant() throws Exception { } @Override @Test(enabled = false) public void testReentrant2Threads() throws Exception { } @Override protected InterProcessLock makeLock(CuratorFramework client) { return new InterProcessSemaphoreMutex(client, LOCK_PATH); } } TestLockACLs.java000066400000000000000000000070661245521677600371720ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.ACLProvider; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.test.TestingServer; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Id; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Collections; import java.util.List; public class TestLockACLs extends BaseClassForTests { private static final List ACLS = Collections.singletonList(new ACL(ZooDefs.Perms.ALL, new Id("ip", "127.0.0.1"))); private CuratorFramework createClient() throws Exception { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); CuratorFramework client = CuratorFrameworkFactory.builder() .namespace("ns") .connectString(server.getConnectString()) .retryPolicy(retryPolicy) .aclProvider(new MyACLProvider()) .build(); client.start(); return client; } @Test public void testLockACLs() throws Exception { CuratorFramework client = createClient(); try { client.create().forPath("/foo"); Assert.assertNotNull(client.checkExists().forPath("/foo")); Assert.assertEquals(ZooDefs.Perms.ALL, client.getACL().forPath("/foo").get(0).getPerms()); Assert.assertEquals("ip", client.getACL().forPath("/foo").get(0).getId().getScheme()); Assert.assertEquals("127.0.0.1", client.getACL().forPath("/foo").get(0).getId().getId()); InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/bar"); InterProcessMutex writeLock = lock.writeLock(); writeLock.acquire(); Assert.assertNotNull(client.checkExists().forPath("/bar")); Assert.assertEquals(ZooDefs.Perms.ALL, client.getACL().forPath("/bar").get(0).getPerms()); Assert.assertEquals("ip", client.getACL().forPath("/bar").get(0).getId().getScheme()); Assert.assertEquals("127.0.0.1", client.getACL().forPath("/bar").get(0).getId().getId()); } finally { CloseableUtils.closeQuietly(client); } } public class MyACLProvider implements ACLProvider { @Override public List getDefaultAcl() { return ACLS; } @Override public List getAclForPath(String path) { return ACLS; } } } TestLockCleanlinessWithFaults.java000066400000000000000000000051141245521677600426530ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryNTimes; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.zookeeper.KeeperException; import org.testng.Assert; import org.testng.annotations.Test; import java.util.List; public class TestLockCleanlinessWithFaults extends BaseClassForTests { @Test public void testNodeDeleted() throws Exception { final String PATH = "/foo/bar"; CuratorFramework client = null; try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryNTimes(0, 0)); client.start(); client.create().creatingParentsIfNeeded().forPath(PATH); Assert.assertEquals(client.checkExists().forPath(PATH).getNumChildren(), 0); LockInternals internals = new LockInternals(client, new StandardLockInternalsDriver(), PATH, "lock-", 1) { @Override List getSortedChildren() throws Exception { throw new KeeperException.NoNodeException(); } }; try { internals.attemptLock(0, null, null); Assert.fail(); } catch ( KeeperException.NoNodeException dummy ) { // expected } // make sure no nodes are left lying around Assert.assertEquals(client.checkExists().forPath(PATH).getNumChildren(), 0); } finally { CloseableUtils.closeQuietly(client); } } } TestReaper.java000066400000000000000000000435411245521677600370130ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.locks; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.leader.LeaderSelector; import org.apache.curator.framework.recipes.leader.LeaderSelectorListener; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.data.Stat; import org.testng.Assert; import org.testng.annotations.Test; import java.io.IOException; import java.util.Queue; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.atomic.AtomicInteger; public class TestReaper extends BaseClassForTests { @Test public void testUsingLeader() throws Exception { final Timing timing = new Timing(); CuratorFramework client = makeClient(timing, null); Reaper reaper1 = null; Reaper reaper2 = null; try { final AtomicInteger reaper1Count = new AtomicInteger(); reaper1 = new Reaper(client, Reaper.newExecutorService(), 1, "/reaper/leader") { @Override protected void reap(PathHolder holder) { reaper1Count.incrementAndGet(); super.reap(holder); } }; final AtomicInteger reaper2Count = new AtomicInteger(); reaper2 = new Reaper(client, Reaper.newExecutorService(), 1, "/reaper/leader") { @Override protected void reap(PathHolder holder) { reaper2Count.incrementAndGet(); super.reap(holder); } }; client.start(); client.create().creatingParentsIfNeeded().forPath("/one/two/three"); reaper1.start(); reaper2.start(); reaper1.addPath("/one/two/three"); reaper2.addPath("/one/two/three"); timing.sleepABit(); Assert.assertTrue((reaper1Count.get() == 0) || (reaper2Count.get() == 0)); Assert.assertTrue((reaper1Count.get() > 0) || (reaper2Count.get() > 0)); Reaper activeReaper; AtomicInteger inActiveReaperCount; if ( reaper1Count.get() > 0 ) { activeReaper = reaper1; inActiveReaperCount = reaper2Count; } else { activeReaper = reaper2; inActiveReaperCount = reaper1Count; } Assert.assertEquals(inActiveReaperCount.get(), 0); activeReaper.close(); timing.sleepABit(); Assert.assertTrue(inActiveReaperCount.get() > 0); } finally { CloseableUtils.closeQuietly(reaper1); CloseableUtils.closeQuietly(reaper2); CloseableUtils.closeQuietly(client); } } @Test public void testUsingManualLeader() throws Exception { final Timing timing = new Timing(); final CuratorFramework client = makeClient(timing, null); final CountDownLatch latch = new CountDownLatch(1); LeaderSelectorListener listener = new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework client) throws Exception { Reaper reaper = new Reaper(client, 1); try { reaper.addPath("/one/two/three", Reaper.Mode.REAP_UNTIL_DELETE); reaper.start(); timing.sleepABit(); latch.countDown(); } finally { CloseableUtils.closeQuietly(reaper); } } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; LeaderSelector selector = new LeaderSelector(client, "/leader", listener); try { client.start(); client.create().creatingParentsIfNeeded().forPath("/one/two/three"); Assert.assertNotNull(client.checkExists().forPath("/one/two/three")); selector.start(); timing.awaitLatch(latch); Assert.assertNull(client.checkExists().forPath("/one/two/three")); } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } @Test public void testSparseUseNoReap() throws Exception { final int THRESHOLD = 3000; Timing timing = new Timing(); Reaper reaper = null; CuratorFramework client = makeClient(timing, null); try { client.start(); client.create().creatingParentsIfNeeded().forPath("/one/two/three"); Assert.assertNotNull(client.checkExists().forPath("/one/two/three")); final Queue holders = new ConcurrentLinkedQueue(); final ExecutorService pool = Executors.newCachedThreadPool(); ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1); reaper = new Reaper(client, service, THRESHOLD) { @Override protected Future schedule(final PathHolder pathHolder, int reapingThresholdMs) { holders.add(pathHolder); final Future f = super.schedule(pathHolder, reapingThresholdMs); pool.submit(new Callable() { @Override public Void call() throws Exception { f.get(); holders.remove(pathHolder); return null; } } ); return null; } }; reaper.start(); reaper.addPath("/one/two/three"); long start = System.currentTimeMillis(); boolean emptyCountIsCorrect = false; while ( ((System.currentTimeMillis() - start) < timing.forWaiting().milliseconds()) && !emptyCountIsCorrect ) // need to loop as the Holder can go in/out of the Reaper's DelayQueue { for ( Reaper.PathHolder holder : holders ) { if ( holder.path.endsWith("/one/two/three") ) { emptyCountIsCorrect = (holder.emptyCount > 0); break; } } Thread.sleep(1); } Assert.assertTrue(emptyCountIsCorrect); client.create().forPath("/one/two/three/foo"); Thread.sleep(2 * (THRESHOLD / Reaper.EMPTY_COUNT_THRESHOLD)); Assert.assertNotNull(client.checkExists().forPath("/one/two/three")); client.delete().forPath("/one/two/three/foo"); Thread.sleep(THRESHOLD); timing.sleepABit(); Assert.assertNull(client.checkExists().forPath("/one/two/three")); } finally { CloseableUtils.closeQuietly(reaper); CloseableUtils.closeQuietly(client); } } @Test public void testReapUntilDelete() throws Exception { testReapUntilDelete(null); } @Test public void testReapUntilDeleteNamespace() throws Exception { testReapUntilDelete("test"); } @Test public void testReapUntilGone() throws Exception { testReapUntilGone(null); } @Test public void testReapUntilGoneNamespace() throws Exception { testReapUntilGone("test"); } @Test public void testRemove() throws Exception { testRemove(null); } @Test public void testRemoveNamespace() throws Exception { testRemove("test"); } @Test public void testSimulationWithLocks() throws Exception { testSimulationWithLocks(null); } @Test public void testSimulationWithLocksNamespace() throws Exception { testSimulationWithLocks("test"); } @Test public void testWithEphemerals() throws Exception { testWithEphemerals(null); } @Test public void testWithEphemeralsNamespace() throws Exception { testWithEphemerals("test"); } @Test public void testBasic() throws Exception { testBasic(null); } @Test public void testBasicNamespace() throws Exception { testBasic("test"); } private void testReapUntilDelete(String namespace) throws Exception { Timing timing = new Timing(); Reaper reaper = null; CuratorFramework client = makeClient(timing, namespace); try { client.start(); client.create().creatingParentsIfNeeded().forPath("/one/two/three"); Assert.assertNotNull(client.checkExists().forPath("/one/two/three")); reaper = new Reaper(client, 100); reaper.start(); reaper.addPath("/one/two/three", Reaper.Mode.REAP_UNTIL_DELETE); timing.sleepABit(); Assert.assertNull(client.checkExists().forPath("/one/two/three")); client.create().forPath("/one/two/three"); timing.sleepABit(); Assert.assertNotNull(client.checkExists().forPath("/one/two/three")); } finally { CloseableUtils.closeQuietly(reaper); CloseableUtils.closeQuietly(client); } } private void testReapUntilGone(String namespace) throws Exception { Timing timing = new Timing(); Reaper reaper = null; CuratorFramework client = makeClient(timing, namespace); try { client.start(); reaper = new Reaper(client, 100); reaper.start(); reaper.addPath("/one/two/three", Reaper.Mode.REAP_UNTIL_GONE); timing.sleepABit(); client.create().creatingParentsIfNeeded().forPath("/one/two/three"); Assert.assertNotNull(client.checkExists().forPath("/one/two/three")); reaper.addPath("/one/two/three", Reaper.Mode.REAP_UNTIL_GONE); timing.sleepABit(); Assert.assertNull(client.checkExists().forPath("/one/two/three")); } finally { CloseableUtils.closeQuietly(reaper); CloseableUtils.closeQuietly(client); } } private CuratorFramework makeClient(Timing timing, String namespace) throws IOException { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder().connectionTimeoutMs(timing.connection()).sessionTimeoutMs(timing.session()).connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)); if ( namespace != null ) { builder = builder.namespace(namespace); } return builder.build(); } private void testRemove(String namespace) throws Exception { Timing timing = new Timing(); Reaper reaper = null; CuratorFramework client = makeClient(timing, namespace); try { client.start(); client.create().creatingParentsIfNeeded().forPath("/one/two/three"); Assert.assertNotNull(client.checkExists().forPath("/one/two/three")); reaper = new Reaper(client, 100); reaper.start(); reaper.addPath("/one/two/three"); timing.sleepABit(); Assert.assertNull(client.checkExists().forPath("/one/two/three")); Assert.assertTrue(reaper.removePath("/one/two/three")); client.create().forPath("/one/two/three"); timing.sleepABit(); Assert.assertNotNull(client.checkExists().forPath("/one/two/three")); } finally { CloseableUtils.closeQuietly(reaper); CloseableUtils.closeQuietly(client); } } private void testSimulationWithLocks(String namespace) throws Exception { final int LOCK_CLIENTS = 10; final int ITERATIONS = 250; final int MAX_WAIT_MS = 10; ExecutorService service = Executors.newFixedThreadPool(LOCK_CLIENTS); ExecutorCompletionService completionService = new ExecutorCompletionService(service); Timing timing = new Timing(); Reaper reaper = null; final CuratorFramework client = makeClient(timing, namespace); try { client.start(); reaper = new Reaper(client, MAX_WAIT_MS / 2); reaper.start(); reaper.addPath("/a/b"); for ( int i = 0; i < LOCK_CLIENTS; ++i ) { completionService.submit(new Callable() { @Override public Object call() throws Exception { final InterProcessMutex lock = new InterProcessMutex(client, "/a/b"); for ( int i = 0; i < ITERATIONS; ++i ) { lock.acquire(); try { Thread.sleep((int)(Math.random() * MAX_WAIT_MS)); } finally { lock.release(); } } return null; } } ); } for ( int i = 0; i < LOCK_CLIENTS; ++i ) { completionService.take().get(); } Thread.sleep(timing.session()); timing.sleepABit(); Stat stat = client.checkExists().forPath("/a/b"); Assert.assertNull(stat, "Child qty: " + ((stat != null) ? stat.getNumChildren() : 0)); } finally { service.shutdownNow(); CloseableUtils.closeQuietly(reaper); CloseableUtils.closeQuietly(client); } } private void testWithEphemerals(String namespace) throws Exception { Timing timing = new Timing(); Reaper reaper = null; CuratorFramework client2 = null; CuratorFramework client = makeClient(timing, namespace); try { client.start(); client.create().creatingParentsIfNeeded().forPath("/one/two/three"); Assert.assertNotNull(client.checkExists().forPath("/one/two/three")); client2 = makeClient(timing, namespace); client2.start(); for ( int i = 0; i < 10; ++i ) { client2.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/one/two/three/foo-"); } reaper = new Reaper(client, 100); reaper.start(); reaper.addPath("/one/two/three"); timing.sleepABit(); Assert.assertNotNull(client.checkExists().forPath("/one/two/three")); client2.close(); // should clear ephemerals client2 = null; Thread.sleep(timing.session()); timing.sleepABit(); Assert.assertNull(client.checkExists().forPath("/one/two/three")); } finally { CloseableUtils.closeQuietly(reaper); CloseableUtils.closeQuietly(client2); CloseableUtils.closeQuietly(client); } } private void testBasic(String namespace) throws Exception { Timing timing = new Timing(); Reaper reaper = null; CuratorFramework client = makeClient(timing, namespace); try { client.start(); client.create().creatingParentsIfNeeded().forPath("/one/two/three"); Assert.assertNotNull(client.checkExists().forPath("/one/two/three")); reaper = new Reaper(client, 100); reaper.start(); reaper.addPath("/one/two/three"); timing.sleepABit(); Assert.assertNull(client.checkExists().forPath("/one/two/three")); } finally { CloseableUtils.closeQuietly(reaper); CloseableUtils.closeQuietly(client); } } } 000077500000000000000000000000001245521677600340605ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodesTestPersistentEphemeralNode.java000066400000000000000000000453221245521677600423620ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.nodes; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.KillSession; import org.apache.curator.test.TestingServer; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.data.Stat; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import static org.testng.Assert.*; public class TestPersistentEphemeralNode extends BaseClassForTests { private static final String DIR = "/test"; private static final String PATH = ZKPaths.makePath(DIR, "/foo"); private final Collection curatorInstances = Lists.newArrayList(); private final Collection createdNodes = Lists.newArrayList(); private final Timing timing = new Timing(); @AfterMethod public void teardown() throws Exception { for ( PersistentEphemeralNode node : createdNodes ) { node.close(); } for ( CuratorFramework curator : curatorInstances ) { curator.close(); } super.teardown(); } @Test public void testListenersReconnectedIsFast() throws Exception { server.close(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); PersistentEphemeralNode node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes()); node.start(); final CountDownLatch connectedLatch = new CountDownLatch(1); final CountDownLatch reconnectedLatch = new CountDownLatch(1); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState == ConnectionState.CONNECTED ) { connectedLatch.countDown(); } if ( newState == ConnectionState.RECONNECTED ) { reconnectedLatch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); timing.sleepABit(); server = new TestingServer(server.getPort()); Assert.assertTrue(timing.awaitLatch(connectedLatch)); timing.sleepABit(); Assert.assertTrue(node.waitForInitialCreate(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); server.close(); timing.sleepABit(); server = new TestingServer(server.getPort()); timing.sleepABit(); Assert.assertTrue(timing.awaitLatch(reconnectedLatch)); } finally { CloseableUtils.closeQuietly(client); } } @Test public void testNoServerAtStart() throws Exception { server.close(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); PersistentEphemeralNode node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes()); node.start(); final CountDownLatch connectedLatch = new CountDownLatch(1); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState == ConnectionState.CONNECTED ) { connectedLatch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); timing.sleepABit(); server = new TestingServer(server.getPort()); Assert.assertTrue(timing.awaitLatch(connectedLatch)); timing.sleepABit(); Assert.assertTrue(node.waitForInitialCreate(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); } finally { CloseableUtils.closeQuietly(client); } } @Test(expectedExceptions = NullPointerException.class) public void testNullCurator() throws Exception { new PersistentEphemeralNode(null, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullPath() throws Exception { CuratorFramework curator = newCurator(); new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, null, new byte[0]); } @Test(expectedExceptions = NullPointerException.class) public void testNullData() throws Exception { CuratorFramework curator = newCurator(); new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, null); } @Test(expectedExceptions = NullPointerException.class) public void testNullMode() throws Exception { CuratorFramework curator = newCurator(); new PersistentEphemeralNode(curator, null, PATH, new byte[0]); } @Test public void testSettingDataSequential() throws Exception { setDataTest(PersistentEphemeralNode.Mode.EPHEMERAL_SEQUENTIAL); } @Test public void testSettingData() throws Exception { setDataTest(PersistentEphemeralNode.Mode.EPHEMERAL); } protected void setDataTest(PersistentEphemeralNode.Mode mode) throws Exception { PersistentEphemeralNode node = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); node = new PersistentEphemeralNode(client, mode, PATH, "a".getBytes()); node.start(); Assert.assertTrue(node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS)); Assert.assertEquals(client.getData().forPath(node.getActualPath()), "a".getBytes()); final Semaphore semaphore = new Semaphore(0); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent arg0) { semaphore.release(); } }; client.checkExists().usingWatcher(watcher).forPath(node.getActualPath()); node.setData("b".getBytes()); Assert.assertTrue(timing.acquireSemaphore(semaphore)); Assert.assertEquals(node.getActualPath(), node.getActualPath()); Assert.assertEquals(client.getData().usingWatcher(watcher).forPath(node.getActualPath()), "b".getBytes()); node.setData("c".getBytes()); Assert.assertTrue(timing.acquireSemaphore(semaphore)); Assert.assertEquals(node.getActualPath(), node.getActualPath()); Assert.assertEquals(client.getData().usingWatcher(watcher).forPath(node.getActualPath()), "c".getBytes()); node.close(); Assert.assertTrue(timing.acquireSemaphore(semaphore)); } finally { if ( node != null ) { node.close(); } client.close(); } } @Test public void testDeletesNodeWhenClosed() throws Exception { CuratorFramework curator = newCurator(); PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); node.start(); String path = null; try { node.waitForInitialCreate(5, TimeUnit.SECONDS); path = node.getActualPath(); assertNodeExists(curator, path); } finally { node.close(); // After closing the path is set to null... } assertNodeDoesNotExist(curator, path); } @Test public void testClosingMultipleTimes() throws Exception { CuratorFramework curator = newCurator(); PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); node.start(); node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); String path = node.getActualPath(); node.close(); assertNodeDoesNotExist(curator, path); node.close(); assertNodeDoesNotExist(curator, path); } @Test public void testDeletesNodeWhenSessionDisconnects() throws Exception { CuratorFramework curator = newCurator(); CuratorFramework observer = newCurator(); PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); node.start(); try { node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertNodeExists(observer, node.getActualPath()); // Register a watch that will fire when the node is deleted... Trigger deletedTrigger = Trigger.deleted(); observer.checkExists().usingWatcher(deletedTrigger).forPath(node.getActualPath()); killSession(curator); // Make sure the node got deleted assertTrue(deletedTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS)); } finally { node.close(); } } @Test public void testRecreatesNodeWhenSessionReconnects() throws Exception { CuratorFramework curator = newCurator(); CuratorFramework observer = newCurator(); PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); node.start(); try { node.waitForInitialCreate(5, TimeUnit.SECONDS); assertNodeExists(observer, node.getActualPath()); Trigger deletedTrigger = Trigger.deleted(); observer.checkExists().usingWatcher(deletedTrigger).forPath(node.getActualPath()); killSession(curator); // Make sure the node got deleted... assertTrue(deletedTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS)); // Check for it to be recreated... Trigger createdTrigger = Trigger.created(); Stat stat = observer.checkExists().usingWatcher(createdTrigger).forPath(node.getActualPath()); assertTrue(stat != null || createdTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS)); } finally { node.close(); } } @Test public void testRecreatesNodeWhenSessionReconnectsMultipleTimes() throws Exception { CuratorFramework curator = newCurator(); CuratorFramework observer = newCurator(); PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); node.start(); try { node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); String path = node.getActualPath(); assertNodeExists(observer, path); // We should be able to disconnect multiple times and each time the node should be recreated. for ( int i = 0; i < 5; i++ ) { Trigger deletionTrigger = Trigger.deleted(); observer.checkExists().usingWatcher(deletionTrigger).forPath(path); // Kill the session, thus cleaning up the node... killSession(curator); // Make sure the node ended up getting deleted... assertTrue(deletionTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS)); // Now put a watch in the background looking to see if it gets created... Trigger creationTrigger = Trigger.created(); Stat stat = observer.checkExists().usingWatcher(creationTrigger).forPath(path); assertTrue(stat != null || creationTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS)); } } finally { node.close(); } } @Test public void testRecreatesNodeWhenItGetsDeleted() throws Exception { CuratorFramework curator = newCurator(); PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); node.start(); try { node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); String originalNode = node.getActualPath(); assertNodeExists(curator, originalNode); // Delete the original node... curator.delete().forPath(originalNode); // Since we're using an ephemeral node, and the original session hasn't been interrupted the name of the new // node that gets created is going to be exactly the same as the original. Trigger createdWatchTrigger = Trigger.created(); Stat stat = curator.checkExists().usingWatcher(createdWatchTrigger).forPath(originalNode); assertTrue(stat != null || createdWatchTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS)); } finally { node.close(); } } @Test public void testNodesCreateUniquePaths() throws Exception { CuratorFramework curator = newCurator(); PersistentEphemeralNode node1 = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL_SEQUENTIAL, PATH, new byte[0]); node1.start(); try { node1.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); String path1 = node1.getActualPath(); PersistentEphemeralNode node2 = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL_SEQUENTIAL, PATH, new byte[0]); node2.start(); try { node2.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); String path2 = node2.getActualPath(); assertFalse(path1.equals(path2)); } finally { node2.close(); } } finally { node1.close(); } } @Test public void testData() throws Exception { CuratorFramework curator = newCurator(); byte[] data = "Hello World".getBytes(); PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, data); node.start(); try { node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), data)); } finally { node.close(); } } private void assertNodeExists(CuratorFramework curator, String path) throws Exception { assertNotNull(path); assertTrue(curator.checkExists().forPath(path) != null); } private void assertNodeDoesNotExist(CuratorFramework curator, String path) throws Exception { assertTrue(curator.checkExists().forPath(path) == null); } private CuratorFramework newCurator() throws IOException { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); curatorInstances.add(client); return client; } public void killSession(CuratorFramework curator) throws Exception { KillSession.kill(curator.getZookeeperClient().getZooKeeper(), curator.getZookeeperClient().getCurrentConnectionString()); } private static final class Trigger implements Watcher { private final Event.EventType type; private final CountDownLatch latch; public Trigger(Event.EventType type) { assertNotNull(type); this.type = type; this.latch = new CountDownLatch(1); } @Override public void process(WatchedEvent event) { if ( type == event.getType() ) { latch.countDown(); } } public boolean firedWithin(long duration, TimeUnit unit) { try { return latch.await(duration, unit); } catch ( InterruptedException e ) { throw Throwables.propagate(e); } } private static Trigger created() { return new Trigger(Event.EventType.NodeCreated); } private static Trigger deleted() { return new Trigger(Event.EventType.NodeDeleted); } } } TestPersistentEphemeralNodeListener.java000066400000000000000000000074571245521677600440770ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.nodes; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.TestingServer; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; public class TestPersistentEphemeralNodeListener extends BaseClassForTests { @Test public void testListenersReconnectedIsOK() throws Exception { server.close(); Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); PersistentEphemeralNode node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes()); node.start(); final CountDownLatch connectedLatch = new CountDownLatch(1); final CountDownLatch reconnectedLatch = new CountDownLatch(1); final AtomicReference lastState = new AtomicReference(); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { lastState.set(newState); if ( newState == ConnectionState.CONNECTED ) { connectedLatch.countDown(); } if ( newState == ConnectionState.RECONNECTED ) { reconnectedLatch.countDown(); } System.out.println("XXXX " + newState); } }; client.getConnectionStateListenable().addListener(listener); timing.sleepABit(); server = new TestingServer(server.getPort()); Assert.assertTrue(timing.awaitLatch(connectedLatch)); timing.sleepABit(); Assert.assertTrue(node.waitForInitialCreate(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); server.close(); timing.sleepABit(); server = new TestingServer(server.getPort()); timing.sleepABit(); Assert.assertTrue(timing.awaitLatch(reconnectedLatch)); timing.sleepABit(); Assert.assertEquals(lastState.get(), ConnectionState.RECONNECTED); } finally { CloseableUtils.closeQuietly(client); } } }000077500000000000000000000000001245521677600340745ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queueQueueItemSerializer.java000066400000000000000000000022271245521677600406770ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; class QueueItemSerializer implements QueueSerializer { @Override public byte[] serialize(TestQueueItem item) { return item.str.getBytes(); } @Override public TestQueueItem deserialize(byte[] bytes) { return new TestQueueItem(new String(bytes)); } } QueueTestProducer.java000066400000000000000000000031071245521677600403700ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import java.util.concurrent.Callable; public class QueueTestProducer implements Callable { private final DistributedQueue queue; private final int itemQty; private final int startIndex; public QueueTestProducer(DistributedQueue queue, int itemQty, int startIndex) { this.queue = queue; this.itemQty = itemQty; this.startIndex = startIndex; } @Override public Void call() throws Exception { int count = 0; while ( !Thread.currentThread().isInterrupted() && (count < itemQty) ) { queue.put(new TestQueueItem(Integer.toString(count + startIndex))); ++count; } return null; } } TestBoundedDistributedQueue.java000066400000000000000000000242431245521677600423740ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.imps.CuratorFrameworkState; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; public class TestBoundedDistributedQueue extends BaseClassForTests { private static final QueueSerializer serializer = new QueueSerializer() { @Override public byte[] serialize(String item) { return item.getBytes(); } @Override public String deserialize(byte[] bytes) { return new String(bytes); } }; @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") @Test public void testMulti() throws Exception { final String PATH = "/queue"; final int CLIENT_QTY = 4; final int MAX_ITEMS = 10; final int ADD_ITEMS = MAX_ITEMS * 100; final int SLOP_FACTOR = 2; final QueueConsumer consumer = new QueueConsumer() { @Override public void consumeMessage(String message) throws Exception { Thread.sleep(10); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; final Timing timing = new Timing(); final ExecutorService executor = Executors.newCachedThreadPool(); ExecutorCompletionService completionService = new ExecutorCompletionService(executor); final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); client.create().forPath(PATH); final CountDownLatch isWaitingLatch = new CountDownLatch(1); final AtomicBoolean isDone = new AtomicBoolean(false); final List counts = new CopyOnWriteArrayList(); final Object lock = new Object(); executor.submit ( new Callable() { @Override public Void call() throws Exception { Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { synchronized(lock) { lock.notifyAll(); } } }; while ( !Thread.currentThread().isInterrupted() && client.getState() == CuratorFrameworkState.STARTED && !isDone.get() ) { synchronized(lock) { int size = client.getChildren().usingWatcher(watcher).forPath(PATH).size(); counts.add(size); isWaitingLatch.countDown(); lock.wait(); } } return null; } } ); isWaitingLatch.await(); for ( int i = 0; i < CLIENT_QTY; ++i ) { final int index = i; completionService.submit ( new Callable() { @Override public Void call() throws Exception { CuratorFramework client = null; DistributedQueue queue = null; try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); queue = QueueBuilder.builder(client, consumer, serializer, PATH).executor(executor).maxItems(MAX_ITEMS).putInBackground(false).lockPath("/locks").buildQueue(); queue.start(); for ( int i = 0; i < ADD_ITEMS; ++i ) { queue.put("" + index + "-" + i); } } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } return null; } } ); } for ( int i = 0; i < CLIENT_QTY; ++i ) { completionService.take().get(); } isDone.set(true); synchronized(lock) { lock.notifyAll(); } for ( int count : counts ) { Assert.assertTrue(count <= (MAX_ITEMS * SLOP_FACTOR), counts.toString()); } } finally { executor.shutdownNow(); CloseableUtils.closeQuietly(client); } } @Test public void testSimple() throws Exception { Timing timing = new Timing(); DistributedQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); final List messages = new CopyOnWriteArrayList(); final CountDownLatch latch = new CountDownLatch(2); final Semaphore semaphore = new Semaphore(0); QueueConsumer consumer = new QueueConsumer() { @Override public void consumeMessage(String message) throws Exception { messages.add(message); semaphore.acquire(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; queue = QueueBuilder.builder(client, consumer, serializer, "/queue").executor(Executors.newSingleThreadExecutor()).maxItems(1).buildQueue(); queue.start(); QueuePutListener listener = new QueuePutListener() { @Override public void putCompleted(String item) { latch.countDown(); } @Override public void putMultiCompleted(MultiItem items) { } }; queue.getPutListenerContainer().addListener(listener); Assert.assertTrue(queue.put("1", timing.milliseconds(), TimeUnit.MILLISECONDS)); // should end up in consumer Assert.assertTrue(queue.put("2", timing.milliseconds(), TimeUnit.MILLISECONDS)); // should sit blocking in DistributedQueue Assert.assertTrue(timing.awaitLatch(latch)); timing.sleepABit(); Assert.assertFalse(queue.put("3", timing.multiple(.5).milliseconds(), TimeUnit.MILLISECONDS)); semaphore.release(100); Assert.assertTrue(queue.put("3", timing.milliseconds(), TimeUnit.MILLISECONDS)); Assert.assertTrue(queue.put("4", timing.milliseconds(), TimeUnit.MILLISECONDS)); Assert.assertTrue(queue.put("5", timing.milliseconds(), TimeUnit.MILLISECONDS)); for ( int i = 0; i < 5; ++i ) { if ( messages.size() == 3 ) { break; } timing.sleepABit(); } timing.sleepABit(); Assert.assertEquals(messages, Arrays.asList("1", "2", "3", "4", "5")); } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } } TestDistributedDelayQueue.java000066400000000000000000000205031245521677600420450ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.Timing; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.TimeUnit; public class TestDistributedDelayQueue extends BaseClassForTests { @Test public void testLateAddition() throws Exception { Timing timing = new Timing(); DistributedDelayQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); queue = QueueBuilder.builder(client, consumer, new LongSerializer(), "/test").buildDelayQueue(); queue.start(); queue.put(1L, System.currentTimeMillis() + Integer.MAX_VALUE); // never come out Long value = consumer.take(1, TimeUnit.SECONDS); Assert.assertNull(value); queue.put(2L, System.currentTimeMillis()); value = consumer.take(timing.seconds(), TimeUnit.SECONDS); Assert.assertEquals(value, Long.valueOf(2)); value = consumer.take(1, TimeUnit.SECONDS); Assert.assertNull(value); } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test public void testBasic() throws Exception { Timing timing = new Timing(); DistributedDelayQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); queue = QueueBuilder.builder(client, consumer, new LongSerializer(), "/test").buildDelayQueue(); queue.start(); queue.put(1L, System.currentTimeMillis() + 1000); Thread.sleep(100); Assert.assertEquals(consumer.size(), 0); // delay hasn't been reached Long value = consumer.take(timing.forWaiting().seconds(), TimeUnit.SECONDS); Assert.assertEquals(value, Long.valueOf(1)); } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test public void testSimple() throws Exception { final int QTY = 10; Timing timing = new Timing(); DistributedDelayQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); queue = QueueBuilder.builder(client, consumer, new LongSerializer(), "/test").buildDelayQueue(); queue.start(); Random random = new Random(); for ( int i = 0; i < QTY; ++i ) { long delay = System.currentTimeMillis() + random.nextInt(100); queue.put(delay, delay); } long lastValue = -1; for ( int i = 0; i < QTY; ++i ) { Long value = consumer.take(timing.forWaiting().seconds(), TimeUnit.SECONDS); Assert.assertNotNull(value); Assert.assertTrue(value >= lastValue); lastValue = value; } } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test public void testSorting() throws Exception { //Need to use a fairly large number to ensure that sorting can take some time. final int QTY = 1000; Timing timing = new Timing(); DistributedDelayQueue putQueue = null; DistributedDelayQueue getQueue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { putQueue = QueueBuilder.builder(client, null, new LongSerializer(), "/test2").putInBackground(false).buildDelayQueue(); putQueue.start(); Map data = new HashMap(); //Make the earliest a second into the future, so we can ensure that everything's //been added prior to the consumption starting. Otherwise it's possible to start //processing entries before they've all been added so the ordering will be //incorrect. long delay = System.currentTimeMillis() + 5000; for ( long i = 0; i < QTY; ++i ) { data.put(delay, i); //We want to make the elements close together but not exactly the same MS. delay += 1; } //Randomly sort the list List keys = new ArrayList(data.keySet()); Collections.shuffle(keys); //Put the messages onto the queue in random order, but with the appropriate //delay and value for ( Long key : keys ) { putQueue.put(data.get(key), key); } BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); getQueue = QueueBuilder.builder(client, consumer, new LongSerializer(), "/test2").putInBackground(false).buildDelayQueue(); getQueue.start(); long lastValue = -1; for ( int i = 0; i < QTY; ++i ) { Long value = consumer.take(6, TimeUnit.SECONDS); Assert.assertNotNull(value); Assert.assertEquals(value, new Long(lastValue + 1)); lastValue = value; } } finally { CloseableUtils.closeQuietly(putQueue); CloseableUtils.closeQuietly(getQueue); CloseableUtils.closeQuietly(client); } } private static class LongSerializer implements QueueSerializer { @Override public byte[] serialize(Long item) { return Long.toString(item).getBytes(); } @Override public Long deserialize(byte[] bytes) { return Long.parseLong(new String(bytes)); } } } TestDistributedIdQueue.java000066400000000000000000000112261245521677600413450ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import com.google.common.collect.Lists; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryOneTime; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.Test; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter"}) public class TestDistributedIdQueue extends BaseClassForTests { private static final String QUEUE_PATH = "/a/queue"; private static final QueueSerializer serializer = new QueueItemSerializer(); @Test public void testDeletingWithLock() throws Exception { DistributedIdQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { final CountDownLatch consumingLatch = new CountDownLatch(1); final CountDownLatch waitLatch = new CountDownLatch(1); QueueConsumer consumer = new QueueConsumer() { @Override public void consumeMessage(TestQueueItem message) throws Exception { consumingLatch.countDown(); waitLatch.await(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).lockPath("/locks").buildIdQueue(); queue.start(); queue.put(new TestQueueItem("test"), "id"); Assert.assertTrue(consumingLatch.await(10, TimeUnit.SECONDS)); // wait until consumer has it Assert.assertEquals(queue.remove("id"), 0); waitLatch.countDown(); } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test public void testOrdering() throws Exception { final int ITEM_QTY = 100; DistributedIdQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).buildIdQueue(); queue.start(); List ids = Lists.newArrayList(); for ( int i = 0; i < ITEM_QTY; ++i ) { String id = Double.toString(Math.random()); ids.add(id); queue.put(new TestQueueItem(id), id); } int iteration = 0; while ( consumer.size() < ITEM_QTY ) { Assert.assertTrue(++iteration < ITEM_QTY); Thread.sleep(1000); } int i = 0; for ( TestQueueItem item : consumer.getItems() ) { Assert.assertEquals(item.str, ids.get(i++)); } } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } } TestDistributedPriorityQueue.java000066400000000000000000000240271245521677600426350ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.Timing; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; public class TestDistributedPriorityQueue extends BaseClassForTests { @Test public void testMinItemsBeforeRefresh() throws Exception { DistributedPriorityQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { final int minItemsBeforeRefresh = 3; BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); queue = QueueBuilder.builder(client, consumer, new IntSerializer(), "/test").buildPriorityQueue(minItemsBeforeRefresh); queue.start(); for ( int i = 0; i < 10; ++i ) { queue.put(i, 10 + i); } Assert.assertEquals(consumer.take(1, TimeUnit.SECONDS), new Integer(0)); queue.put(1000, 1); // lower priority int count = 0; while ( consumer.take(1, TimeUnit.SECONDS) < 1000 ) { ++count; } Assert.assertTrue(Math.abs(minItemsBeforeRefresh - count) < minItemsBeforeRefresh, String.format("Diff: %d - min: %d", Math.abs(minItemsBeforeRefresh - count), minItemsBeforeRefresh)); // allows for some slack - testing that within a slop value the newly inserted item with lower priority comes out } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test public void testSortingWhileTaking() throws Exception { Timing timing = new Timing(); DistributedPriorityQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { final BlockingQueue blockingQueue = new SynchronousQueue(); QueueConsumer consumer = new QueueConsumer() { @Override public void consumeMessage(Integer message) throws Exception { blockingQueue.put(message); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; queue = QueueBuilder.builder(client, consumer, new IntSerializer(), "/test").buildPriorityQueue(0); queue.start(); for ( int i = 0; i < 10; ++i ) { queue.put(i, 10); } Assert.assertEquals(blockingQueue.poll(timing.seconds(), TimeUnit.SECONDS), new Integer(0)); timing.sleepABit(); queue.put(1000, 1); // lower priority timing.sleepABit(); Assert.assertEquals(blockingQueue.poll(timing.seconds(), TimeUnit.SECONDS), new Integer(1)); // is in consumer already Assert.assertEquals(blockingQueue.poll(timing.seconds(), TimeUnit.SECONDS), new Integer(1000)); } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test public void testAdditions() throws Exception { DistributedPriorityQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { final CountDownLatch latch = new CountDownLatch(1); QueueSerializer serializer = new IntSerializer() { @Override public Integer deserialize(byte[] bytes) { // gets called in the Queue's event processing thread try { latch.await(); } catch ( InterruptedException e ) { // ignore } return super.deserialize(bytes); } }; BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); queue = QueueBuilder.builder(client, consumer, serializer, "/test").buildPriorityQueue(1); queue.start(); for ( int i = 0; i < 10; ++i ) { queue.put(10, 10); if ( i == 0 ) { queue.put(1, 1); latch.countDown(); } } assertOrdering(consumer, 10); } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test public void testSimple() throws Exception { List nums = new ArrayList(); Timing timing = new Timing(); DistributedPriorityQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { final CountDownLatch hasConsumedLatch = new CountDownLatch(1); final CountDownLatch okToConsumeLatch = new CountDownLatch(1); BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)) { @Override public void consumeMessage(Integer message) throws Exception { hasConsumedLatch.countDown(); okToConsumeLatch.await(); super.consumeMessage(message); } }; queue = QueueBuilder.builder(client, consumer, new IntSerializer(), "/test").buildPriorityQueue(0); queue.start(); nums.add(Integer.MIN_VALUE); queue.put(Integer.MIN_VALUE, Integer.MIN_VALUE); // the queue background thread will be blocking with the first item - make sure it's the lowest value Assert.assertTrue(timing.awaitLatch(hasConsumedLatch)); Random random = new Random(); for ( int i = 0; i < 100; ++i ) { int priority = random.nextInt(); nums.add(priority); queue.put(priority, priority); } while ( queue.getCache().getData().children.size() < (nums.size() - 1) ) // -1 because the first message has already been consumed { timing.sleepABit(); // wait for the cache to catch up } okToConsumeLatch.countDown(); assertOrdering(consumer, nums.size()); } catch ( AssertionError e ) { StringBuilder message = new StringBuilder(e.getMessage()); for ( int i : nums ) { message.append(i).append("\t").append(DistributedPriorityQueue.priorityToString(i)).append("\n"); } Assert.fail(message.toString()); } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } private void assertOrdering(BlockingQueueConsumer consumer, int qty) throws Exception { int previous = 0; for ( int i = 0; i < qty; ++i ) { Integer value = consumer.take(10, TimeUnit.SECONDS); Assert.assertNotNull(value); if ( i > 0 ) { Assert.assertTrue(value >= previous, String.format("Value: (%d:%s) Previous: (%d:%s)", value, DistributedPriorityQueue.priorityToString(value), previous, DistributedPriorityQueue.priorityToString(previous))); } previous = value; } } private static class IntSerializer implements QueueSerializer { @Override public byte[] serialize(Integer item) { return Integer.toString(item).getBytes(); } @Override public Integer deserialize(byte[] bytes) { return Integer.parseInt(new String(bytes)); } } } TestDistributedQueue.java000066400000000000000000000725351245521677600411020ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.imps.CuratorFrameworkState; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.Timing; import org.apache.zookeeper.CreateMode; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter"}) public class TestDistributedQueue extends BaseClassForTests { private static final String QUEUE_PATH = "/a/queue"; private static final QueueSerializer serializer = new QueueItemSerializer(); @Test public void testRetryAfterFailure_Curator56() throws Exception { /* https://issues.apache.org/jira/browse/CURATOR-56 This tests against ever growing node name bug */ DistributedQueue queue = null; final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { final int RETRY_COUNT = 1; final CountDownLatch retryCounter = new CountDownLatch(RETRY_COUNT + 1); final List names = new ArrayList(); QueueConsumer consumer = new QueueConsumer() { @Override public void consumeMessage(TestQueueItem messsage) throws Exception { List queueItems = client.getChildren().forPath(QUEUE_PATH); names.add(queueItems.get(0)); if (retryCounter.getCount() > 1) { retryCounter.countDown(); throw new Exception("Something went wrong"); } else { retryCounter.countDown(); } } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH) .lockPath("/lock") .buildQueue(); queue.start(); queue.put(new TestQueueItem("test")); retryCounter.await(10, TimeUnit.SECONDS); Assert.assertEquals(retryCounter.getCount(), 0, "Queue item was not consumed. Retry counter is " + retryCounter.getCount()); Assert.assertEquals(names.size(), 2); Assert.assertEquals(names.get(0).length(), names.get(1).length()); } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test public void testCustomExecutor() throws Exception { final int ITERATIONS = 1000; Timing timing = new Timing(); DistributedQueue queue = null; final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { final CountDownLatch latch = new CountDownLatch(ITERATIONS); QueueConsumer consumer = new QueueConsumer() { @Override public void consumeMessage(String message) throws Exception { latch.countDown(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; QueueSerializer serializer = new QueueSerializer() { @Override public byte[] serialize(String item) { return item.getBytes(); } @Override public String deserialize(byte[] bytes) { return new String(bytes); } }; Executor executor = Executors.newCachedThreadPool(); final Set used = Sets.newHashSet(); final Set doubleUsed = Sets.newHashSet(); queue = new DistributedQueue ( client, consumer, serializer, QUEUE_PATH, QueueBuilder.defaultThreadFactory, executor, Integer.MAX_VALUE, false, "/lock", QueueBuilder.NOT_SET, true, 5000 ) { @SuppressWarnings("SimplifiableConditionalExpression") @Override protected boolean processWithLockSafety(String itemNode, DistributedQueue.ProcessType type) throws Exception { if ( used.contains(itemNode) ) { doubleUsed.add(itemNode); } else { used.add(itemNode); } return (client.getState() == CuratorFrameworkState.STARTED) ? super.processWithLockSafety(itemNode, type) : false; } }; queue.start(); for ( int i = 0; i < ITERATIONS; ++i ) { queue.put(Integer.toString(i)); } Assert.assertTrue(timing.awaitLatch(latch)); Assert.assertTrue(doubleUsed.size() == 0, doubleUsed.toString()); } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test public void testPutListener() throws Exception { final int itemQty = 10; DistributedQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).buildQueue(); queue.start(); QueueTestProducer producer = new QueueTestProducer(queue, itemQty, 0); final AtomicInteger listenerCalls = new AtomicInteger(0); QueuePutListener listener = new QueuePutListener() { @Override public void putCompleted(TestQueueItem item) { listenerCalls.incrementAndGet(); } @Override public void putMultiCompleted(MultiItem items) { } }; queue.getPutListenerContainer().addListener(listener); ExecutorService service = Executors.newCachedThreadPool(); service.submit(producer); int iteration = 0; while ( consumer.size() < itemQty ) { Assert.assertTrue(++iteration < 10); Thread.sleep(1000); } int i = 0; for ( TestQueueItem item : consumer.getItems() ) { Assert.assertEquals(item.str, Integer.toString(i++)); } Assert.assertEquals(listenerCalls.get(), itemQty); } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test public void testErrorMode() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { final AtomicReference latch = new AtomicReference(new CountDownLatch(1)); final AtomicInteger count = new AtomicInteger(0); QueueConsumer consumer = new QueueConsumer() { @Override public void consumeMessage(TestQueueItem message) throws Exception { if ( count.incrementAndGet() < 2 ) { throw new Exception(); } latch.get().countDown(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; DistributedQueue queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).lockPath("/locks").buildQueue(); try { queue.start(); TestQueueItem item = new TestQueueItem("1"); queue.put(item); Assert.assertTrue(timing.awaitLatch(latch.get())); Assert.assertEquals(count.get(), 2); queue.setErrorMode(ErrorMode.DELETE); count.set(0); latch.set(new CountDownLatch(1)); item = new TestQueueItem("1"); queue.put(item); Assert.assertFalse(latch.get().await(5, TimeUnit.SECONDS)); // consumer should get called only once Assert.assertEquals(count.get(), 1); } finally { queue.close(); } } finally { client.close(); } } @Test public void testNoDuplicateProcessing() throws Exception { final int itemQty = 1000; final int consumerQty = 4; Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); client.start(); try { DistributedQueue producerQueue = QueueBuilder.builder(client, null, serializer, QUEUE_PATH).buildQueue(); try { producerQueue.start(); for ( int i = 0; i < itemQty; ++i ) { TestQueueItem item = new TestQueueItem(Integer.toString(i)); producerQueue.put(item); } producerQueue.flushPuts(timing.multiple(2).seconds(), TimeUnit.SECONDS); } finally { producerQueue.close(); } } finally { client.close(); } final Set consumedMessages = Sets.newHashSet(); final Set duplicateMessages = Sets.newHashSet(); final CountDownLatch latch = new CountDownLatch(itemQty); List> consumers = Lists.newArrayList(); List consumerClients = Lists.newArrayList(); try { final QueueConsumer ourQueue = new QueueConsumer() { @Override public void consumeMessage(TestQueueItem message) { synchronized(consumedMessages) { if ( consumedMessages.contains(message.str) ) { duplicateMessages.add(message.str); } consumedMessages.add(message.str); } latch.countDown(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; for ( int i = 0; i < consumerQty; ++i ) { CuratorFramework thisClient = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); consumerClients.add(thisClient); thisClient.start(); DistributedQueue thisConsumer = QueueBuilder.builder(thisClient, ourQueue, serializer, QUEUE_PATH). lockPath("/a/locks"). buildQueue(); consumers.add(thisConsumer); } for ( DistributedQueue consumer : consumers ) { consumer.start(); } timing.awaitLatch(latch); Assert.assertTrue(duplicateMessages.size() == 0, duplicateMessages.toString()); } finally { for ( DistributedQueue consumer : consumers ) { CloseableUtils.closeQuietly(consumer); } for ( CuratorFramework curatorFramework : consumerClients ) { CloseableUtils.closeQuietly(curatorFramework); } } } @Test public void testSafetyWithCrash() throws Exception { final int itemQty = 100; DistributedQueue producerQueue = null; DistributedQueue consumerQueue1 = null; DistributedQueue consumerQueue2 = null; CuratorFramework producerClient = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); CuratorFramework consumerClient1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); CuratorFramework consumerClient2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { producerClient.start(); consumerClient1.start(); consumerClient2.start(); ExecutorService service = Executors.newCachedThreadPool(); // make the producer queue { producerQueue = QueueBuilder.builder(producerClient, null, serializer, QUEUE_PATH).buildQueue(); producerQueue.start(); QueueTestProducer producer = new QueueTestProducer(producerQueue, itemQty, 0); service.submit(producer); } final Set takenItems = Sets.newTreeSet(); final Set takenItemsForConsumer1 = Sets.newTreeSet(); final Set takenItemsForConsumer2 = Sets.newTreeSet(); final AtomicReference thrownItemFromConsumer1 = new AtomicReference(null); // make the first consumer queue { final QueueConsumer ourQueue = new QueueConsumer() { @Override public void consumeMessage(TestQueueItem message) throws Exception { synchronized(takenItems) { if ( takenItems.size() > 10 ) { thrownItemFromConsumer1.set(message); throw new Exception("dummy"); // simulate a crash } } addToTakenItems(message, takenItems, itemQty); synchronized(takenItemsForConsumer1) { takenItemsForConsumer1.add(message); } Thread.sleep((long)(Math.random() * 5)); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; consumerQueue1 = QueueBuilder.builder(consumerClient1, ourQueue, serializer, QUEUE_PATH). lockPath("/a/locks"). buildQueue(); consumerQueue1.start(); } // make the second consumer queue { final QueueConsumer ourQueue = new QueueConsumer() { @Override public void consumeMessage(TestQueueItem message) throws Exception { addToTakenItems(message, takenItems, itemQty); synchronized(takenItemsForConsumer2) { takenItemsForConsumer2.add(message); } Thread.sleep((long)(Math.random() * 5)); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; consumerQueue2 = QueueBuilder.builder(consumerClient2, ourQueue, serializer, QUEUE_PATH). lockPath("/a/locks"). buildQueue(); consumerQueue2.start(); } synchronized(takenItems) { while ( takenItems.size() < itemQty ) { takenItems.wait(1000); } } int i = 0; for ( TestQueueItem item : takenItems ) { Assert.assertEquals(item.str, Integer.toString(i++)); } Assert.assertNotNull(thrownItemFromConsumer1.get()); Assert.assertTrue((takenItemsForConsumer2.contains(thrownItemFromConsumer1.get()))); Assert.assertTrue(Sets.intersection(takenItemsForConsumer1, takenItemsForConsumer2).size() == 0); } finally { CloseableUtils.closeQuietly(producerQueue); CloseableUtils.closeQuietly(consumerQueue1); CloseableUtils.closeQuietly(consumerQueue2); CloseableUtils.closeQuietly(producerClient); CloseableUtils.closeQuietly(consumerClient1); CloseableUtils.closeQuietly(consumerClient2); } } private void addToTakenItems(TestQueueItem message, Set takenItems, int itemQty) { synchronized(takenItems) { takenItems.add(message); if ( takenItems.size() > itemQty ) { takenItems.notifyAll(); } } } @Test public void testSafetyBasic() throws Exception { final int itemQty = 10; DistributedQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { final BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH). lockPath("/a/locks"). buildQueue(); queue.start(); QueueTestProducer producer = new QueueTestProducer(queue, itemQty, 0); ExecutorService service = Executors.newCachedThreadPool(); service.submit(producer); final CountDownLatch latch = new CountDownLatch(1); service.submit ( new Callable() { @Override public Object call() throws Exception { for ( int i = 0; i < itemQty; ++i ) { TestQueueItem item = consumer.take(); Assert.assertEquals(item.str, Integer.toString(i)); } latch.countDown(); return null; } } ); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test public void testPutMulti() throws Exception { final int itemQty = 100; DistributedQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).buildQueue(); queue.start(); MultiItem items = new MultiItem() { private int index = 0; @Override public TestQueueItem nextItem() throws Exception { if ( index >= itemQty ) { return null; } return new TestQueueItem(Integer.toString(index++)); } }; queue.putMulti(items); for ( int i = 0; i < itemQty; ++i ) { TestQueueItem queueItem = consumer.take(1, TimeUnit.SECONDS); Assert.assertNotNull(queueItem); Assert.assertEquals(queueItem, new TestQueueItem(Integer.toString(i))); } } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test public void testMultiPutterSingleGetter() throws Exception { final int itemQty = 100; DistributedQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).buildQueue(); queue.start(); QueueTestProducer producer1 = new QueueTestProducer(queue, itemQty / 2, 0); QueueTestProducer producer2 = new QueueTestProducer(queue, ((itemQty + 1) / 2), itemQty / 2); ExecutorService service = Executors.newCachedThreadPool(); service.submit(producer1); service.submit(producer2); int iteration = 0; while ( consumer.size() < itemQty ) { Assert.assertTrue(++iteration < 10); Thread.sleep(1000); } List items = consumer.getItems(); Assert.assertEquals(com.google.common.collect.Sets.newHashSet(items).size(), items.size()); // check no duplicates } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test public void testFlush() throws Exception { final Timing timing = new Timing(); final CountDownLatch latch = new CountDownLatch(1); DistributedQueue queue = null; final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { final AtomicBoolean firstTime = new AtomicBoolean(true); queue = new DistributedQueue(client, null, serializer, "/test", new ThreadFactoryBuilder().build(), MoreExecutors.sameThreadExecutor(), 10, true, null, QueueBuilder.NOT_SET, true, 0) { @Override void internalCreateNode(final String path, final byte[] bytes, final BackgroundCallback callback) throws Exception { if ( firstTime.compareAndSet(true, false) ) { Executors.newSingleThreadExecutor().submit ( new Callable() { @Override public Object call() throws Exception { latch.await(); timing.sleepABit(); client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).inBackground(callback).forPath(path, bytes); return null; } } ); } else { super.internalCreateNode(path, bytes, callback); } } }; queue.start(); queue.put(new TestQueueItem("1")); Assert.assertFalse(queue.flushPuts(timing.forWaiting().seconds(), TimeUnit.SECONDS)); latch.countDown(); Assert.assertTrue(queue.flushPuts(timing.forWaiting().seconds(), TimeUnit.SECONDS)); } finally { if ( latch.getCount() > 0 ) { latch.countDown(); } CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test public void testSimple() throws Exception { final int itemQty = 10; DistributedQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).buildQueue(); queue.start(); QueueTestProducer producer = new QueueTestProducer(queue, itemQty, 0); ExecutorService service = Executors.newCachedThreadPool(); service.submit(producer); int iteration = 0; while ( consumer.size() < itemQty ) { Assert.assertTrue(++iteration < 10); Thread.sleep(1000); } int i = 0; for ( TestQueueItem item : consumer.getItems() ) { Assert.assertEquals(item.str, Integer.toString(i++)); } } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } } TestQueueItem.java000066400000000000000000000033421245521677600375040ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; class TestQueueItem implements Comparable { final String str; TestQueueItem(String str) { this.str = str; } @Override public int compareTo(TestQueueItem rhs) { if ( this == rhs ) { return 0; } int val = Integer.parseInt(str); int rhsVal = Integer.parseInt(rhs.str); int diff = val - rhsVal; return (diff < 0) ? -1 : ((diff > 0) ? 1 : 0); } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } TestQueueItem that = (TestQueueItem)o; return str.equals(that.str); } @Override public int hashCode() { return str.hashCode(); } } TestQueueSharder.java000066400000000000000000000230541245521677600402000ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import com.google.common.collect.Sets; import org.apache.commons.math.stat.descriptive.SummaryStatistics; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class TestQueueSharder extends BaseClassForTests { @Test public void testDistribution() throws Exception { final int threshold = 100; final int factor = 10; Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); QueueSharder> sharder = null; try { client.start(); final CountDownLatch latch = new CountDownLatch(1); QueueConsumer consumer = new QueueConsumer() { @Override public void consumeMessage(String message) throws Exception { latch.await(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; QueueAllocator> distributedQueueAllocator = makeAllocator(consumer); QueueSharderPolicies policies = QueueSharderPolicies.builder().newQueueThreshold(threshold).thresholdCheckMs(1).build(); sharder = new QueueSharder>(client, distributedQueueAllocator, "/queues", "/leader", policies); sharder.start(); for ( int i = 0; i < (factor * threshold); ++i ) { sharder.getQueue().put(Integer.toString(i)); Thread.sleep(5); } timing.forWaiting().sleepABit(); SummaryStatistics statistics = new SummaryStatistics(); for ( String path : sharder.getQueuePaths() ) { int numChildren = client.checkExists().forPath(path).getNumChildren(); Assert.assertTrue(numChildren > 0); Assert.assertTrue(numChildren >= (threshold * .1)); statistics.addValue(numChildren); } latch.countDown(); Assert.assertTrue(statistics.getMean() >= (threshold * .9)); } finally { timing.sleepABit(); // let queue clear CloseableUtils.closeQuietly(sharder); CloseableUtils.closeQuietly(client); } } @Test public void testSharderWatchSync() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); final BlockingQueueConsumer consumer = makeConsumer(null); QueueAllocator> distributedQueueAllocator = makeAllocator(consumer); QueueSharderPolicies policies = QueueSharderPolicies.builder().newQueueThreshold(2).thresholdCheckMs(1).build(); QueueSharder> sharder1 = new QueueSharder>(client, distributedQueueAllocator, "/queues", "/leader", policies); QueueSharder> sharder2 = new QueueSharder>(client, distributedQueueAllocator, "/queues", "/leader", policies); try { client.start(); sharder1.start(); sharder2.start(); for ( int i = 0; i < 20; ++i ) { sharder1.getQueue().put(Integer.toString(i)); } timing.sleepABit(); Assert.assertTrue((sharder1.getShardQty() > 1) || (sharder2.getShardQty() > 1)); timing.forWaiting().sleepABit(); Assert.assertEquals(sharder1.getShardQty(), sharder2.getShardQty()); } finally { timing.sleepABit(); // let queues clear CloseableUtils.closeQuietly(sharder1); CloseableUtils.closeQuietly(sharder2); CloseableUtils.closeQuietly(client); } } @Test public void testSimpleDistributedQueue() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); final CountDownLatch latch = new CountDownLatch(1); final BlockingQueueConsumer consumer = makeConsumer(latch); QueueAllocator> distributedQueueAllocator = makeAllocator(consumer); QueueSharderPolicies policies = QueueSharderPolicies.builder().newQueueThreshold(2).thresholdCheckMs(1).build(); QueueSharder> sharder = new QueueSharder>(client, distributedQueueAllocator, "/queues", "/leader", policies); try { client.start(); sharder.start(); sharder.getQueue().put("one"); sharder.getQueue().put("two"); sharder.getQueue().put("three"); sharder.getQueue().put("four"); latch.countDown(); timing.sleepABit(); sharder.getQueue().put("five"); sharder.getQueue().put("six"); sharder.getQueue().put("seven"); sharder.getQueue().put("eight"); timing.sleepABit(); Assert.assertTrue(sharder.getShardQty() > 1); Set consumed = Sets.newHashSet(); for ( int i = 0; i < 8; ++i ) { String s = consumer.take(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS); Assert.assertNotNull(s); consumed.add(s); } Assert.assertEquals(consumed, Sets.newHashSet("one", "two", "three", "four", "five", "six", "seven", "eight")); int shardQty = sharder.getShardQty(); sharder.close(); // check re-open sharder = new QueueSharder>(client, distributedQueueAllocator, "/queues", "/leader", policies); sharder.start(); Assert.assertEquals(sharder.getShardQty(), shardQty); } finally { CloseableUtils.closeQuietly(sharder); CloseableUtils.closeQuietly(client); } } private QueueAllocator> makeAllocator(final QueueConsumer consumer) { final QueueSerializer serializer = new QueueSerializer() { @Override public byte[] serialize(String item) { return item.getBytes(); } @Override public String deserialize(byte[] bytes) { return new String(bytes); } }; return new QueueAllocator>() { @Override public DistributedQueue allocateQueue(CuratorFramework client, String queuePath) { return QueueBuilder.builder(client, consumer, serializer, queuePath).buildQueue(); } }; } private BlockingQueueConsumer makeConsumer(final CountDownLatch latch) { ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; return new BlockingQueueConsumer(connectionStateListener) { @Override public void consumeMessage(String message) throws Exception { if ( latch != null ) { latch.await(); } super.consumeMessage(message); } }; } } TestSimpleDistributedQueue.java000066400000000000000000000322031245521677600422400ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.queue; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.testng.Assert; import org.testng.annotations.Test; import java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class TestSimpleDistributedQueue extends BaseClassForTests { @Test public void testPollWithTimeout() throws Exception { CuratorFramework clients[] = null; try { String dir = "/testOffer1"; final int num_clients = 1; clients = new CuratorFramework[num_clients]; SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; for ( int i = 0; i < clients.length; i++ ) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); } Assert.assertNull(queueHandles[0].poll(3, TimeUnit.SECONDS)); } finally { closeAll(clients); } } @Test public void testOffer1() throws Exception { CuratorFramework clients[] = null; try { String dir = "/testOffer1"; String testString = "Hello World"; final int num_clients = 1; clients = new CuratorFramework[num_clients]; SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; for ( int i = 0; i < clients.length; i++ ) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); } queueHandles[0].offer(testString.getBytes()); byte dequeuedBytes[] = queueHandles[0].remove(); assertEquals(new String(dequeuedBytes), testString); } finally { closeAll(clients); } } @Test public void testOffer2() throws Exception { CuratorFramework clients[] = null; try { String dir = "/testOffer2"; String testString = "Hello World"; final int num_clients = 2; clients = new CuratorFramework[num_clients]; SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; for ( int i = 0; i < clients.length; i++ ) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); } queueHandles[0].offer(testString.getBytes()); byte dequeuedBytes[] = queueHandles[1].remove(); assertEquals(new String(dequeuedBytes), testString); } finally { closeAll(clients); } } @Test public void testTake1() throws Exception { CuratorFramework clients[] = null; try { String dir = "/testTake1"; String testString = "Hello World"; final int num_clients = 1; clients = new CuratorFramework[num_clients]; SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; for ( int i = 0; i < clients.length; i++ ) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); } queueHandles[0].offer(testString.getBytes()); byte dequeuedBytes[] = queueHandles[0].take(); assertEquals(new String(dequeuedBytes), testString); } finally { closeAll(clients); } } @Test public void testRemova1() throws Exception { CuratorFramework clients[] = null; try { String dir = "/testRemove1"; final int num_clients = 1; clients = new CuratorFramework[num_clients]; SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; for ( int i = 0; i < clients.length; i++ ) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); } try { queueHandles[0].remove(); } catch ( NoSuchElementException e ) { return; } assertTrue(false); } finally { closeAll(clients); } } public void createNremoveMtest(String dir, int n, int m) throws Exception { CuratorFramework clients[] = null; try { String testString = "Hello World"; final int num_clients = 2; clients = new CuratorFramework[num_clients]; SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; for ( int i = 0; i < clients.length; i++ ) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); } for ( int i = 0; i < n; i++ ) { String offerString = testString + i; queueHandles[0].offer(offerString.getBytes()); } byte data[] = null; for ( int i = 0; i < m; i++ ) { data = queueHandles[1].remove(); } assertEquals(new String(data), testString + (m - 1)); } finally { closeAll(clients); } } @Test public void testRemove2() throws Exception { createNremoveMtest("/testRemove2", 10, 2); } @Test public void testRemove3() throws Exception { createNremoveMtest("/testRemove3", 1000, 1000); } public void createNremoveMelementTest(String dir, int n, int m) throws Exception { CuratorFramework clients[] = null; try { String testString = "Hello World"; final int num_clients = 2; clients = new CuratorFramework[num_clients]; SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; for ( int i = 0; i < clients.length; i++ ) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); } for ( int i = 0; i < n; i++ ) { String offerString = testString + i; queueHandles[0].offer(offerString.getBytes()); } for ( int i = 0; i < m; i++ ) { queueHandles[1].remove(); } assertEquals(new String(queueHandles[1].element()), testString + m); } finally { closeAll(clients); } } @Test public void testElement1() throws Exception { createNremoveMelementTest("/testElement1", 1, 0); } @Test public void testElement2() throws Exception { createNremoveMelementTest("/testElement2", 10, 2); } @Test public void testElement3() throws Exception { createNremoveMelementTest("/testElement3", 1000, 500); } @Test public void testElement4() throws Exception { createNremoveMelementTest("/testElement4", 1000, 1000 - 1); } @Test public void testTakeWait1() throws Exception { CuratorFramework clients[] = null; try { String dir = "/testTakeWait1"; final String testString = "Hello World"; final int num_clients = 1; clients = new CuratorFramework[num_clients]; final SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; for ( int i = 0; i < clients.length; i++ ) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); } final byte[] takeResult[] = new byte[1][]; Thread takeThread = new Thread() { public void run() { try { takeResult[0] = queueHandles[0].take(); } catch ( Exception e ) { // ignore } } }; takeThread.start(); Thread.sleep(1000); Thread offerThread = new Thread() { public void run() { try { queueHandles[0].offer(testString.getBytes()); } catch ( Exception e ) { // ignore } } }; offerThread.start(); offerThread.join(); takeThread.join(); assertTrue(takeResult[0] != null); assertEquals(new String(takeResult[0]), testString); } finally { closeAll(clients); } } @Test public void testTakeWait2() throws Exception { String dir = "/testTakeWait2"; final String testString = "Hello World"; final int num_clients = 1; final CuratorFramework clients[] = new CuratorFramework[num_clients]; final SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; for ( int i = 0; i < clients.length; i++ ) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); } int num_attempts = 2; for ( int i = 0; i < num_attempts; i++ ) { final byte[] takeResult[] = new byte[1][]; final String threadTestString = testString + i; Thread takeThread = new Thread() { public void run() { try { takeResult[0] = queueHandles[0].take(); } catch ( Exception e ) { // ignore } } }; takeThread.start(); Thread.sleep(1000); Thread offerThread = new Thread() { public void run() { try { queueHandles[0].offer(threadTestString.getBytes()); } catch ( Exception e ) { // ignore } } }; offerThread.start(); offerThread.join(); takeThread.join(); assertTrue(takeResult[0] != null); assertEquals(new String(takeResult[0]), threadTestString); } } private void closeAll(CuratorFramework[] clients) { if ( clients != null ) { for ( CuratorFramework c : clients ) { CloseableUtils.closeQuietly(c); } } } } 000077500000000000000000000000001245521677600342165ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/sharedTestSharedCount.java000066400000000000000000000244001245521677600401400ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/java/org/apache/curator/framework/recipes/shared/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.shared; import com.google.common.collect.Lists; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.testng.Assert; import org.testng.annotations.Test; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class TestSharedCount extends BaseClassForTests { @Test public void testMultiClients() throws Exception { final int CLIENT_QTY = 5; List>> futures = Lists.newArrayList(); final List clients = new CopyOnWriteArrayList(); final List counts = new CopyOnWriteArrayList(); try { final CountDownLatch startLatch = new CountDownLatch(CLIENT_QTY); final Semaphore semaphore = new Semaphore(0); ExecutorService service = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("Test-%d").build()); for ( int i = 0; i < CLIENT_QTY; ++i ) { Future> future = service.submit ( new Callable>() { @Override public List call() throws Exception { final List countList = Lists.newArrayList(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients.add(client); client.start(); SharedCount count = new SharedCount(client, "/count", 10); counts.add(count); final CountDownLatch latch = new CountDownLatch(1); count.addListener ( new SharedCountListener() { @Override public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception { if ( newCount < 0 ) { latch.countDown(); } else { countList.add(newCount); } semaphore.release(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } } ); count.start(); startLatch.countDown(); latch.await(); return countList; } } ); futures.add(future); } CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients.add(client); client.start(); Assert.assertTrue(startLatch.await(10, TimeUnit.SECONDS)); SharedCount count = new SharedCount(client, "/count", 10); counts.add(count); count.start(); List countList = Lists.newArrayList(); Random random = new Random(); for ( int i = 0; i < 100; ++i ) { Thread.sleep(random.nextInt(10)); int next = random.nextInt(100); countList.add(next); count.setCount(next); Assert.assertTrue(semaphore.tryAcquire(CLIENT_QTY, 10, TimeUnit.SECONDS)); } count.setCount(-1); for ( Future> future : futures ) { List thisCountList = future.get(); Assert.assertEquals(thisCountList, countList); } } finally { for ( SharedCount count : counts ) { CloseableUtils.closeQuietly(count); } for ( CuratorFramework client : clients ) { CloseableUtils.closeQuietly(client); } } } @Test public void testSimple() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); SharedCount count = new SharedCount(client, "/count", 0); try { client.start(); count.start(); Assert.assertTrue(count.trySetCount(1)); Assert.assertTrue(count.trySetCount(2)); Assert.assertTrue(count.trySetCount(10)); Assert.assertEquals(count.getCount(), 10); } finally { CloseableUtils.closeQuietly(count); CloseableUtils.closeQuietly(client); } } @Test public void testSimpleVersioned() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); SharedCount count = new SharedCount(client, "/count", 0); client.start(); try { count.start(); VersionedValue current = count.getVersionedValue(); Assert.assertEquals(current.getVersion(), 0); Assert.assertTrue(count.trySetCount(current, 1)); current = count.getVersionedValue(); Assert.assertEquals(current.getVersion(), 1); Assert.assertEquals(count.getCount(), 1); Assert.assertTrue(count.trySetCount(current, 5)); current = count.getVersionedValue(); Assert.assertEquals(current.getVersion(), 2); Assert.assertEquals(count.getCount(), 5); Assert.assertTrue(count.trySetCount(current, 10)); current = count.getVersionedValue(); Assert.assertEquals(current.getVersion(), 3); Assert.assertEquals(count.getCount(), 10); // Wrong value Assert.assertFalse(count.trySetCount(new VersionedValue(3, 20), 7)); // Wrong version Assert.assertFalse(count.trySetCount(new VersionedValue(10, 10), 7)); // Server changed client.setData().forPath("/count", SharedCount.toBytes(88)); Assert.assertFalse(count.trySetCount(current, 234)); } finally { CloseableUtils.closeQuietly(count); CloseableUtils.closeQuietly(client); } } @Test public void testMultiClientVersioned() throws Exception { Timing timing = new Timing(); CuratorFramework client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); CuratorFramework client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); SharedCount count1 = new SharedCount(client1, "/count", 0); SharedCount count2 = new SharedCount(client2, "/count", 0); try { client1.start(); client2.start(); count1.start(); count2.start(); VersionedValue versionedValue = count1.getVersionedValue(); Assert.assertTrue(count1.trySetCount(versionedValue, 10)); timing.sleepABit(); versionedValue = count2.getVersionedValue(); Assert.assertTrue(count2.trySetCount(versionedValue, 20)); timing.sleepABit(); VersionedValue versionedValue1 = count1.getVersionedValue(); VersionedValue versionedValue2 = count2.getVersionedValue(); Assert.assertTrue(count2.trySetCount(versionedValue2, 30)); Assert.assertFalse(count1.trySetCount(versionedValue1, 40)); versionedValue1 = count1.getVersionedValue(); Assert.assertTrue(count1.trySetCount(versionedValue1, 40)); } finally { CloseableUtils.closeQuietly(count2); CloseableUtils.closeQuietly(count1); CloseableUtils.closeQuietly(client2); CloseableUtils.closeQuietly(client1); } } } curator-apache-curator-2.7.1/curator-recipes/src/test/resources/000077500000000000000000000000001245521677600250025ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-recipes/src/test/resources/log4j.properties000066400000000000000000000021131245521677600301340ustar00rootroot00000000000000# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # log4j.rootLogger=ERROR, console log4j.logger.org.apache.curator=DEBUG, console log4j.additivity.org.apache.curator=false log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%-5p %c %x %m [%t]%n curator-apache-curator-2.7.1/curator-test/000077500000000000000000000000001245521677600205475ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-test/LICENSE000066400000000000000000000261361245521677600215640ustar00rootroot00000000000000 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. curator-apache-curator-2.7.1/curator-test/NOTICE000066400000000000000000000002501245521677600214500ustar00rootroot00000000000000Apache Curator Copyright 2013-2014 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). curator-apache-curator-2.7.1/curator-test/pom.xml000066400000000000000000000036431245521677600220720ustar00rootroot00000000000000 4.0.0 org.apache.curator apache-curator 2.7.1 curator-test 2.7.1 Curator Testing Unit testing utilities. 2011 org.javassist javassist org.apache.commons commons-math org.testng testng provided curator-apache-curator-2.7.1/curator-test/src/000077500000000000000000000000001245521677600213365ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-test/src/main/000077500000000000000000000000001245521677600222625ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-test/src/main/java/000077500000000000000000000000001245521677600232035ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-test/src/main/java/org/000077500000000000000000000000001245521677600237725ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-test/src/main/java/org/apache/000077500000000000000000000000001245521677600252135ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-test/src/main/java/org/apache/curator/000077500000000000000000000000001245521677600266725ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-test/src/main/java/org/apache/curator/test/000077500000000000000000000000001245521677600276515ustar00rootroot00000000000000BaseClassForTests.java000066400000000000000000000072721245521677600337770ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-test/src/main/java/org/apache/curator/test/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.test; import org.testng.IRetryAnalyzer; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import java.net.BindException; import java.util.concurrent.atomic.AtomicBoolean; public class BaseClassForTests { protected TestingServer server; private static final int RETRY_WAIT_MS = 5000; private static final String INTERNAL_PROPERTY_DONT_LOG_CONNECTION_ISSUES; static { String s = null; try { // use reflection to avoid adding a circular dependency in the pom s = (String)Class.forName("org.apache.curator.utils.DebugUtils").getField("PROPERTY_DONT_LOG_CONNECTION_ISSUES").get(null); } catch ( Exception e ) { e.printStackTrace(); } INTERNAL_PROPERTY_DONT_LOG_CONNECTION_ISSUES = s; } @BeforeSuite(alwaysRun = true) public void beforeSuite(ITestContext context) { for ( ITestNGMethod method : context.getAllTestMethods() ) { method.setRetryAnalyzer(new RetryTest()); } } @BeforeMethod public void setup() throws Exception { if ( INTERNAL_PROPERTY_DONT_LOG_CONNECTION_ISSUES != null ) { System.setProperty(INTERNAL_PROPERTY_DONT_LOG_CONNECTION_ISSUES, "true"); } while ( server == null ) { try { server = new TestingServer(); } catch ( BindException e ) { System.err.println("Getting bind exception - retrying to allocate server"); server = null; } } } @AfterMethod public void teardown() throws Exception { server.close(); server = null; } private static class RetryTest implements IRetryAnalyzer { private final AtomicBoolean hasBeenRetried = new AtomicBoolean(false); @Override public boolean retry(ITestResult result) { boolean isRetrying = hasBeenRetried.compareAndSet(false, true); if ( isRetrying ) { System.err.println(String.format("Waiting " + RETRY_WAIT_MS + " ms and retrying test. Name: %s - TestName: %s ", result.getName(), result.getTestName())); try { Thread.sleep(RETRY_WAIT_MS); } catch ( InterruptedException e ) { System.err.println(String.format("Retry interrupted. Name: %s - TestName: %s ", result.getName(), result.getTestName())); Thread.currentThread().interrupt(); isRetrying = false; } } return isRetrying; } } } curator-apache-curator-2.7.1/curator-test/src/main/java/org/apache/curator/test/ByteCodeRewrite.java000066400000000000000000000060131245521677600335540ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.test; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; public class ByteCodeRewrite { public static void apply() { // NOP - only needed so that static initializer is run } static { /* This ugliness is necessary. There is no way to tell ZK to not register JMX beans. Something in the shutdown of a QuorumPeer causes the state of the MBeanRegistry to get confused and generates an assert Exception. */ ClassPool pool = ClassPool.getDefault(); try { pool.appendClassPath(new javassist.LoaderClassPath(TestingCluster.class.getClassLoader())); // re: https://github.com/Netflix/curator/issues/11 try { CtClass cc = pool.get("org.apache.zookeeper.server.ZooKeeperServer"); fixMethods(cc, "registerJMX", "unregisterJMX"); } catch ( NotFoundException ignore ) { // ignore } try { CtClass cc = pool.get("org.apache.zookeeper.server.quorum.LearnerZooKeeperServer"); fixMethods(cc, "registerJMX", "unregisterJMX"); } catch ( NotFoundException ignore ) { // ignore } try { CtClass cc = pool.get("org.apache.zookeeper.jmx.MBeanRegistry"); fixMethods(cc, "register", "unregister"); } catch ( NotFoundException ignore ) { // ignore } } catch ( Exception e ) { e.printStackTrace(); } } private static void fixMethods(CtClass cc, String... methodNames) throws CannotCompileException { for ( CtMethod method : cc.getDeclaredMethods() ) { for ( String methodName : methodNames ) { if ( method.getName().equals(methodName) ) { method.setBody(null); } } } cc.toClass(); } } curator-apache-curator-2.7.1/curator-test/src/main/java/org/apache/curator/test/DirectoryUtils.java000066400000000000000000000035111245521677600335010ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.test; import com.google.common.base.Preconditions; import java.io.File; import java.io.IOException; // copied from Google Guava as these methods are now deprecated // NOTE: removed the line of code documented: Symbolic links will have different canonical and absolute paths public class DirectoryUtils { public static void deleteRecursively(File file) throws IOException { if (file.isDirectory()) { deleteDirectoryContents(file); } if (!file.delete()) { throw new IOException("Failed to delete " + file); } } public static void deleteDirectoryContents(File directory) throws IOException { Preconditions.checkArgument(directory.isDirectory(), "Not a directory: %s", directory); File[] files = directory.listFiles(); if (files == null) { throw new IOException("Error listing files for " + directory); } for (File file : files) { deleteRecursively(file); } } } curator-apache-curator-2.7.1/curator-test/src/main/java/org/apache/curator/test/InstanceSpec.java000066400000000000000000000167071245521677600331060ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.test; import com.google.common.io.Files; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.UnknownHostException; import java.util.concurrent.atomic.AtomicInteger; /** * Abstracts one of the servers in the ensemble */ public class InstanceSpec { private static final AtomicInteger nextServerId = new AtomicInteger(1); private static final String localhost; static { String address = "localhost"; try { // This is a workaround for people using OS X Lion. On Lion when a process tries to connect to a link-local // address it takes 5 seconds to establish the connection for some reason. So instead of using 'localhost' // which could return the link-local address randomly, we'll manually resolve it and look for an address to // return that isn't link-local. If for some reason we can't find an address that isn't link-local then // we'll fall back to the default lof just looking up 'localhost'. for ( InetAddress a : InetAddress.getAllByName("localhost") ) { if ( !a.isLinkLocalAddress() ) { address = a.getHostAddress(); break; } } } catch ( UnknownHostException e ) { // Something went wrong, just default to the existing approach of using 'localhost'. } localhost = address; } private final File dataDirectory; private final int port; private final int electionPort; private final int quorumPort; private final boolean deleteDataDirectoryOnClose; private final int serverId; private final int tickTime; private final int maxClientCnxns; public static InstanceSpec newInstanceSpec() { return new InstanceSpec(null, -1, -1, -1, true, -1, -1, -1); } public static int getRandomPort() { ServerSocket server = null; try { server = new ServerSocket(0); return server.getLocalPort(); } catch ( IOException e ) { throw new Error(e); } finally { if ( server != null ) { try { server.close(); } catch ( IOException ignore ) { // ignore } } } } /** * @param dataDirectory where to store data/logs/etc. * @param port the port to listen on - each server in the ensemble must use a unique port * @param electionPort the electionPort to listen on - each server in the ensemble must use a unique electionPort * @param quorumPort the quorumPort to listen on - each server in the ensemble must use a unique quorumPort * @param deleteDataDirectoryOnClose if true, the data directory will be deleted when {@link TestingCluster#close()} is called * @param serverId the server ID for the instance */ public InstanceSpec(File dataDirectory, int port, int electionPort, int quorumPort, boolean deleteDataDirectoryOnClose, int serverId) { this(dataDirectory, port, electionPort, quorumPort, deleteDataDirectoryOnClose, serverId, -1, -1); } /** * @param dataDirectory where to store data/logs/etc. * @param port the port to listen on - each server in the ensemble must use a unique port * @param electionPort the electionPort to listen on - each server in the ensemble must use a unique electionPort * @param quorumPort the quorumPort to listen on - each server in the ensemble must use a unique quorumPort * @param deleteDataDirectoryOnClose if true, the data directory will be deleted when {@link TestingCluster#close()} is called * @param serverId the server ID for the instance * @param tickTime tickTime. Set -1 to used fault server configuration * @param maxClientCnxns max number of client connections from the same IP. Set -1 to use default server configuration */ public InstanceSpec(File dataDirectory, int port, int electionPort, int quorumPort, boolean deleteDataDirectoryOnClose, int serverId, int tickTime, int maxClientCnxns) { this.dataDirectory = (dataDirectory != null) ? dataDirectory : Files.createTempDir(); this.port = (port >= 0) ? port : getRandomPort(); this.electionPort = (electionPort >= 0) ? electionPort : getRandomPort(); this.quorumPort = (quorumPort >= 0) ? quorumPort : getRandomPort(); this.deleteDataDirectoryOnClose = deleteDataDirectoryOnClose; this.serverId = (serverId >= 0) ? serverId : nextServerId.getAndIncrement(); this.tickTime = (tickTime > 0 ? tickTime : -1); // -1 to set default value this.maxClientCnxns = (maxClientCnxns >= 0 ? maxClientCnxns : -1); // -1 to set default value } public int getServerId() { return serverId; } public File getDataDirectory() { return dataDirectory; } public int getPort() { return port; } public int getElectionPort() { return electionPort; } public int getQuorumPort() { return quorumPort; } public String getConnectString() { return localhost + ":" + port; } public int getTickTime() { return tickTime; } public int getMaxClientCnxns() { return maxClientCnxns; } public boolean deleteDataDirectoryOnClose() { return deleteDataDirectoryOnClose; } @Override public String toString() { return "InstanceSpec{" + "dataDirectory=" + dataDirectory + ", port=" + port + ", electionPort=" + electionPort + ", quorumPort=" + quorumPort + ", deleteDataDirectoryOnClose=" + deleteDataDirectoryOnClose + ", serverId=" + serverId + ", tickTime=" + tickTime + ", maxClientCnxns=" + maxClientCnxns + "} " + super.toString(); } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } InstanceSpec that = (InstanceSpec)o; return port == that.port; } @Override public int hashCode() { return port; } } curator-apache-curator-2.7.1/curator-test/src/main/java/org/apache/curator/test/KillSession.java000066400000000000000000000103161245521677600327540ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.test; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** *

* Utility to simulate a ZK session dying. See: ZooKeeper FAQ *

* *
* In the case of testing we want to cause a problem, so to explicitly expire a session an * application connects to ZooKeeper, saves the session id and password, creates another * ZooKeeper handle with that id and password, and then closes the new handle. Since both * handles reference the same session, the close on second handle will invalidate the session * causing a SESSION_EXPIRED on the first handle. *
*/ public class KillSession { /** * Kill the given ZK session * * @param client the client to kill * @param connectString server connection string * @throws Exception errors */ public static void kill(ZooKeeper client, String connectString) throws Exception { kill(client, connectString, new Timing().forWaiting().milliseconds()); } /** * Kill the given ZK session * * @param client the client to kill * @param connectString server connection string * @param maxMs max time ms to wait for kill * @throws Exception errors */ public static void kill(ZooKeeper client, String connectString, int maxMs) throws Exception { long startTicks = System.currentTimeMillis(); final CountDownLatch sessionLostLatch = new CountDownLatch(1); Watcher sessionLostWatch = new Watcher() { @Override public void process(WatchedEvent event) { sessionLostLatch.countDown(); } }; client.exists("/___CURATOR_KILL_SESSION___" + System.nanoTime(), sessionLostWatch); final CountDownLatch connectionLatch = new CountDownLatch(1); Watcher connectionWatcher = new Watcher() { @Override public void process(WatchedEvent event) { if ( event.getState() == Event.KeeperState.SyncConnected ) { connectionLatch.countDown(); } } }; ZooKeeper zk = new ZooKeeper(connectString, maxMs, connectionWatcher, client.getSessionId(), client.getSessionPasswd()); try { if ( !connectionLatch.await(maxMs, TimeUnit.MILLISECONDS) ) { throw new Exception("KillSession could not establish duplicate session"); } try { zk.close(); } finally { zk = null; } while ( client.getState().isConnected() && !sessionLostLatch.await(100, TimeUnit.MILLISECONDS) ) { long elapsed = System.currentTimeMillis() - startTicks; if ( elapsed > maxMs ) { throw new Exception("KillSession timed out waiting for session to expire"); } } } finally { if ( zk != null ) { zk.close(); } } } } QuorumConfigBuilder.java000066400000000000000000000067621245521677600343750ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-test/src/main/java/org/apache/curator/test/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.test; import com.google.common.collect.ImmutableList; import com.google.common.io.Files; import org.apache.zookeeper.server.quorum.QuorumPeerConfig; import java.io.File; import java.util.Collection; import java.util.List; import java.util.Properties; @SuppressWarnings("UnusedDeclaration") public class QuorumConfigBuilder { private final ImmutableList instanceSpecs; private final boolean fromRandom; public QuorumConfigBuilder(Collection specs) { this(specs.toArray(new InstanceSpec[specs.size()])); } public QuorumConfigBuilder(InstanceSpec... specs) { fromRandom = (specs == null) || (specs.length == 0); instanceSpecs = fromRandom ? ImmutableList.of(InstanceSpec.newInstanceSpec()) : ImmutableList.copyOf(specs); } public boolean isFromRandom() { return fromRandom; } public QuorumPeerConfig buildConfig() throws Exception { return buildConfig(0); } public InstanceSpec getInstanceSpec(int index) { return instanceSpecs.get(index); } public List getInstanceSpecs() { return instanceSpecs; } public int size() { return instanceSpecs.size(); } public QuorumPeerConfig buildConfig(int instanceIndex) throws Exception { boolean isCluster = (instanceSpecs.size() > 1); InstanceSpec spec = instanceSpecs.get(instanceIndex); if ( isCluster ) { Files.write(Integer.toString(spec.getServerId()).getBytes(), new File(spec.getDataDirectory(), "myid")); } Properties properties = new Properties(); properties.setProperty("initLimit", "10"); properties.setProperty("syncLimit", "5"); properties.setProperty("dataDir", spec.getDataDirectory().getCanonicalPath()); properties.setProperty("clientPort", Integer.toString(spec.getPort())); int tickTime = spec.getTickTime(); if ( tickTime >= 0 ) { properties.setProperty("tickTime", Integer.toString(tickTime)); } int maxClientCnxns = spec.getMaxClientCnxns(); if ( maxClientCnxns >= 0 ) { properties.setProperty("maxClientCnxns", Integer.toString(maxClientCnxns)); } if ( isCluster ) { for ( InstanceSpec thisSpec : instanceSpecs ) { properties.setProperty("server." + thisSpec.getServerId(), String.format("localhost:%d:%d", thisSpec.getQuorumPort(), thisSpec.getElectionPort())); } } QuorumPeerConfig config = new QuorumPeerConfig(); config.parseProperties(properties); return config; } } curator-apache-curator-2.7.1/curator-test/src/main/java/org/apache/curator/test/ServerHelper.java000066400000000000000000000125731245521677600331320ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.test; import org.apache.zookeeper.server.ZooKeeperServer; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.net.InetSocketAddress; class ServerHelper { private static class ServerCnxnFactoryMethods { private final Constructor constructor; private final Method configureMethod; private final Method startupMethod; private final Method shutdownMethod; private ServerCnxnFactoryMethods(Constructor constructor, Method configureMethod, Method startupMethod, Method shutdownMethod) { this.constructor = constructor; this.configureMethod = configureMethod; this.startupMethod = startupMethod; this.shutdownMethod = shutdownMethod; } } private static class NioServerCnxnMethods { private final Constructor constructor; private final Method startupMethod; private final Method shutdownMethod; private NioServerCnxnMethods(Constructor constructor, Method startupMethod, Method shutdownMethod) { this.constructor = constructor; this.startupMethod = startupMethod; this.shutdownMethod = shutdownMethod; } } private static final ServerCnxnFactoryMethods serverCnxnFactoryMethods; private static final NioServerCnxnMethods nioServerCnxn; static { Class serverCnxnFactoryClass = null; Class nioServerCnxnFactoryClass = null; try { serverCnxnFactoryClass = Class.forName("org.apache.zookeeper.server.NIOServerCnxnFactory"); } catch ( ClassNotFoundException ignore ) { // ignore } try { nioServerCnxnFactoryClass = Class.forName("org.apache.zookeeper.server.NIOServerCnxn$Factory"); } catch ( ClassNotFoundException ignore ) { // ignore } ServerCnxnFactoryMethods localServerCnxnFactoryMethods = null; NioServerCnxnMethods localNioServerCnxn = null; try { if ( serverCnxnFactoryClass != null ) { localServerCnxnFactoryMethods = new ServerCnxnFactoryMethods ( serverCnxnFactoryClass.getConstructor(), serverCnxnFactoryClass.getDeclaredMethod("configure", InetSocketAddress.class, Integer.TYPE), serverCnxnFactoryClass.getDeclaredMethod("startup", ZooKeeperServer.class), serverCnxnFactoryClass.getDeclaredMethod("shutdown") ); } else if ( nioServerCnxnFactoryClass != null ) { localNioServerCnxn = new NioServerCnxnMethods ( nioServerCnxnFactoryClass.getConstructor(InetSocketAddress.class), nioServerCnxnFactoryClass.getDeclaredMethod("startup", ZooKeeperServer.class), nioServerCnxnFactoryClass.getDeclaredMethod("shutdown") ); } } catch ( Exception e ) { e.printStackTrace(); throw new Error(e); } serverCnxnFactoryMethods = localServerCnxnFactoryMethods; nioServerCnxn = localNioServerCnxn; } static Object makeFactory(ZooKeeperServer server, int port) throws Exception { Object factory; if ( nioServerCnxn != null ) { factory = nioServerCnxn.constructor.newInstance(new InetSocketAddress(port)); if ( server != null ) { nioServerCnxn.startupMethod.invoke(factory, server); } } else { factory = serverCnxnFactoryMethods.constructor.newInstance(); serverCnxnFactoryMethods.configureMethod.invoke(factory, new InetSocketAddress(port), 0); if ( server != null ) { serverCnxnFactoryMethods.startupMethod.invoke(factory, server); } } return factory; } static void shutdownFactory(Object factory) { try { if ( nioServerCnxn != null ) { nioServerCnxn.shutdownMethod.invoke(factory); } else { serverCnxnFactoryMethods.shutdownMethod.invoke(factory); } } catch ( Exception e ) { e.printStackTrace(); throw new Error(e); } } private ServerHelper() { } } curator-apache-curator-2.7.1/curator-test/src/main/java/org/apache/curator/test/TestingCluster.java000066400000000000000000000176011245521677600335000ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.test; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.apache.zookeeper.ZooKeeper; import java.io.Closeable; import java.io.IOException; import java.lang.reflect.Method; import java.net.InetSocketAddress; import java.util.Collection; import java.util.List; import java.util.Map; /** * manages an internally running ensemble of ZooKeeper servers. FOR TESTING PURPOSES ONLY */ public class TestingCluster implements Closeable { static { ByteCodeRewrite.apply(); } private final List servers; /** * Creates an ensemble comprised of n servers. Each server will use * a temp directory and random ports * * @param instanceQty number of servers to create in the ensemble */ public TestingCluster(int instanceQty) { this(makeSpecs(instanceQty)); } /** * Creates an ensemble using the given server specs * * @param specs the server specs */ public TestingCluster(InstanceSpec... specs) { this(listToMap(ImmutableList.copyOf(specs))); } /** * Creates an ensemble using the given server specs * * @param specs the server specs */ public TestingCluster(Collection specs) { this(listToMap(specs)); } /** * Creates an ensemble using the given server specs * * @param specs map of an instance spec to its set of quorum instances. Allows simulation of an ensemble with instances * having different config peers */ public TestingCluster(Map> specs) { ImmutableList.Builder serverBuilder = ImmutableList.builder(); for ( Map.Entry> entry : specs.entrySet() ) { List instanceSpecs = Lists.newArrayList(entry.getValue()); int index = instanceSpecs.indexOf(entry.getKey()); Preconditions.checkState(index >= 0, entry.getKey() + " not found in specs"); QuorumConfigBuilder builder = new QuorumConfigBuilder(instanceSpecs); serverBuilder.add(new TestingZooKeeperServer(builder, index)); } servers = serverBuilder.build(); } /** * Returns the set of servers in the ensemble * * @return set of servers */ public Collection getInstances() { Iterable transformed = Iterables.transform ( servers, new Function() { @Override public InstanceSpec apply(TestingZooKeeperServer server) { return server.getInstanceSpec(); } } ); return Lists.newArrayList(transformed); } public List getServers() { return Lists.newArrayList(servers); } /** * Returns the connection string to pass to the ZooKeeper constructor * * @return connection string */ public String getConnectString() { StringBuilder str = new StringBuilder(); for ( InstanceSpec spec : getInstances() ) { if ( str.length() > 0 ) { str.append(","); } str.append(spec.getConnectString()); } return str.toString(); } /** * Start the ensemble. The cluster must be started before use. * * @throws Exception errors */ public void start() throws Exception { for ( TestingZooKeeperServer server : servers ) { server.start(); } } /** * Shutdown the ensemble WITHOUT freeing resources, etc. */ public void stop() throws IOException { for ( TestingZooKeeperServer server : servers ) { server.stop(); } } /** * Shutdown the ensemble, free resources, etc. If temp directories were used, they * are deleted. You should call this in a finally block. * * @throws IOException errors */ @Override public void close() throws IOException { for ( TestingZooKeeperServer server : servers ) { server.close(); } } /** * Kills the given server. This simulates the server unexpectedly crashing * * @param instance server to kill * @return true if the instance was found * @throws Exception errors */ public boolean killServer(InstanceSpec instance) throws Exception { for ( TestingZooKeeperServer server : servers ) { if ( server.getInstanceSpec().equals(instance) ) { server.kill(); return true; } } return false; } /** * Restart the given server of the cluster * * @param instance server instance * @return true of the server was found * @throws Exception errors */ public boolean restartServer(InstanceSpec instance) throws Exception { for ( TestingZooKeeperServer server : servers ) { if ( server.getInstanceSpec().equals(instance) ) { server.restart(); return true; } } return false; } /** * Given a ZooKeeper instance, returns which server it is connected to * * @param client ZK instance * @return the server * @throws Exception errors */ public InstanceSpec findConnectionInstance(ZooKeeper client) throws Exception { Method m = client.getClass().getDeclaredMethod("testableRemoteSocketAddress"); m.setAccessible(true); InetSocketAddress address = (InetSocketAddress)m.invoke(client); if ( address != null ) { for ( TestingZooKeeperServer server : servers ) { if ( server.getInstanceSpec().getPort() == address.getPort() ) { return server.getInstanceSpec(); } } } return null; } private static Map> makeSpecs(int instanceQty) { ImmutableList.Builder builder = ImmutableList.builder(); for ( int i = 0; i < instanceQty; ++i ) { builder.add(InstanceSpec.newInstanceSpec()); } return listToMap(builder.build()); } private static Map> listToMap(Collection list) { ImmutableMap.Builder> mapBuilder = ImmutableMap.builder(); for ( InstanceSpec spec : list ) { mapBuilder.put(spec, list); } return mapBuilder.build(); } } TestingQuorumPeerMain.java000066400000000000000000000050771245521677600347150ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-test/src/main/java/org/apache/curator/test/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.test; import org.apache.zookeeper.server.ServerCnxnFactory; import org.apache.zookeeper.server.quorum.QuorumPeer; import org.apache.zookeeper.server.quorum.QuorumPeerMain; import java.io.IOException; import java.lang.reflect.Field; import java.nio.channels.ServerSocketChannel; class TestingQuorumPeerMain extends QuorumPeerMain implements ZooKeeperMainFace { @Override public void kill() { try { if ( quorumPeer != null ) { Field cnxnFactoryField = QuorumPeer.class.getDeclaredField("cnxnFactory"); cnxnFactoryField.setAccessible(true); ServerCnxnFactory cnxnFactory = (ServerCnxnFactory)cnxnFactoryField.get(quorumPeer); cnxnFactory.closeAll(); Field ssField = cnxnFactory.getClass().getDeclaredField("ss"); ssField.setAccessible(true); ServerSocketChannel ss = (ServerSocketChannel)ssField.get(cnxnFactory); ss.close(); } close(); } catch ( Exception e ) { e.printStackTrace(); } } @Override public QuorumPeer getQuorumPeer() { return quorumPeer; } @Override public void close() throws IOException { if ( quorumPeer != null ) { quorumPeer.shutdown(); } } @Override public void blockUntilStarted() throws Exception { while ( quorumPeer == null ) { try { Thread.sleep(100); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); break; } } } } curator-apache-curator-2.7.1/curator-test/src/main/java/org/apache/curator/test/TestingServer.java000066400000000000000000000115271245521677600333260ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.test; import java.io.Closeable; import java.io.File; import java.io.IOException; /** * manages an internally running ZooKeeper server. FOR TESTING PURPOSES ONLY */ public class TestingServer implements Closeable { static { ByteCodeRewrite.apply(); } private final TestingZooKeeperServer testingZooKeeperServer; private final InstanceSpec spec; /** * Create the server using a random port * * @throws Exception errors */ public TestingServer() throws Exception { this(-1, null, true); } /** * Create the server using a random port * * @param start True if the server should be started, false otherwise * @throws Exception errors */ public TestingServer(boolean start) throws Exception { this(-1, null, start); } /** * Create and start the server using the given port * * @param port the port * @throws Exception errors */ public TestingServer(int port) throws Exception { this(port, null, true); } /** * Create the server using the given port * * @param port the port * @param start True if the server should be started, false otherwise * @throws Exception errors */ public TestingServer(int port, boolean start) throws Exception { this(port, null, start); } /** * Create and start the server using the given port * * @param port the port * @param tempDirectory directory to use * @throws Exception errors */ public TestingServer(int port, File tempDirectory) throws Exception { this(port, tempDirectory, true); } /** * Create the server using the given port * * @param port the port * @param tempDirectory directory to use * @param start True if the server should be started, false otherwise * @throws Exception errors */ public TestingServer(int port, File tempDirectory, boolean start) throws Exception { this(new InstanceSpec(tempDirectory, port, -1, -1, true, -1), start); } /** * Create the server using the given port * * @param spec instance details * @param start True if the server should be started, false otherwise * @throws Exception errors */ public TestingServer(InstanceSpec spec, boolean start) throws Exception { this.spec = spec; testingZooKeeperServer = new TestingZooKeeperServer(new QuorumConfigBuilder(spec)); if ( start ) { testingZooKeeperServer.start(); } } /** * Return the port being used * * @return port */ public int getPort() { return spec.getPort(); } /** * Returns the temp directory being used * * @return directory */ public File getTempDirectory() { return spec.getDataDirectory(); } /** * Start the server * * @throws Exception */ public void start() throws Exception { testingZooKeeperServer.start(); } /** * Stop the server without deleting the temp directory */ public void stop() throws IOException { testingZooKeeperServer.stop(); } /** * Restart the server. If the server is currently running it will be stopped * and restarted. If it's not currently running then it will be started. If * it has been closed (had close() called on it) then an exception will be * thrown. * * @throws Exception */ public void restart() throws Exception { testingZooKeeperServer.restart(); } /** * Close the server and any open clients and delete the temp directory */ @Override public void close() throws IOException { testingZooKeeperServer.close(); } /** * Returns the connection string to use * * @return connection string */ public String getConnectString() { return spec.getConnectString(); } }TestingZooKeeperMain.java000066400000000000000000000134111245521677600345030ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-test/src/main/java/org/apache/curator/test/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.test; import org.apache.zookeeper.server.ServerCnxnFactory; import org.apache.zookeeper.server.ServerConfig; import org.apache.zookeeper.server.ZKDatabase; import org.apache.zookeeper.server.ZooKeeperServer; import org.apache.zookeeper.server.ZooKeeperServerMain; import org.apache.zookeeper.server.quorum.QuorumPeer; import org.apache.zookeeper.server.quorum.QuorumPeerConfig; import java.io.IOException; import java.lang.reflect.Field; import java.nio.channels.ServerSocketChannel; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; public class TestingZooKeeperMain extends ZooKeeperServerMain implements ZooKeeperMainFace { private final CountDownLatch latch = new CountDownLatch(1); private final AtomicReference startingException = new AtomicReference(null); private static final int MAX_WAIT_MS = 1000; @Override public void kill() { try { Field cnxnFactoryField = ZooKeeperServerMain.class.getDeclaredField("cnxnFactory"); cnxnFactoryField.setAccessible(true); ServerCnxnFactory cnxnFactory = (ServerCnxnFactory)cnxnFactoryField.get(this); cnxnFactory.closeAll(); Field ssField = cnxnFactory.getClass().getDeclaredField("ss"); ssField.setAccessible(true); ServerSocketChannel ss = (ServerSocketChannel)ssField.get(cnxnFactory); ss.close(); close(); } catch ( Exception e ) { e.printStackTrace(); // just ignore - this class is only for testing } } @Override public void runFromConfig(QuorumPeerConfig config) throws Exception { ServerConfig serverConfig = new ServerConfig(); serverConfig.readFrom(config); latch.countDown(); try { super.runFromConfig(serverConfig); } catch ( IOException e ) { startingException.set(e); throw e; } } @Override public QuorumPeer getQuorumPeer() { throw new UnsupportedOperationException(); } @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") @Override public void blockUntilStarted() throws Exception { latch.await(); ServerCnxnFactory cnxnFactory = getServerConnectionFactory(); if ( cnxnFactory != null ) { final ZooKeeperServer zkServer = getZooKeeperServer(cnxnFactory); if ( zkServer != null ) { synchronized(zkServer) { if ( !zkServer.isRunning() ) { zkServer.wait(); } } } } Thread.sleep(1000); Exception exception = startingException.get(); if ( exception != null ) { throw exception; } } @Override public void close() throws IOException { shutdown(); try { ServerCnxnFactory cnxnFactory = getServerConnectionFactory(); if ( cnxnFactory != null ) { ZooKeeperServer zkServer = getZooKeeperServer(cnxnFactory); if ( zkServer != null ) { ZKDatabase zkDb = zkServer.getZKDatabase(); if ( zkDb != null ) { // make ZK server close its log files zkDb.close(); } } } } catch ( Exception e ) { e.printStackTrace(); // just ignore - this class is only for testing } } private ServerCnxnFactory getServerConnectionFactory() throws Exception { Field cnxnFactoryField = ZooKeeperServerMain.class.getDeclaredField("cnxnFactory"); cnxnFactoryField.setAccessible(true); ServerCnxnFactory cnxnFactory; // Wait until the cnxnFactory field is non-null or up to 1s, whichever comes first. long startTime = System.currentTimeMillis(); do { cnxnFactory = (ServerCnxnFactory)cnxnFactoryField.get(this); } while ( (cnxnFactory == null) && ((System.currentTimeMillis() - startTime) < MAX_WAIT_MS) ); return cnxnFactory; } private ZooKeeperServer getZooKeeperServer(ServerCnxnFactory cnxnFactory) throws Exception { Field zkServerField = ServerCnxnFactory.class.getDeclaredField("zkServer"); zkServerField.setAccessible(true); ZooKeeperServer zkServer; // Wait until the zkServer field is non-null or up to 1s, whichever comes first. long startTime = System.currentTimeMillis(); do { zkServer = (ZooKeeperServer)zkServerField.get(cnxnFactory); } while ( (zkServer == null) && ((System.currentTimeMillis() - startTime) < MAX_WAIT_MS) ); return zkServer; } } TestingZooKeeperServer.java000066400000000000000000000113341245521677600350670ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-test/src/main/java/org/apache/curator/test/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.test; import org.apache.zookeeper.server.quorum.QuorumPeer; import org.apache.zookeeper.server.quorum.QuorumPeerConfig; import org.apache.zookeeper.server.quorum.QuorumPeerMain; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.Collection; import java.util.concurrent.atomic.AtomicReference; /** * Thanks to Jeremie BORDIER (ahfeel) for this code */ public class TestingZooKeeperServer extends QuorumPeerMain implements Closeable { private static final Logger logger = LoggerFactory.getLogger(TestingZooKeeperServer.class); private final QuorumConfigBuilder configBuilder; private final int thisInstanceIndex; private volatile ZooKeeperMainFace main; private final AtomicReference state = new AtomicReference(State.LATENT); private enum State { LATENT, STARTED, STOPPED, CLOSED } public TestingZooKeeperServer(QuorumConfigBuilder configBuilder) { this(configBuilder, 0); } public TestingZooKeeperServer(QuorumConfigBuilder configBuilder, int thisInstanceIndex) { this.configBuilder = configBuilder; this.thisInstanceIndex = thisInstanceIndex; main = (configBuilder.size() > 1) ? new TestingQuorumPeerMain() : new TestingZooKeeperMain(); } public QuorumPeer getQuorumPeer() { return main.getQuorumPeer(); } public Collection getInstanceSpecs() { return configBuilder.getInstanceSpecs(); } public void kill() { main.kill(); state.set(State.STOPPED); } /** * Restart the server. If the server is running it will be stopped and then * started again. If it is not running (in a LATENT or STOPPED state) then * it will be restarted. If it is in a CLOSED state then an exception will * be thrown. * * @throws Exception */ public void restart() throws Exception { // Can't restart from a closed state as all the temporary data is gone if ( state.get() == State.CLOSED ) { throw new IllegalStateException("Cannot restart a closed instance"); } // If the server's currently running then stop it. if ( state.get() == State.STARTED ) { stop(); } // Set to a LATENT state so we can restart state.set(State.LATENT); main = (configBuilder.size() > 1) ? new TestingQuorumPeerMain() : new TestingZooKeeperMain(); start(); } public void stop() throws IOException { if ( state.compareAndSet(State.STARTED, State.STOPPED) ) { main.close(); } } public InstanceSpec getInstanceSpec() { return configBuilder.getInstanceSpec(thisInstanceIndex); } @Override public void close() throws IOException { stop(); if ( state.compareAndSet(State.STOPPED, State.CLOSED) ) { InstanceSpec spec = getInstanceSpec(); if ( spec.deleteDataDirectoryOnClose() ) { DirectoryUtils.deleteRecursively(spec.getDataDirectory()); } } } public void start() throws Exception { if ( !state.compareAndSet(State.LATENT, State.STARTED) ) { return; } new Thread(new Runnable() { public void run() { try { QuorumPeerConfig config = configBuilder.buildConfig(thisInstanceIndex); main.runFromConfig(config); } catch ( Exception e ) { logger.error(String.format("From testing server (random state: %s) for instance: %s", String.valueOf(configBuilder.isFromRandom()), getInstanceSpec()), e); } } }).start(); main.blockUntilStarted(); } }curator-apache-curator-2.7.1/curator-test/src/main/java/org/apache/curator/test/Timing.java000066400000000000000000000131351245521677600317460ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * Utility to get various testing times */ public class Timing { private final long value; private final TimeUnit unit; private final int waitingMultiple; private static final int DEFAULT_SECONDS = 10; private static final int DEFAULT_WAITING_MULTIPLE = 5; private static final double SESSION_MULTIPLE = .25; /** * Use the default base time */ public Timing() { this(Integer.getInteger("timing-multiple", 1), getWaitingMultiple()); } /** * Use a multiple of the default base time * * @param multiple the multiple */ public Timing(double multiple) { this((long)(DEFAULT_SECONDS * multiple), TimeUnit.SECONDS, getWaitingMultiple()); } /** * Use a multiple of the default base time * * @param multiple the multiple * @param waitingMultiple multiple of main timing to use when waiting */ public Timing(double multiple, int waitingMultiple) { this((long)(DEFAULT_SECONDS * multiple), TimeUnit.SECONDS, waitingMultiple); } /** * @param value base time * @param unit base time unit */ public Timing(long value, TimeUnit unit) { this(value, unit, getWaitingMultiple()); } /** * @param value base time * @param unit base time unit * @param waitingMultiple multiple of main timing to use when waiting */ public Timing(long value, TimeUnit unit, int waitingMultiple) { this.value = value; this.unit = unit; this.waitingMultiple = waitingMultiple; } /** * Return the base time in milliseconds * * @return time ms */ public int milliseconds() { return (int)TimeUnit.MILLISECONDS.convert(value, unit); } /** * Return the base time in seconds * * @return time secs */ public int seconds() { return (int)value; } /** * Wait on the given latch * * @param latch latch to wait on * @return result of {@link CountDownLatch#await(long, TimeUnit)} */ public boolean awaitLatch(CountDownLatch latch) { Timing m = forWaiting(); try { return latch.await(m.value, m.unit); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } return false; } /** * Wait on the given semaphore * * @param semaphore the semaphore * @return result of {@link Semaphore#tryAcquire()} */ public boolean acquireSemaphore(Semaphore semaphore) { Timing m = forWaiting(); try { return semaphore.tryAcquire(m.value, m.unit); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } return false; } /** * Wait on the given semaphore * * @param semaphore the semaphore * @param n number of permits to acquire * @return result of {@link Semaphore#tryAcquire(int, long, TimeUnit)} */ public boolean acquireSemaphore(Semaphore semaphore, int n) { Timing m = forWaiting(); try { return semaphore.tryAcquire(n, m.value, m.unit); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } return false; } /** * Return a new timing that is a multiple of the this timing * * @param n the multiple * @return this timing times the multiple */ public Timing multiple(double n) { return new Timing((int)(value * n), unit); } /** * Return a new timing with the standard multiple for waiting on latches, etc. * * @return this timing multiplied */ @SuppressWarnings("PointlessArithmeticExpression") public Timing forWaiting() { return multiple(waitingMultiple); } /** * Sleep for a small amount of time * * @throws InterruptedException if interrupted */ public void sleepABit() throws InterruptedException { unit.sleep(value / 4); } /** * Return the value to use for ZK session timeout * * @return session timeout */ public int session() { return multiple(SESSION_MULTIPLE).milliseconds(); } /** * Return the value to use for ZK connection timeout * * @return connection timeout */ public int connection() { return milliseconds(); } private static Integer getWaitingMultiple() { return Integer.getInteger("timing-waiting-multiple", DEFAULT_WAITING_MULTIPLE); } } ZooKeeperMainFace.java000066400000000000000000000023221245521677600337230ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-test/src/main/java/org/apache/curator/test/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.test; import org.apache.zookeeper.server.quorum.QuorumPeer; import org.apache.zookeeper.server.quorum.QuorumPeerConfig; import java.io.Closeable; public interface ZooKeeperMainFace extends Closeable { public void runFromConfig(QuorumPeerConfig config) throws Exception; public void blockUntilStarted() throws Exception; public void kill(); public QuorumPeer getQuorumPeer(); } curator-apache-curator-2.7.1/curator-test/src/site/000077500000000000000000000000001245521677600223025ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-test/src/site/confluence/000077500000000000000000000000001245521677600244235ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-test/src/site/confluence/index.confluence000066400000000000000000000007021245521677600275740ustar00rootroot00000000000000h1. Testing Utilities h2. Test Server In the curator\-test sub\-model the {{TestingServer}} class is provided. This class creates a local, in\-process ZooKeeper server that can be used for testing. h2. Test Cluster In the curator\-test sub\-model the {{TestingCluster}} class is provided. This class creates an internally running ensemble of ZooKeeper servers. h2. Usage Look at the various Curator unit tests to see how these utilities are used. curator-apache-curator-2.7.1/curator-test/src/site/site.xml000066400000000000000000000023261245521677600237730ustar00rootroot00000000000000 curator-apache-curator-2.7.1/curator-x-discovery-server/000077500000000000000000000000001245521677600233505ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/LICENSE000066400000000000000000000261361245521677600243650ustar00rootroot00000000000000 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. curator-apache-curator-2.7.1/curator-x-discovery-server/NOTICE000066400000000000000000000002501245521677600242510ustar00rootroot00000000000000Apache Curator Copyright 2013-2014 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). curator-apache-curator-2.7.1/curator-x-discovery-server/README.txt000066400000000000000000000061501245521677600250500ustar00rootroot00000000000000==== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==== == Service Discovery Server == A REST server for use with Curator Service Discovery. This server can be used for non-Java applications that need to participate in the Curator Service Discovery. Full documentation: http://curator.apache.org/curator-x-discovery-server/index.html == JSON specifications for REST entities == = ServiceInstance = FIELD TYPE REQUIRED DESCRIPTION ------------------------------------------------------------------------------------------------------- name string Y Service Name id string Y Instance ID address string Y Hostname/IP port int * Instance port (port and/or sslPort must be present) sslPort int * Instance SSL port (port and/or sslPort must be present) payload user-defined N Instance payload registrationTimeUTC long N Time of the registration in UTC serviceType string Y Either "STATIC" or "PERMANENT". STATIC will get purged after the defined threshold has elapsed. PERMANENT must be manually purged. Example: { "name": "test", "id": "ca2fff8e-d756-480c-b59e-8297ff88624b", "address": "10.20.30.40", "port": 1234, "payload": "From Test", "registrationTimeUTC": 1325129459728, "serviceType": "STATIC" } = ServiceInstances = A list of ServiceInstance entities. Example: [ { "name": "test", "id": "ca2fff8e-d756-480c-b59e-8297ff88624b", "address": "10.20.30.40", "port": 1234, "payload": "From Test", "registrationTimeUTC": 1325129459728, "serviceType": "STATIC" }, { "name": "foo", "id": "bd4fff8e-c234-480c-f6ee-8297ff813765", "address": "10.20.30.40", "sslPort": 1235, "payload": "foo-bar", "registrationTimeUTC": 1325129459728, "serviceType": "STATIC" } ] = ServiceNames = A list of strings (service names). Example: [ { "name": "foo" }, { "name": "bar" } ] curator-apache-curator-2.7.1/curator-x-discovery-server/pom.xml000066400000000000000000000075061245521677600246750ustar00rootroot00000000000000 4.0.0 org.apache.curator apache-curator 2.7.1 curator-x-discovery-server 2.7.1 bundle Curator Service Discovery Server Bridges non-Java or legacy applications with the Curator Service Discovery. 2011 * org.apache.curator.x.discovery.server*;version="${project.version}";-noimport:=true org.apache.curator curator-x-discovery javax.ws.rs jsr311-api org.apache.curator curator-test test com.sun.jersey jersey-server test com.sun.jersey jersey-servlet test com.sun.jersey jersey-client test com.sun.jersey jersey-core test org.mortbay.jetty jetty test net.sf.scannotation scannotation test org.jboss.resteasy resteasy-jaxrs test org.apache.maven.plugins maven-surefire-plugin none curator-apache-curator-2.7.1/curator-x-discovery-server/src/000077500000000000000000000000001245521677600241375ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/000077500000000000000000000000001245521677600250635ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/000077500000000000000000000000001245521677600260045ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/000077500000000000000000000000001245521677600265735ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/000077500000000000000000000000001245521677600300145ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/000077500000000000000000000000001245521677600314735ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/000077500000000000000000000000001245521677600317425ustar00rootroot00000000000000000077500000000000000000000000001245521677600336725ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery000077500000000000000000000000001245521677600352005ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server000077500000000000000000000000001245521677600370475ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contextsGenericDiscoveryContext.java000066400000000000000000000064661245521677600445370ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.contexts; import com.google.common.reflect.TypeToken; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.server.rest.DiscoveryContext; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.node.ObjectNode; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; /** * For convenience, a version of {@link DiscoveryContext} that uses any generic type as the payload */ @Provider public class GenericDiscoveryContext implements DiscoveryContext, ContextResolver> { private final ServiceDiscovery serviceDiscovery; private final ProviderStrategy providerStrategy; private final int instanceRefreshMs; private final TypeToken payloadType; public GenericDiscoveryContext(ServiceDiscovery serviceDiscovery, ProviderStrategy providerStrategy, int instanceRefreshMs, Class payloadType) { this(serviceDiscovery, providerStrategy, instanceRefreshMs, TypeToken.of(payloadType)); } public GenericDiscoveryContext(ServiceDiscovery serviceDiscovery, ProviderStrategy providerStrategy, int instanceRefreshMs, TypeToken payloadType) { this.serviceDiscovery = serviceDiscovery; this.providerStrategy = providerStrategy; this.instanceRefreshMs = instanceRefreshMs; this.payloadType = payloadType; } @Override public ProviderStrategy getProviderStrategy() { return providerStrategy; } @Override public int getInstanceRefreshMs() { return instanceRefreshMs; } @Override public ServiceDiscovery getServiceDiscovery() { return serviceDiscovery; } @Override public void marshallJson(ObjectNode node, String fieldName, T payload) throws Exception { if ( payload == null ) { //noinspection unchecked payload = (T)payloadType.getRawType().newInstance(); } node.putPOJO(fieldName, payload); } @Override public T unMarshallJson(JsonNode node) throws Exception { T payload; ObjectMapper mapper = new ObjectMapper(); //noinspection unchecked payload = (T)mapper.readValue(node, payloadType.getRawType()); return payload; } @Override public DiscoveryContext getContext(Class type) { return this; } } IntegerDiscoveryContext.java000066400000000000000000000053631245521677600445530ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.contexts; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.server.rest.DiscoveryContext; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.node.ObjectNode; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; /** * For convenience, a version of {@link DiscoveryContext} that uses an int as the * payload */ @Provider public class IntegerDiscoveryContext implements DiscoveryContext, ContextResolver> { private final ServiceDiscovery serviceDiscovery; private final ProviderStrategy providerStrategy; private final int instanceRefreshMs; public IntegerDiscoveryContext(ServiceDiscovery serviceDiscovery, ProviderStrategy providerStrategy, int instanceRefreshMs) { this.serviceDiscovery = serviceDiscovery; this.providerStrategy = providerStrategy; this.instanceRefreshMs = instanceRefreshMs; } @Override public ProviderStrategy getProviderStrategy() { return providerStrategy; } @Override public int getInstanceRefreshMs() { return instanceRefreshMs; } @Override public ServiceDiscovery getServiceDiscovery() { return serviceDiscovery; } @Override public void marshallJson(ObjectNode node, String fieldName, Integer payload) throws Exception { if ( payload != null ) { node.put(fieldName, payload.toString()); } } @Override public Integer unMarshallJson(JsonNode node) throws Exception { if ( node != null ) { return Integer.parseInt(node.asText()); } return null; } @Override public DiscoveryContext getContext(Class type) { return this; } } MapDiscoveryContext.java000066400000000000000000000033321245521677600436650ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.contexts; import com.google.common.reflect.TypeToken; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.server.rest.DiscoveryContext; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; import java.util.Map; /** * For convenience, a version of {@link DiscoveryContext} that uses a String-to-String map as the * payload */ @Provider public class MapDiscoveryContext extends GenericDiscoveryContext> implements ContextResolver>> { public MapDiscoveryContext(ServiceDiscovery> serviceDiscovery, ProviderStrategy> providerStrategy, int instanceRefreshMs) { super(serviceDiscovery, providerStrategy, instanceRefreshMs, new TypeToken>(){}); } } StringDiscoveryContext.java000066400000000000000000000052321245521677600444170ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.contexts; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.server.rest.DiscoveryContext; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.node.ObjectNode; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; /** * For convenience, a version of {@link DiscoveryContext} that uses a string as the * payload */ @Provider public class StringDiscoveryContext implements DiscoveryContext, ContextResolver> { private final ServiceDiscovery serviceDiscovery; private final ProviderStrategy providerStrategy; private final int instanceRefreshMs; public StringDiscoveryContext(ServiceDiscovery serviceDiscovery, ProviderStrategy providerStrategy, int instanceRefreshMs) { this.serviceDiscovery = serviceDiscovery; this.providerStrategy = providerStrategy; this.instanceRefreshMs = instanceRefreshMs; } @Override public ProviderStrategy getProviderStrategy() { return providerStrategy; } @Override public int getInstanceRefreshMs() { return instanceRefreshMs; } @Override public ServiceDiscovery getServiceDiscovery() { return serviceDiscovery; } @Override public void marshallJson(ObjectNode node, String fieldName, String payload) throws Exception { if ( payload != null ) { node.put(fieldName, payload); } } @Override public String unMarshallJson(JsonNode node) throws Exception { return (node != null) ? node.asText() : null; } @Override public DiscoveryContext getContext(Class type) { return this; } } 000077500000000000000000000000001245521677600365145ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entityJsonServiceInstanceMarshaller.java000066400000000000000000000135271245521677600453210ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.entity; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceInstanceBuilder; import org.apache.curator.x.discovery.ServiceType; import org.apache.curator.x.discovery.server.rest.DiscoveryContext; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.node.ObjectNode; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; /** * Message body reader/writer. Inject this as appropriate for the JAX-RS implementation you are using */ @Provider @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class JsonServiceInstanceMarshaller implements MessageBodyReader>, MessageBodyWriter> { private final DiscoveryContext context; public JsonServiceInstanceMarshaller(DiscoveryContext context) { this.context = context; } static ServiceInstance readInstance(JsonNode node, DiscoveryContext context) throws Exception { ServiceInstanceBuilder builder = ServiceInstance.builder(); builder.name(node.get("name").asText()); builder.id(node.get("id").asText()); builder.address(node.get("address").asText()); builder.registrationTimeUTC(node.get("registrationTimeUTC").asLong()); builder.serviceType(ServiceType.valueOf(node.get("serviceType").asText())); builder.payload(context.unMarshallJson(node.get("payload"))); Integer port = getInteger(node, "port"); Integer sslPort = getInteger(node, "sslPort"); if ( port != null ) { builder.port(port); } if ( sslPort != null ) { builder.sslPort(sslPort); } return builder.build(); } static ObjectNode writeInstance(ObjectMapper mapper, ServiceInstance instance, DiscoveryContext context) { ObjectNode node = mapper.createObjectNode(); node.put("name", instance.getName()); node.put("id", instance.getId()); node.put("address", instance.getAddress()); putInteger(node, "port", instance.getPort()); putInteger(node, "sslPort", instance.getSslPort()); node.put("registrationTimeUTC", instance.getRegistrationTimeUTC()); node.put("serviceType", instance.getServiceType().name()); try { context.marshallJson(node, "payload", instance.getPayload()); } catch ( Exception e ) { throw new WebApplicationException(e); } return node; } private static Integer getInteger(JsonNode node, String fieldName) { JsonNode intNode = node.get(fieldName); return (intNode != null) ? intNode.asInt() : null; } private static void putInteger(ObjectNode node, String fieldName, Integer value) { if ( value != null ) { node.put(fieldName, value); } } @Override public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return isWriteable(type, genericType, annotations, mediaType); } @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return ServiceInstance.class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE); } @Override public long getSize(ServiceInstance serviceInstance, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public ServiceInstance readFrom(Class> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { try { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.reader().readTree(entityStream); return readInstance(node, context); } catch ( Exception e ) { throw new WebApplicationException(e); } } @Override public void writeTo(ServiceInstance serviceInstance, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { ObjectMapper mapper = new ObjectMapper(); ObjectNode node = writeInstance(mapper, serviceInstance, context); mapper.writer().writeValue(entityStream, node); } } JsonServiceInstancesMarshaller.java000066400000000000000000000107241245521677600455000ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.entity; import com.google.common.collect.Lists; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.server.rest.DiscoveryContext; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.node.ArrayNode; import org.codehaus.jackson.node.ObjectNode; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.List; /** * Message body reader/writer. Inject this as appropriate for the JAX-RS implementation you are using */ @Provider @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class JsonServiceInstancesMarshaller implements MessageBodyReader>, MessageBodyWriter> { private final DiscoveryContext context; public JsonServiceInstancesMarshaller(DiscoveryContext context) { this.context = context; } @Override public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return isWriteable(type, genericType, annotations, mediaType); } @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return ServiceInstances.class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE); } @Override public long getSize(ServiceInstances serviceInstances, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public ServiceInstances readFrom(Class> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { try { List> instances = Lists.newArrayList(); ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.reader().readTree(entityStream); for ( int i = 0; i < tree.size(); ++i ) { JsonNode node = tree.get(i); ServiceInstance instance = JsonServiceInstanceMarshaller.readInstance(node, context); instances.add(instance); } return new ServiceInstances(instances); } catch ( Exception e ) { throw new WebApplicationException(e); } } @Override public void writeTo(ServiceInstances serviceInstances, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { ObjectMapper mapper = new ObjectMapper(); ArrayNode arrayNode = mapper.createArrayNode(); List> instanceList = serviceInstances.getServices(); for ( ServiceInstance instance : instanceList ) { ObjectNode node = JsonServiceInstanceMarshaller.writeInstance(mapper, instance, context); arrayNode.add(node); } mapper.writer().writeValue(entityStream, arrayNode); } } JsonServiceNamesMarshaller.java000066400000000000000000000075021245521677600446140ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.entity; import com.google.common.collect.Lists; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.node.ArrayNode; import org.codehaus.jackson.node.ObjectNode; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.List; /** * Message body reader/writer. Inject this as appropriate for the JAX-RS implementation you are using */ @Provider @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class JsonServiceNamesMarshaller implements MessageBodyReader, MessageBodyWriter { @Override public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return allow(type, mediaType); } @Override public ServiceNames readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { List names = Lists.newArrayList(); ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.reader().readTree(entityStream); for ( int i = 0; i < tree.size(); ++i ) { JsonNode node = tree.get(i); names.add(node.get("name").asText()); } return new ServiceNames(names); } @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return allow(type, mediaType); } @Override public long getSize(ServiceNames serviceNames, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public void writeTo(ServiceNames serviceNames, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { ObjectMapper mapper = new ObjectMapper(); ArrayNode arrayNode = mapper.createArrayNode(); for ( String name : serviceNames.getNames() ) { ObjectNode node = mapper.createObjectNode(); node.put("name", name); arrayNode.add(node); } mapper.writer().writeValue(entityStream, arrayNode); } private static boolean allow(Class type, MediaType mediaType) { return ServiceNames.class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE); } } ServiceInstances.java000066400000000000000000000030251245521677600426270ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.entity; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.apache.curator.x.discovery.ServiceInstance; import java.util.Collection; import java.util.List; /** * Raw generic lists don't work well in JAX-RS. Thus, this wrapper is needed. */ public class ServiceInstances { private final List> services; public ServiceInstances() { services = Lists.newArrayList(); } public ServiceInstances(Collection> c) { services = Lists.newArrayList(c); } public List> getServices() { return ImmutableList.copyOf(services); } } ServiceNames.java000066400000000000000000000026341245521677600417500ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.entity; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import java.util.Collection; import java.util.List; /** * Raw generic lists don't work well in JAX-RS. Thus, this wrapper is needed. */ public class ServiceNames { private final List names; public ServiceNames() { names = Lists.newArrayList(); } public ServiceNames(Collection c) { names = Lists.newArrayList(c); } public List getNames() { return ImmutableList.copyOf(names); } } 000077500000000000000000000000001245521677600361555ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/restDiscoveryContext.java000066400000000000000000000044241245521677600423400ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.rest; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceDiscovery; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.node.ObjectNode; /** * Bridge between the specifics of your needs and the generic implementation */ public interface DiscoveryContext { /** * Return the threshold in milliseconds to consider a registration stale * * @return number of milliseconds */ public int getInstanceRefreshMs(); /** * Return the service singleton * * @return service */ public ServiceDiscovery getServiceDiscovery(); /** * Serialize your payload * * @param node the node to serialize into * @param fieldName field name to use * @param payload the payload value (can be null) * @throws Exception any errors */ public void marshallJson(ObjectNode node, String fieldName, T payload) throws Exception; /** * Deserialize your payload * * @param node the node that has the payload * @return the payload or null * @throws Exception any errors */ public T unMarshallJson(JsonNode node) throws Exception; /** * Return the provider strategy to use for {@link DiscoveryResource#getAny(String)} * * @return strategy */ public ProviderStrategy getProviderStrategy(); } DiscoveryResource.java000066400000000000000000000200361245521677600425000ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.rest; import com.google.common.collect.Lists; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceType; import org.apache.curator.x.discovery.details.InstanceProvider; import org.apache.curator.x.discovery.server.entity.ServiceInstances; import org.apache.curator.x.discovery.server.entity.ServiceNames; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.Collection; import java.util.Collections; import java.util.List; /** *

* The JAX-RS web service. Due to how most JAX-RS implementations are written, you must * create a concrete class that extends this using your payload type. The concrete class should * have the base path that you'd like to use. *

* *

* Because the JAX-RS implementation can create a new instance of the resource for every request, * your concrete class must use a context resolver to access the DiscoveryContext. Or, if you * are using an IoC framework, you can access it that way. *

* *

* Here's a version that has no payload (i.e. * a Void payload): *

*
 * @Path("/")
 * public class MyResource extends DiscoveryResource<Void> {
 *     public MyResource(@Context ContextResolver<DiscoveryContext<Void>> resolver) {
 *         // note: this may not work with all JAX-RS implementations
 *         super(resolver.getContext(DiscoveryContext.class));
 *     }
 * }
 * 
*/ public abstract class DiscoveryResource { private static final Logger log = LoggerFactory.getLogger(DiscoveryResource.class); private final DiscoveryContext context; public DiscoveryResource(DiscoveryContext context) { this.context = context; } @PUT @Path("v1/service/{name}/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response putService(ServiceInstance instance, @PathParam("name") String name, @PathParam("id") String id) { if ( !instance.getId().equals(id) || !instance.getName().equals(name) ) { log.info("Request where path id and/or name doesn't match entity"); return Response.status(Response.Status.BAD_REQUEST).build(); } if ( instance.getServiceType() == ServiceType.DYNAMIC ) { log.info("Service type cannot be dynamic"); return Response.status(Response.Status.BAD_REQUEST).build(); } try { context.getServiceDiscovery().registerService(instance); } catch ( Exception e ) { log.error("Trying to register service", e); return Response.serverError().build(); } return Response.status(Response.Status.CREATED).build(); } @DELETE @Path("v1/service/{name}/{id}") public Response removeService(@PathParam("name") String name, @PathParam("id") String id) { try { ServiceInstance instance = context.getServiceDiscovery().queryForInstance(name, id); if ( instance != null ) { //noinspection unchecked context.getServiceDiscovery().unregisterService(instance); } } catch ( Exception e ) { log.error("Trying to delete service", e); return Response.serverError().build(); } return Response.ok().build(); } @Deprecated @GET @Path("{name}/{id}") @Produces(MediaType.APPLICATION_JSON) public Response getDeprecated(@PathParam("name") String name, @PathParam("id") String id) { return internalGet(name, id, true); } @GET @Path("v1/service/{name}/{id}") @Produces(MediaType.APPLICATION_JSON) public Response get(@PathParam("name") String name, @PathParam("id") String id) { return internalGet(name, id, false); } @GET @Path("v1/service") @Produces(MediaType.APPLICATION_JSON) public Response getAllNames() { try { List instances = Lists.newArrayList(context.getServiceDiscovery().queryForNames()); Collections.sort(instances); return Response.ok(new ServiceNames(instances)).build(); } catch ( Exception e ) { log.error("Trying to get service names", e); return Response.serverError().build(); } } @GET @Path("v1/service/{name}") @Produces(MediaType.APPLICATION_JSON) public Response getAll(@PathParam("name") String name) { try { Collection> instances = context.getServiceDiscovery().queryForInstances(name); return Response.ok(new ServiceInstances(instances)).build(); } catch ( Exception e ) { log.error(String.format("Trying to get instances from service (%s)", name), e); return Response.serverError().build(); } } @GET @Path("v1/anyservice/{name}") @Produces(MediaType.APPLICATION_JSON) public Response getAny(@PathParam("name") String name) { try { final List> instances = Lists.newArrayList(context.getServiceDiscovery().queryForInstances(name)); ServiceInstance randomInstance = context.getProviderStrategy().getInstance ( new InstanceProvider() { @Override public List> getInstances() throws Exception { return instances; } } ); if ( randomInstance == null ) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok(randomInstance).build(); } catch ( Exception e ) { log.error(String.format("Trying to get any instance from service (%s)", name), e); return Response.serverError().build(); } } private Response internalGet(String name, String id, boolean addDeprecationHeader) { try { ServiceInstance instance = context.getServiceDiscovery().queryForInstance(name, id); if ( instance == null ) { return Response.status(Response.Status.NOT_FOUND).build(); } Response.ResponseBuilder builder = Response.ok(instance); if ( addDeprecationHeader ) { builder = builder.header("Warning", "This API has been deprecated. Please see the updated spec for the replacement API."); } return builder.build(); } catch ( Exception e ) { log.error(String.format("Trying to get instance (%s) from service (%s)", id, name), e); return Response.serverError().build(); } } } InstanceCleanup.java000066400000000000000000000077741245521677600421130ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.rest; import com.google.common.base.Preconditions; import org.apache.curator.utils.ThreadUtils; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.Collection; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * A background task that purges stale registrations. You should allocate a singleton * of this class, call {@link #start()} and then call {@link #close()} when your application * is shutting down. */ public class InstanceCleanup implements Closeable { private static final Logger log = LoggerFactory.getLogger(InstanceCleanup.class); private final ServiceDiscovery discovery; private final int instanceRefreshMs; private final ScheduledExecutorService service = ThreadUtils.newSingleThreadScheduledExecutor("InstanceCleanup"); /** * @param discovery the service being monitored * @param instanceRefreshMs time in milliseconds to consider a registration stale */ public InstanceCleanup(ServiceDiscovery discovery, int instanceRefreshMs) { //noinspection unchecked this.discovery = (ServiceDiscovery)discovery; // this cast is safe - this class never accesses the payload this.instanceRefreshMs = instanceRefreshMs; } /** * Start the task */ public void start() { Preconditions.checkArgument(!service.isShutdown(), "already started"); service.scheduleWithFixedDelay ( new Runnable() { @Override public void run() { doWork(); } }, instanceRefreshMs, instanceRefreshMs, TimeUnit.MILLISECONDS ); } @Override public void close() throws IOException { Preconditions.checkArgument(!service.isShutdown(), "not started"); service.shutdownNow(); } private void doWork() { try { for ( String name : discovery.queryForNames() ) { checkService(name); } } catch ( Exception e ) { log.error("GC for service names", e); } } private void checkService(String name) { try { Collection> instances = discovery.queryForInstances(name); for ( ServiceInstance instance : instances ) { if ( instance.getServiceType() == ServiceType.STATIC ) { if ( (System.currentTimeMillis() - instance.getRegistrationTimeUTC()) > instanceRefreshMs ) { discovery.unregisterService(instance); } } } } catch ( Exception e ) { log.error(String.format("GC for service: %s", name), e); } } } curator-apache-curator-2.7.1/curator-x-discovery-server/src/site/000077500000000000000000000000001245521677600251035ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/site/confluence/000077500000000000000000000000001245521677600272245ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/site/confluence/index.confluence000066400000000000000000000073421245521677600324040ustar00rootroot00000000000000h1. Service Discovery Server h2. Packaging Curator Service Discovery is in its own package in Maven Central: curator\-x\-discovery\-server h2. Description The Service Discovery Server bridges non\-Java or legacy applications with the Curator [[Service Discovery|../curator-x-discovery/index.html]]. It exposes RESTful web services to register, remove, query, etc. services. The Service Discovery Server provides JAX\-RS components that can be incorporated into a container of your choice (Tomcat, Jetty, etc.). You can also choose any JAX\-RS provider (Jersey, RESTEasy, etc.). h2. Deploying the Server The server must be combined with a JAX\-RS implementation (Jersey, etc.) and a container (Tomcat, Jetty, etc.). Several singletons need to be injected: * ServiceDiscovery * DiscoveryContext * JsonServiceInstanceMarshaller * JsonServiceInstancesMarshaller * JsonServiceNamesMarshaller Additionally the JAX\-RS Resource class must be injected. Due to how most JAX\-RS implementations are written, you must create a concrete class that extends this using your payload type. The concrete class should have the base path that you'd like to use. Because the JAX\-RS implementation can create a new instance of the resource for every request, your concrete class must use a context resolver to access the DiscoveryContext. Or, if you are using an IoC framework, you can access it that way. Here's a version that has no payload (i.e. a Void payload): {code} @Path("/") public class MyResource extends DiscoveryResource { public MyResource(@Context ContextResolver> resolver) { // note: this may not work with all JAX-RS implementations super(resolver.getContext(DiscoveryContext.class)); } } {code} h2. REST Clients must make appropriate REST calls to register themselves and send periodic heartbeats. They can also find services via REST calls: h2. putService *Method:* PUT \\ *Path:* v1/service/{name}/{id} \\ *Request Entity:* ServiceInstance \\ *Response Entity:* n/a \\ *Description:* {name} is the service name, {id} is the instance id. The request entity is a _ServiceInstance_. This method registers a service instance. If the ServiceType is STATIC, the instance is registered only for the pre\-defined period (defined in the DiscoveryContext). STATIC services must call putService at least once per period. PERMANENT services are registered until they are manually deleted. h2. removeService *Method:* DELETE \\ *Path:* v1/service/{name}/{id} \\ *Request Entity:* n/a \\ *Response Entity:* n/a \\ *Description:* {name} is the service name, {id} is the instance id. The specified service is deleted/unregistered. h2. get *Method:* GET \\ *Path:* v1/service/{name}/{id} \\ *Request Entity:* n/a \\ *Response Entity:* ServiceInstance \\ *Description:* {name} is the service name, {id} is the instance id. Returns the complete _ServiceInstance_ for the specified service. 404 is returned if not found. h2. getAllNames *Method:* GET \\ *Path:* v1/service \\ *Request Entity:* n/a \\ *Response Entity:* ServiceNames \\ *Description:* Returns all currently registered service names. h2. getAll *Method:* GET \\ *Path:* v1/service/{name} \\ *Request Entity:* n/a \\ *Response Entity:* ServiceInstances \\ *Description:* {name} is the service name. Returns all service instances for the named service. h2. getAny *Method:* GET \\ *Path:* v1/anyservice/{name} \\ *Request Entity:* n/a \\ *Response Entity:* ServiceInstance \\ *Description:* {name} is the service name. Return a random instance from the given service or 404. h2. JSON specs The JSON specifications for the REST entities are documented here: [[https://git-wip-us.apache.org/repos/asf?p=curator.git;a=blob_plain;f=curator-x-discovery-server/README.txt;hb=HEAD]] curator-apache-curator-2.7.1/curator-x-discovery-server/src/site/site.xml000066400000000000000000000026511245521677600265750ustar00rootroot00000000000000 curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/000077500000000000000000000000001245521677600251165ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/000077500000000000000000000000001245521677600260375ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/000077500000000000000000000000001245521677600266265ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/000077500000000000000000000000001245521677600300475ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/000077500000000000000000000000001245521677600315265ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/000077500000000000000000000000001245521677600317755ustar00rootroot00000000000000000077500000000000000000000000001245521677600337255ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery000077500000000000000000000000001245521677600352335ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server000077500000000000000000000000001245521677600377535ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jerseyMapDiscoveryResource.java000066400000000000000000000025721245521677600447410ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.jetty_jersey; import org.apache.curator.x.discovery.server.rest.DiscoveryContext; import org.apache.curator.x.discovery.server.rest.DiscoveryResource; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.ext.ContextResolver; import java.util.Map; @Path("/") public class MapDiscoveryResource extends DiscoveryResource> { public MapDiscoveryResource(@Context ContextResolver>> resolver) { super(resolver.getContext(DiscoveryContext.class)); } } ServiceDetails.java000066400000000000000000000044571245521677600435360ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.jetty_jersey; import java.util.HashMap; import java.util.Map; import org.codehaus.jackson.map.annotate.JsonRootName; /** * Service payload describing details of a service. */ @JsonRootName("details") public class ServiceDetails { private Map data; private String description; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public ServiceDetails() { this(new HashMap()); } public ServiceDetails(Map data) { this.data = data; } public void setData(Map data) { this.data = data; } public Map getData() { return data; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((data == null) ? 0 : data.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ServiceDetails other = (ServiceDetails) obj; if (data == null) { if (other.data != null) return false; } else if (!data.equals(other.data)) return false; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; return true; } } ServiceDetailsDiscoveryContext.java000066400000000000000000000033431245521677600467640ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.jetty_jersey; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.server.contexts.GenericDiscoveryContext; import org.apache.curator.x.discovery.server.rest.DiscoveryContext; /** * A DiscoveryContext that maps a concrete payload object of ServiceDetails */ @Provider public class ServiceDetailsDiscoveryContext extends GenericDiscoveryContext implements DiscoveryContext, ContextResolver> { public ServiceDetailsDiscoveryContext(ServiceDiscovery serviceDiscovery, ProviderStrategy providerStrategy, int instanceRefreshMs) { super(serviceDiscovery, providerStrategy, instanceRefreshMs, ServiceDetails.class); } } ServiceDetailsDiscoveryResource.java000066400000000000000000000025611245521677600471300ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.jetty_jersey; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.ext.ContextResolver; import org.apache.curator.x.discovery.server.rest.DiscoveryContext; import org.apache.curator.x.discovery.server.rest.DiscoveryResource; @Path("/") public class ServiceDetailsDiscoveryResource extends DiscoveryResource { public ServiceDetailsDiscoveryResource(@Context ContextResolver> resolver) { super(resolver.getContext(DiscoveryContext.class)); } } StringDiscoveryResource.java000066400000000000000000000025201245521677600454630ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.jetty_jersey; import org.apache.curator.x.discovery.server.rest.DiscoveryContext; import org.apache.curator.x.discovery.server.rest.DiscoveryResource; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.ext.ContextResolver; @Path("/") public class StringDiscoveryResource extends DiscoveryResource { public StringDiscoveryResource(@Context ContextResolver> resolver) { super(resolver.getContext(DiscoveryContext.class)); } } TestMapsWithJersey.java000066400000000000000000000151551245521677600444030ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.jetty_jersey; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.GenericType; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.core.DefaultResourceConfig; import com.sun.jersey.spi.container.servlet.ServletContainer; import org.apache.curator.test.InstanceSpec; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceType; import org.apache.curator.x.discovery.server.contexts.MapDiscoveryContext; import org.apache.curator.x.discovery.server.entity.JsonServiceInstanceMarshaller; import org.apache.curator.x.discovery.server.entity.JsonServiceInstancesMarshaller; import org.apache.curator.x.discovery.server.entity.JsonServiceNamesMarshaller; import org.apache.curator.x.discovery.server.entity.ServiceInstances; import org.apache.curator.x.discovery.server.entity.ServiceNames; import org.apache.curator.x.discovery.server.mocks.MockServiceDiscovery; import org.apache.curator.x.discovery.strategies.RandomStrategy; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; import java.util.Map; import java.util.Set; public class TestMapsWithJersey { private Server server; private JsonServiceNamesMarshaller serviceNamesMarshaller; private JsonServiceInstanceMarshaller> serviceInstanceMarshaller; private JsonServiceInstancesMarshaller> serviceInstancesMarshaller; private MapDiscoveryContext context; private int port; @BeforeMethod public void setup() throws Exception { context = new MapDiscoveryContext(new MockServiceDiscovery>(), new RandomStrategy>(), 1000); serviceNamesMarshaller = new JsonServiceNamesMarshaller(); serviceInstanceMarshaller = new JsonServiceInstanceMarshaller>(context); serviceInstancesMarshaller = new JsonServiceInstancesMarshaller>(context); Application application = new DefaultResourceConfig() { @Override public Set> getClasses() { Set> classes = Sets.newHashSet(); classes.add(MapDiscoveryResource.class); return classes; } @Override public Set getSingletons() { Set singletons = Sets.newHashSet(); singletons.add(context); singletons.add(serviceNamesMarshaller); singletons.add(serviceInstanceMarshaller); singletons.add(serviceInstancesMarshaller); return singletons; } }; ServletContainer container = new ServletContainer(application); port = InstanceSpec.getRandomPort(); server = new Server(port); Context root = new Context(server, "/", Context.SESSIONS); root.addServlet(new ServletHolder(container), "/*"); server.start(); } @AfterMethod public void teardown() throws Exception { server.stop(); server.join(); } @Test public void testRegisterService() throws Exception { Map payload = Maps.newHashMap(); payload.put("one", "1"); payload.put("two", "2"); payload.put("three", "3"); ServiceInstance> service = ServiceInstance.>builder() .name("test") .payload(payload) .serviceType(ServiceType.STATIC) .build(); ClientConfig config = new DefaultClientConfig() { @Override public Set getSingletons() { Set singletons = Sets.newHashSet(); singletons.add(context); singletons.add(serviceNamesMarshaller); singletons.add(serviceInstanceMarshaller); singletons.add(serviceInstancesMarshaller); return singletons; } }; Client client = Client.create(config); WebResource resource = client.resource("http://localhost:" + port); resource.path("/v1/service/test/" + service.getId()).type(MediaType.APPLICATION_JSON_TYPE).put(service); ServiceNames names = resource.path("/v1/service").get(ServiceNames.class); Assert.assertEquals(names.getNames(), Lists.newArrayList("test")); GenericType>> type = new GenericType>>(){}; ServiceInstances> instances = resource.path("/v1/service/test").get(type); Assert.assertEquals(instances.getServices().size(), 1); Assert.assertEquals(instances.getServices().get(0), service); Assert.assertEquals(instances.getServices().get(0).getPayload(), payload); // Retrieve a single instance GenericType>> singleInstanceType = new GenericType>>(){}; ServiceInstance> instance = resource.path("/v1/service/test/" + service.getId()).get(singleInstanceType); Assert.assertEquals(instance, service); } } TestObjectPayloadWithJersey.java000066400000000000000000000150461245521677600462220ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.jetty_jersey; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.GenericType; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.core.DefaultResourceConfig; import com.sun.jersey.spi.container.servlet.ServletContainer; import org.apache.curator.test.InstanceSpec; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceType; import org.apache.curator.x.discovery.server.entity.JsonServiceInstanceMarshaller; import org.apache.curator.x.discovery.server.entity.JsonServiceInstancesMarshaller; import org.apache.curator.x.discovery.server.entity.JsonServiceNamesMarshaller; import org.apache.curator.x.discovery.server.entity.ServiceInstances; import org.apache.curator.x.discovery.server.entity.ServiceNames; import org.apache.curator.x.discovery.server.mocks.MockServiceDiscovery; import org.apache.curator.x.discovery.strategies.RandomStrategy; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; import java.util.Set; public class TestObjectPayloadWithJersey { private Server server; private JsonServiceNamesMarshaller serviceNamesMarshaller; private JsonServiceInstanceMarshaller serviceInstanceMarshaller; private JsonServiceInstancesMarshaller serviceInstancesMarshaller; private ServiceDetailsDiscoveryContext context; private int port; @BeforeMethod public void setup() throws Exception { context = new ServiceDetailsDiscoveryContext(new MockServiceDiscovery(), new RandomStrategy(), 1000); serviceNamesMarshaller = new JsonServiceNamesMarshaller(); serviceInstanceMarshaller = new JsonServiceInstanceMarshaller(context); serviceInstancesMarshaller = new JsonServiceInstancesMarshaller(context); Application application = new DefaultResourceConfig() { @Override public Set> getClasses() { Set> classes = Sets.newHashSet(); classes.add(ServiceDetailsDiscoveryResource.class); return classes; } @Override public Set getSingletons() { Set singletons = Sets.newHashSet(); singletons.add(context); singletons.add(serviceNamesMarshaller); singletons.add(serviceInstanceMarshaller); singletons.add(serviceInstancesMarshaller); return singletons; } }; ServletContainer container = new ServletContainer(application); port = InstanceSpec.getRandomPort(); server = new Server(port); Context root = new Context(server, "/", Context.SESSIONS); root.addServlet(new ServletHolder(container), "/*"); server.start(); } @AfterMethod public void teardown() throws Exception { server.stop(); server.join(); } @Test public void testRegisterService() throws Exception { ServiceDetails payload = new ServiceDetails(); payload.setDescription("Example description for test"); payload.getData().put("one", "1"); payload.getData().put("two", "2"); payload.getData().put("three", "3"); ServiceInstance service = ServiceInstance.builder() .name("test") .payload(payload) .serviceType(ServiceType.STATIC) .build(); ClientConfig config = new DefaultClientConfig() { @Override public Set getSingletons() { Set singletons = Sets.newHashSet(); singletons.add(context); singletons.add(serviceNamesMarshaller); singletons.add(serviceInstanceMarshaller); singletons.add(serviceInstancesMarshaller); return singletons; } }; Client client = Client.create(config); WebResource resource = client.resource("http://localhost:" + port); resource.path("/v1/service/test/" + service.getId()).type(MediaType.APPLICATION_JSON_TYPE).put(service); ServiceNames names = resource.path("/v1/service").get(ServiceNames.class); Assert.assertEquals(names.getNames(), Lists.newArrayList("test")); GenericType> type = new GenericType>(){}; ServiceInstances instances = resource.path("/v1/service/test").get(type); Assert.assertEquals(instances.getServices().size(), 1); Assert.assertEquals(instances.getServices().get(0), service); Assert.assertEquals(instances.getServices().get(0).getPayload(), payload); // Retrieve a single instance GenericType> singleInstanceType = new GenericType>(){}; ServiceInstance instance = resource.path("/v1/service/test/" + service.getId()).get(singleInstanceType); Assert.assertEquals(instance, service); } } TestStringsWithJersey.java000066400000000000000000000157471245521677600451430ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.jetty_jersey; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.GenericType; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.core.DefaultResourceConfig; import com.sun.jersey.spi.container.servlet.ServletContainer; import org.apache.curator.test.InstanceSpec; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceType; import org.apache.curator.x.discovery.server.contexts.StringDiscoveryContext; import org.apache.curator.x.discovery.server.entity.JsonServiceInstanceMarshaller; import org.apache.curator.x.discovery.server.entity.JsonServiceInstancesMarshaller; import org.apache.curator.x.discovery.server.entity.JsonServiceNamesMarshaller; import org.apache.curator.x.discovery.server.entity.ServiceInstances; import org.apache.curator.x.discovery.server.entity.ServiceNames; import org.apache.curator.x.discovery.server.mocks.MockServiceDiscovery; import org.apache.curator.x.discovery.strategies.RandomStrategy; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; import java.util.Set; public class TestStringsWithJersey { private Server server; private JsonServiceNamesMarshaller serviceNamesMarshaller; private JsonServiceInstanceMarshaller serviceInstanceMarshaller; private JsonServiceInstancesMarshaller serviceInstancesMarshaller; private StringDiscoveryContext context; private int port; @BeforeMethod public void setup() throws Exception { context = new StringDiscoveryContext(new MockServiceDiscovery(), new RandomStrategy(), 1000); serviceNamesMarshaller = new JsonServiceNamesMarshaller(); serviceInstanceMarshaller = new JsonServiceInstanceMarshaller(context); serviceInstancesMarshaller = new JsonServiceInstancesMarshaller(context); Application application = new DefaultResourceConfig() { @Override public Set> getClasses() { Set> classes = Sets.newHashSet(); classes.add(StringDiscoveryResource.class); return classes; } @Override public Set getSingletons() { Set singletons = Sets.newHashSet(); singletons.add(context); singletons.add(serviceNamesMarshaller); singletons.add(serviceInstanceMarshaller); singletons.add(serviceInstancesMarshaller); return singletons; } }; ServletContainer container = new ServletContainer(application); port = InstanceSpec.getRandomPort(); server = new Server(port); Context root = new Context(server, "/", Context.SESSIONS); root.addServlet(new ServletHolder(container), "/*"); server.start(); } @AfterMethod public void teardown() throws Exception { server.stop(); server.join(); } @Test public void testRegisterService() throws Exception { ServiceInstance service = ServiceInstance.builder() .name("test") .payload("From Test") .serviceType(ServiceType.STATIC) .build(); ClientConfig config = new DefaultClientConfig() { @Override public Set getSingletons() { Set singletons = Sets.newHashSet(); singletons.add(context); singletons.add(serviceNamesMarshaller); singletons.add(serviceInstanceMarshaller); singletons.add(serviceInstancesMarshaller); return singletons; } }; Client client = Client.create(config); WebResource resource = client.resource("http://localhost:" + port); resource.path("/v1/service/test/" + service.getId()).type(MediaType.APPLICATION_JSON_TYPE).put(service); ServiceNames names = resource.path("/v1/service").get(ServiceNames.class); Assert.assertEquals(names.getNames(), Lists.newArrayList("test")); GenericType> type = new GenericType>(){}; ServiceInstances instances = resource.path("/v1/service/test").get(type); Assert.assertEquals(instances.getServices().size(), 1); Assert.assertEquals(instances.getServices().get(0), service); // Retrieve a single instance GenericType> singleInstanceType = new GenericType>(){}; ServiceInstance instance = resource.path("/v1/service/test/" + service.getId()).get(singleInstanceType); Assert.assertEquals(instance, service); } @Test public void testEmptyServiceNames() { ClientConfig config = new DefaultClientConfig() { @Override public Set getSingletons() { Set singletons = Sets.newHashSet(); singletons.add(context); singletons.add(serviceNamesMarshaller); singletons.add(serviceInstanceMarshaller); singletons.add(serviceInstancesMarshaller); return singletons; } }; Client client = Client.create(config); WebResource resource = client.resource("http://localhost:" + port); ServiceNames names = resource.path("/v1/service").get(ServiceNames.class); Assert.assertEquals(names.getNames(), Lists.newArrayList()); } } 000077500000000000000000000000001245521677600403115ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasyRestEasyApplication.java000066400000000000000000000035221245521677600451010ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.jetty_resteasy; import com.google.common.collect.Sets; import javax.ws.rs.core.Application; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; public class RestEasyApplication extends Application { public static final AtomicReference singletonsRef = new AtomicReference(new RestEasySingletons()); @Override public Set> getClasses() { Set> classes = Sets.newHashSet(); classes.add(StringDiscoveryResource.class); return classes; } @Override public Set getSingletons() { Set singletons = Sets.newHashSet(); singletons.add(singletonsRef.get().contextSingleton); singletons.add(singletonsRef.get().serviceNamesMarshallerSingleton); singletons.add(singletonsRef.get().serviceInstanceMarshallerSingleton); singletons.add(singletonsRef.get().serviceInstancesMarshallerSingleton); return singletons; } } RestEasySingletons.java000066400000000000000000000042411245521677600447620ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.jetty_resteasy; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.server.entity.JsonServiceInstanceMarshaller; import org.apache.curator.x.discovery.server.entity.JsonServiceInstancesMarshaller; import org.apache.curator.x.discovery.server.entity.JsonServiceNamesMarshaller; import org.apache.curator.x.discovery.server.mocks.MockServiceDiscovery; import org.apache.curator.x.discovery.server.contexts.StringDiscoveryContext; import org.apache.curator.x.discovery.strategies.RandomStrategy; /** * For testing purposes only. You will inject these however is appropriate for your application */ public class RestEasySingletons { public final ServiceDiscovery serviceDiscoverySingleton = new MockServiceDiscovery(); public final StringDiscoveryContext contextSingleton = new StringDiscoveryContext(serviceDiscoverySingleton, new RandomStrategy(), 1000); public final JsonServiceInstanceMarshaller serviceInstanceMarshallerSingleton = new JsonServiceInstanceMarshaller(contextSingleton); public final JsonServiceInstancesMarshaller serviceInstancesMarshallerSingleton = new JsonServiceInstancesMarshaller(contextSingleton); public final JsonServiceNamesMarshaller serviceNamesMarshallerSingleton = new JsonServiceNamesMarshaller(); } StringDiscoveryResource.java000066400000000000000000000033021245521677600460200ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.jetty_resteasy; import org.apache.curator.x.discovery.server.rest.DiscoveryContext; import org.apache.curator.x.discovery.server.rest.DiscoveryResource; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Providers; @Path("/") public class StringDiscoveryResource extends DiscoveryResource { public StringDiscoveryResource(@Context Providers providers) { super(getContextFromProvider(providers)); } private static DiscoveryContext getContextFromProvider(Providers providers) { ContextResolver contextResolver = providers.getContextResolver(DiscoveryContext.class, MediaType.WILDCARD_TYPE); //noinspection unchecked return contextResolver.getContext(DiscoveryContext.class); } } TestStringsWithRestEasy.java000066400000000000000000000142621245521677600457660ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.jetty_resteasy; import com.google.common.collect.Lists; import com.google.common.io.ByteStreams; import com.google.common.io.CharStreams; import org.apache.curator.test.InstanceSpec; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceType; import org.apache.curator.x.discovery.server.entity.ServiceInstances; import org.apache.curator.x.discovery.server.entity.ServiceNames; import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher; import org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap; import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import javax.ws.rs.core.MediaType; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; @SuppressWarnings("unchecked") public class TestStringsWithRestEasy { private Server server; private int port; @BeforeMethod public void setup() throws Exception { RestEasyApplication.singletonsRef.set(new RestEasySingletons()); ResteasyProviderFactory.setInstance(new ResteasyProviderFactory()); HttpServletDispatcher dispatcher = new HttpServletDispatcher(); port = InstanceSpec.getRandomPort(); server = new Server(port); Context root = new Context(server, "/", Context.SESSIONS); root.getInitParams().put("javax.ws.rs.Application", RestEasyApplication.class.getName()); root.addServlet(new ServletHolder(dispatcher), "/*"); root.addEventListener(new ResteasyBootstrap()); server.start(); } @AfterMethod public void teardown() throws Exception { server.stop(); server.join(); } @Test public void testRegisterService() throws Exception { RestEasySingletons restEasySingletons = RestEasyApplication.singletonsRef.get(); ServiceInstance service = ServiceInstance.builder() .name("test") .payload("From Test") .serviceType(ServiceType.STATIC) .build(); ByteArrayOutputStream out = new ByteArrayOutputStream(); restEasySingletons.serviceInstanceMarshallerSingleton.writeTo(service, null, null, null, null, null, out); getJson("http://localhost:" + port + "/v1/service/test/" + service.getId(), new String(out.toByteArray())); String json = getJson("http://localhost:" + port + "/v1/service", null); ServiceNames names = restEasySingletons.serviceNamesMarshallerSingleton.readFrom(ServiceNames.class, null, null, MediaType.APPLICATION_JSON_TYPE, null, new ByteArrayInputStream(json.getBytes())); Assert.assertEquals(names.getNames(), Lists.newArrayList("test")); json = getJson("http://localhost:" + port + "/v1/service/test", null); ServiceInstances instances = restEasySingletons.serviceInstancesMarshallerSingleton.readFrom(null, null, null, null, null, new ByteArrayInputStream(json.getBytes())); Assert.assertEquals(instances.getServices().size(), 1); Assert.assertEquals(instances.getServices().get(0), service); // Retrieve single instance json = getJson("http://localhost:" + port + "/v1/service/test/" + service.getId(), null); ServiceInstance instance = restEasySingletons.serviceInstanceMarshallerSingleton.readFrom(null, null, null, null, null, new ByteArrayInputStream(json.getBytes())); Assert.assertEquals(instance, service); } @Test public void testEmptyServiceNames() throws Exception { String json = getJson("http://localhost:" + port + "/v1/service", null); ServiceNames names = RestEasyApplication.singletonsRef.get().serviceNamesMarshallerSingleton.readFrom(ServiceNames.class, null, null, MediaType.APPLICATION_JSON_TYPE, null, new ByteArrayInputStream(json.getBytes())); Assert.assertEquals(names.getNames(), Lists.newArrayList()); } private String getJson(String urlStr, String body) throws IOException { URL url = new URL(urlStr); URLConnection urlConnection = url.openConnection(); urlConnection.addRequestProperty("Accept", "application/json"); if ( body != null ) { ((HttpURLConnection)urlConnection).setRequestMethod("PUT"); urlConnection.addRequestProperty("Content-Type", "application/json"); urlConnection.addRequestProperty("Content-Length", Integer.toString(body.length())); urlConnection.setDoOutput(true); OutputStream out = urlConnection.getOutputStream(); ByteStreams.copy(ByteStreams.newInputStreamSupplier(body.getBytes()), out); } BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); try { return CharStreams.toString(in); } finally { in.close(); } } } 000077500000000000000000000000001245521677600363475ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/mocksMockServiceDiscovery.java000066400000000000000000000066131245521677600433220ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/mocks/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.server.mocks; import com.google.common.base.Supplier; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import org.apache.curator.x.discovery.ServiceCacheBuilder; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceProviderBuilder; import java.io.IOException; import java.util.Collection; public class MockServiceDiscovery implements ServiceDiscovery { private final Multimap> services = Multimaps.synchronizedMultimap ( Multimaps.newMultimap ( Maps.>>newHashMap(), new Supplier>>() { @Override public Collection> get() { return Lists.newArrayList(); } } ) ); @Override public void start() throws Exception { } @Override public void registerService(ServiceInstance service) throws Exception { services.put(service.getName(), service); } @Override public void unregisterService(ServiceInstance service) throws Exception { services.remove(service.getName(), service); } @Override public void updateService(ServiceInstance service) throws Exception { services.put(service.getName(), service); } @Override public ServiceCacheBuilder serviceCacheBuilder() { throw new UnsupportedOperationException(); } @Override public Collection queryForNames() throws Exception { return services.keys(); } @Override public Collection> queryForInstances(String name) throws Exception { return services.get(name); } @Override public ServiceInstance queryForInstance(String name, String id) throws Exception { Collection> instances = services.get(name); for ( ServiceInstance instance : instances ) { if ( instance.getId().equals(id) ) { return instance; } } return null; } @Override public ServiceProviderBuilder serviceProviderBuilder() { throw new UnsupportedOperationException(); } @Override public void close() throws IOException { } } curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/resources/000077500000000000000000000000001245521677600271305ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery-server/src/test/resources/log4j.properties000066400000000000000000000021131245521677600322620ustar00rootroot00000000000000# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # log4j.rootLogger=ERROR, console log4j.logger.org.apache.curator=DEBUG, console log4j.additivity.org.apache.curator=false log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%-5p %c %x %m [%t]%n curator-apache-curator-2.7.1/curator-x-discovery/000077500000000000000000000000001245521677600220445ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/LICENSE000066400000000000000000000261361245521677600230610ustar00rootroot00000000000000 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. curator-apache-curator-2.7.1/curator-x-discovery/NOTICE000066400000000000000000000002501245521677600227450ustar00rootroot00000000000000Apache Curator Copyright 2013-2014 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). curator-apache-curator-2.7.1/curator-x-discovery/pom.xml000066400000000000000000000043741245521677600233710ustar00rootroot00000000000000 4.0.0 org.apache.curator apache-curator 2.7.1 curator-x-discovery 2.7.1 bundle Curator Service Discovery A service discovery recipe. 2011 * org.apache.curator.x.discovery*;version="${project.version}";-noimport:=true org.apache.curator curator-recipes org.codehaus.jackson jackson-mapper-asl org.apache.curator curator-test test curator-apache-curator-2.7.1/curator-x-discovery/src/000077500000000000000000000000001245521677600226335ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/000077500000000000000000000000001245521677600235575ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/000077500000000000000000000000001245521677600245005ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/000077500000000000000000000000001245521677600252675ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/000077500000000000000000000000001245521677600265105ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/000077500000000000000000000000001245521677600301675ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/000077500000000000000000000000001245521677600304365ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/000077500000000000000000000000001245521677600324455ustar00rootroot00000000000000DownInstancePolicy.java000066400000000000000000000035351245521677600370130ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import java.util.concurrent.TimeUnit; /** * Abstraction for values that determine when an instance is down */ public class DownInstancePolicy { private final long timeoutMs; private final int errorThreshold; private static final long DEFAULT_TIMEOUT_MS = 30000; private static final int DEFAULT_THRESHOLD = 2; /** * Policy with default values */ public DownInstancePolicy() { this(DEFAULT_TIMEOUT_MS, TimeUnit.MILLISECONDS, DEFAULT_THRESHOLD); } /** * @param timeout window of time for down instances * @param unit time unit * @param errorThreshold number of errors within time window that denotes a down instance */ public DownInstancePolicy(long timeout, TimeUnit unit, int errorThreshold) { this.timeoutMs = unit.toMillis(timeout); this.errorThreshold = errorThreshold; } public long getTimeoutMs() { return timeoutMs; } public int getErrorThreshold() { return errorThreshold; } } InstanceFilter.java000066400000000000000000000017661245521677600361550ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import com.google.common.base.Predicate; /** * Typedef for an Instance predicate */ public interface InstanceFilter extends Predicate> { } LocalIpFilter.java000066400000000000000000000021021245521677600357150ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; public interface LocalIpFilter { public boolean use(NetworkInterface networkInterface, InetAddress address) throws SocketException; } ProviderStrategy.java000066400000000000000000000024761245521677600365570ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import org.apache.curator.x.discovery.details.InstanceProvider; /** * A strategy for picking one from a set of instances */ public interface ProviderStrategy { /** * Given a source of instances, return one of them for a single use. * * @param instanceProvider the instance provider * @return the instance to use * @throws Exception any errors */ public ServiceInstance getInstance(InstanceProvider instanceProvider) throws Exception; } ServiceCache.java000066400000000000000000000032431245521677600355570ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import org.apache.curator.framework.listen.Listenable; import org.apache.curator.x.discovery.details.InstanceProvider; import org.apache.curator.x.discovery.details.ServiceCacheListener; import java.io.Closeable; import java.util.List; public interface ServiceCache extends Closeable, Listenable, InstanceProvider { /** * Return the current list of instances. NOTE: there is no guarantee of freshness. This is * merely the last known list of instances. However, the list is updated via a ZooKeeper watcher * so it should be fresh within a window of a second or two. * * @return the list */ public List> getInstances(); /** * The cache must be started before use * * @throws Exception errors */ public void start() throws Exception; } ServiceCacheBuilder.java000066400000000000000000000027261245521677600370730ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import java.util.concurrent.ThreadFactory; public interface ServiceCacheBuilder { /** * Return a new service cache with the current settings * * @return service cache */ public ServiceCache build(); /** * The name of the service to cache (required) * * @param name service name * @return this */ public ServiceCacheBuilder name(String name); /** * Optional thread factory to use for the cache's internal thread * * @param threadFactory factory * @return this */ public ServiceCacheBuilder threadFactory(ThreadFactory threadFactory); } ServiceDiscovery.java000066400000000000000000000057671245521677600365400ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import org.apache.curator.x.discovery.strategies.RoundRobinStrategy; import java.io.Closeable; import java.util.Collection; public interface ServiceDiscovery extends Closeable { /** * The discovery must be started before use * * @throws Exception errors */ public void start() throws Exception; /** * Register/re-register a service * * @param service service to add * @throws Exception errors */ public void registerService(ServiceInstance service) throws Exception; /** * Update a service * * @param service service to update * @throws Exception errors */ public void updateService(ServiceInstance service) throws Exception; /** * Unregister/remove a service instance * * @param service the service * @throws Exception errors */ public void unregisterService(ServiceInstance service) throws Exception; /** * Allocate a new service cache builder. The refresh padding is defaulted to 1 second. * * @return new cache builder */ public ServiceCacheBuilder serviceCacheBuilder(); /** * Return the names of all known services * * @return list of service names * @throws Exception errors */ public Collection queryForNames() throws Exception; /** * Return all known instances for the given service * * @param name name of the service * @return list of instances (or an empty list) * @throws Exception errors */ public Collection> queryForInstances(String name) throws Exception; /** * Return a service instance POJO * * @param name name of the service * @param id ID of the instance * @return the instance or null if not found * @throws Exception errors */ public ServiceInstance queryForInstance(String name, String id) throws Exception; /** * Allocate a new builder. {@link ServiceProviderBuilder#providerStrategy} is set to {@link RoundRobinStrategy} * * @return the builder */ public ServiceProviderBuilder serviceProviderBuilder(); } ServiceDiscoveryBuilder.java000066400000000000000000000077741245521677600400470ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.x.discovery.details.InstanceSerializer; import org.apache.curator.x.discovery.details.JsonInstanceSerializer; import org.apache.curator.x.discovery.details.ServiceDiscoveryImpl; public class ServiceDiscoveryBuilder { private CuratorFramework client; private String basePath; private InstanceSerializer serializer; private ServiceInstance thisInstance; private Class payloadClass; private boolean watchInstances = false; /** * Return a new builder. * * @param payloadClass the class of the payload of your service instance (you can use {@link Void} * if your instances don't need a payload) * @return new builder */ public static ServiceDiscoveryBuilder builder(Class payloadClass) { return new ServiceDiscoveryBuilder(payloadClass); } /** * Build a new service discovery with the currently set values. If not set, the builder will be * defaulted with a {@link JsonInstanceSerializer}. * * @return new service discovery */ public ServiceDiscovery build() { if ( serializer == null ) { serializer(new JsonInstanceSerializer(payloadClass)); } return new ServiceDiscoveryImpl(client, basePath, serializer, thisInstance, watchInstances); } /** * Required - set the client to use * * @param client client * @return this */ public ServiceDiscoveryBuilder client(CuratorFramework client) { this.client = client; return this; } /** * Required - set the base path to store in ZK * * @param basePath base path * @return this */ public ServiceDiscoveryBuilder basePath(String basePath) { this.basePath = basePath; return this; } /** * optional - change the serializer used (the default is {@link JsonInstanceSerializer} * * @param serializer the serializer * @return this */ public ServiceDiscoveryBuilder serializer(InstanceSerializer serializer) { this.serializer = serializer; return this; } /** * Optional - instance that represents the service that is running. The instance will get auto-registered * * @param thisInstance initial instance * @return this */ public ServiceDiscoveryBuilder thisInstance(ServiceInstance thisInstance) { this.thisInstance = thisInstance; return this; } /** * Optional - if true, watches for changes to locally registered instances * (via {@link #thisInstance(ServiceInstance)} or {@link ServiceDiscovery#registerService(ServiceInstance)}). * If the data for instances changes, they are reloaded. * * @param watchInstances true to watch instances * @return this */ public ServiceDiscoveryBuilder watchInstances(boolean watchInstances) { this.watchInstances = watchInstances; return this; } ServiceDiscoveryBuilder(Class payloadClass) { this.payloadClass = payloadClass; } } ServiceInstance.java000066400000000000000000000162021245521677600363170ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import java.net.InetAddress; import java.util.Collection; import java.util.Map; import java.util.UUID; import org.codehaus.jackson.annotate.JsonTypeInfo; import org.codehaus.jackson.annotate.JsonTypeInfo.Id; /** * POJO that represents a service instance */ public class ServiceInstance { private final String name; private final String id; private final String address; private final Integer port; private final Integer sslPort; private final T payload; private final long registrationTimeUTC; private final ServiceType serviceType; private final UriSpec uriSpec; /** * Return a new builder. The {@link #address} is set to the ip of the first * NIC in the system. The {@link #id} is set to a random UUID. * * @return builder * @throws Exception errors getting the local IP */ public static ServiceInstanceBuilderbuilder() throws Exception { String address = null; Collection ips = ServiceInstanceBuilder.getAllLocalIPs(); if ( ips.size() > 0 ) { address = ips.iterator().next().getHostAddress(); // default to the first address } String id = UUID.randomUUID().toString(); return new ServiceInstanceBuilder().address(address).id(id).registrationTimeUTC(System.currentTimeMillis()); } /** * @param name name of the service * @param id id of this instance (must be unique) * @param address address of this instance * @param port the port for this instance or null * @param sslPort the SSL port for this instance or null * @param payload the payload for this instance or null * @param registrationTimeUTC the time (in UTC) of the registration * @param serviceType type of the service * @param uriSpec the uri spec or null */ public ServiceInstance(String name, String id, String address, Integer port, Integer sslPort, T payload, long registrationTimeUTC, ServiceType serviceType, UriSpec uriSpec) { name = Preconditions.checkNotNull(name, "name cannot be null"); id = Preconditions.checkNotNull(id, "id cannot be null"); this.serviceType = serviceType; this.uriSpec = uriSpec; this.name = name; this.id = id; this.address = address; this.port = port; this.sslPort = sslPort; this.payload = payload; this.registrationTimeUTC = registrationTimeUTC; } /** * Inits to default values. Only exists for deserialization */ ServiceInstance() { this("", "", null, null, null, null, 0, ServiceType.DYNAMIC, null); } public String getName() { return name; } public String getId() { return id; } public String getAddress() { return address; } public Integer getPort() { return port; } public Integer getSslPort() { return sslPort; } @JsonTypeInfo(use=Id.CLASS, defaultImpl=Object.class) public T getPayload() { return payload; } public long getRegistrationTimeUTC() { return registrationTimeUTC; } public ServiceType getServiceType() { return serviceType; } public UriSpec getUriSpec() { return uriSpec; } public String buildUriSpec() { return buildUriSpec(Maps.newHashMap()); } public String buildUriSpec(Map variables) { return (uriSpec != null) ? uriSpec.build(this, variables) : ""; } @SuppressWarnings("RedundantIfStatement") @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } ServiceInstance that = (ServiceInstance)o; if ( registrationTimeUTC != that.registrationTimeUTC ) { return false; } if ( address != null ? !address.equals(that.address) : that.address != null ) { return false; } if ( id != null ? !id.equals(that.id) : that.id != null ) { return false; } if ( name != null ? !name.equals(that.name) : that.name != null ) { return false; } if ( payload != null ? !payload.equals(that.payload) : that.payload != null ) { return false; } if ( port != null ? !port.equals(that.port) : that.port != null ) { return false; } if ( serviceType != that.serviceType ) { return false; } if ( sslPort != null ? !sslPort.equals(that.sslPort) : that.sslPort != null ) { return false; } if ( uriSpec != null ? !uriSpec.equals(that.uriSpec) : that.uriSpec != null ) { return false; } return true; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (id != null ? id.hashCode() : 0); result = 31 * result + (address != null ? address.hashCode() : 0); result = 31 * result + (port != null ? port.hashCode() : 0); result = 31 * result + (sslPort != null ? sslPort.hashCode() : 0); result = 31 * result + (payload != null ? payload.hashCode() : 0); result = 31 * result + (int)(registrationTimeUTC ^ (registrationTimeUTC >>> 32)); result = 31 * result + (serviceType != null ? serviceType.hashCode() : 0); result = 31 * result + (uriSpec != null ? uriSpec.hashCode() : 0); return result; } @Override public String toString() { return "ServiceInstance{" + "name='" + name + '\'' + ", id='" + id + '\'' + ", address='" + address + '\'' + ", port=" + port + ", sslPort=" + sslPort + ", payload=" + payload + ", registrationTimeUTC=" + registrationTimeUTC + ", serviceType=" + serviceType + ", uriSpec=" + uriSpec + '}'; } } ServiceInstanceBuilder.java000066400000000000000000000123151245521677600376270ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import com.google.common.collect.Lists; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Collection; import java.util.Enumeration; import java.util.List; import java.util.concurrent.atomic.AtomicReference; /** * Builder for service instances */ public class ServiceInstanceBuilder { private T payload; private String name; private String address; private Integer port; private Integer sslPort; private String id; private long registrationTimeUTC; private ServiceType serviceType = ServiceType.DYNAMIC; private UriSpec uriSpec; private static final AtomicReference localIpFilter = new AtomicReference ( new LocalIpFilter() { @Override public boolean use(NetworkInterface nif, InetAddress adr) throws SocketException { return (adr != null) && !adr.isLoopbackAddress() && (nif.isPointToPoint() || !adr.isLinkLocalAddress()); } } ); /** * Replace the default local ip filter used by {@link #getAllLocalIPs()} * * @param newLocalIpFilter the new local ip filter */ public static void setLocalIpFilter(LocalIpFilter newLocalIpFilter) { localIpFilter.set(newLocalIpFilter); } /** * Return the current local ip filter used by {@link #getAllLocalIPs()} * * @return ip filter */ public static LocalIpFilter getLocalIpFilter() { return localIpFilter.get(); } ServiceInstanceBuilder() { } /** * Return a new instance with the currently set values * * @return instance */ public ServiceInstance build() { return new ServiceInstance(name, id, address, port, sslPort, payload, registrationTimeUTC, serviceType, uriSpec); } public ServiceInstanceBuilder name(String name) { this.name = name; return this; } public ServiceInstanceBuilder address(String address) { this.address = address; return this; } public ServiceInstanceBuilder id(String id) { this.id = id; return this; } public ServiceInstanceBuilder port(int port) { this.port = port; return this; } public ServiceInstanceBuilder sslPort(int port) { this.sslPort = port; return this; } public ServiceInstanceBuilder payload(T payload) { this.payload = payload; return this; } public ServiceInstanceBuilder serviceType(ServiceType serviceType) { this.serviceType = serviceType; return this; } public ServiceInstanceBuilder registrationTimeUTC(long registrationTimeUTC) { this.registrationTimeUTC = registrationTimeUTC; return this; } public ServiceInstanceBuilder uriSpec(UriSpec uriSpec) { this.uriSpec = uriSpec; return this; } /** * based on http://pastebin.com/5X073pUc *

* * Returns all available IP addresses. *

* In error case or if no network connection is established, we return * an empty list here. *

* Loopback addresses are excluded - so 127.0.0.1 will not be never * returned. *

* The "primary" IP might not be the first one in the returned list. * * @return Returns all IP addresses (can be an empty list in error case * or if network connection is missing). * @since 0.1.0 * @throws SocketException errors */ public static Collection getAllLocalIPs() throws SocketException { List listAdr = Lists.newArrayList(); Enumeration nifs = NetworkInterface.getNetworkInterfaces(); if (nifs == null) return listAdr; while (nifs.hasMoreElements()) { NetworkInterface nif = nifs.nextElement(); // We ignore subinterfaces - as not yet needed. Enumeration adrs = nif.getInetAddresses(); while ( adrs.hasMoreElements() ) { InetAddress adr = adrs.nextElement(); if ( localIpFilter.get().use(nif, adr) ) { listAdr.add(adr); } } } return listAdr; } } ServiceProvider.java000066400000000000000000000043501245521677600363460ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import org.apache.curator.x.discovery.details.InstanceProvider; import java.io.Closeable; import java.util.Collection; /** * The main API for Discovery. This class is essentially a facade over a {@link ProviderStrategy} * paired with an {@link InstanceProvider} */ public interface ServiceProvider extends Closeable { /** * The provider must be started before use * * @throws Exception any errors */ public void start() throws Exception; /** * Return an instance for a single use. IMPORTANT: users * should not hold on to the instance returned. They should always get a fresh instance. * * @return the instance to use * @throws Exception any errors */ public ServiceInstance getInstance() throws Exception; /** * Return the current available set of instances IMPORTANT: users * should not hold on to the instance returned. They should always get a fresh list. * * @return all known instances * @throws Exception any errors */ public Collection> getAllInstances() throws Exception; /** * Take note of an error connecting to the given instance. The instance will potentially * be marked as "down" depending on the {@link DownInstancePolicy}. * * @param instance instance that had an error */ public void noteError(ServiceInstance instance); } ServiceProviderBuilder.java000066400000000000000000000046641245521677600376650ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import org.apache.curator.x.discovery.strategies.RoundRobinStrategy; import java.util.concurrent.ThreadFactory; public interface ServiceProviderBuilder { /** * Allocate a new service provider based on the current builder settings * * @return provider */ public ServiceProvider build(); /** * required - set the name of the service to be provided * * @param serviceName the name of the service * @return this */ public ServiceProviderBuilder serviceName(String serviceName); /** * optional - set the provider strategy. The default is {@link RoundRobinStrategy} * * @param providerStrategy strategy to use * @return this */ public ServiceProviderBuilder providerStrategy(ProviderStrategy providerStrategy); /** * optional - the thread factory to use for creating internal threads * * @param threadFactory factory to use * @return this */ public ServiceProviderBuilder threadFactory(ThreadFactory threadFactory); /** * Set the down instance policy * * @param downInstancePolicy new policy * @return this */ public ServiceProviderBuilder downInstancePolicy(DownInstancePolicy downInstancePolicy); /** * Add an instance filter. NOTE: this does not remove previously added filters. i.e. * a l;ist is created of all added filters. Filters are called in the order they were * added. * * @param filter filter to add * @return this */ public ServiceProviderBuilder additionalFilter(InstanceFilter filter); } ServiceType.java000066400000000000000000000016251245521677600354770ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; public enum ServiceType { DYNAMIC, STATIC, PERMANENT } UriSpec.java000066400000000000000000000251331245521677600346070ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; /** *

* An abstraction for specifying a URI for an instance allowing for variable substitutions. *

* *

* A Uri spec is a string with optional replacement fields. A replacement field begins with * an open brace and ends with a close brace. The value between the braces is the name of the * field. e.g. "{scheme}://foo.com:{port}" has two replacement fields named "scheme" and "port". * Several pre-defined fields are listed as constants in this class (e.g. {@link #FIELD_SCHEME}). *

*/ public class UriSpec implements Iterable { private final Logger log = LoggerFactory.getLogger(getClass()); private final List parts = Lists.newArrayList(); /** * This defaults to "http". If a {@link ServiceInstance} is passed when building and an sslPort * is specified in the instance, the replacement is "https". */ public static final String FIELD_SCHEME = "scheme"; /** * If a {@link ServiceInstance} is passed when building, the replacement is {@link ServiceInstance#getName()} */ public static final String FIELD_NAME = "name"; /** * If a {@link ServiceInstance} is passed when building, the replacement is {@link ServiceInstance#getId()} */ public static final String FIELD_ID = "id"; /** * If a {@link ServiceInstance} is passed when building, the replacement is {@link ServiceInstance#getAddress()} */ public static final String FIELD_ADDRESS = "address"; /** * If a {@link ServiceInstance} is passed when building, the replacement is {@link ServiceInstance#getPort()} */ public static final String FIELD_PORT = "port"; /** * If a {@link ServiceInstance} is passed when building, the replacement is {@link ServiceInstance#getSslPort()} */ public static final String FIELD_SSL_PORT = "ssl-port"; /** * If a {@link ServiceInstance} is passed when building, the replacement is {@link ServiceInstance#getRegistrationTimeUTC()} */ public static final String FIELD_REGISTRATION_TIME_UTC = "registration-time-utc"; /** * If a {@link ServiceInstance} is passed when building, the replacement is {@link ServiceInstance#getServiceType()} */ public static final String FIELD_SERVICE_TYPE = "service-type"; /** * Always replaced with '{' - i.e. this is how to insert a literal '{' */ public static final String FIELD_OPEN_BRACE = "["; /** * Always replaced with '}' - i.e. this is how to insert a literal '}' */ public static final String FIELD_CLOSE_BRACE = "]"; /** * Represents one token in the Uri spec */ public static class Part { private final String value; private final boolean variable; /** * @param value the token value * @param isVariable if true, a replacement field. If false, a literal string */ public Part(String value, boolean isVariable) { this.value = value; this.variable = isVariable; } public Part() { value = ""; variable = false; } public String getValue() { return value; } public boolean isVariable() { return variable; } @SuppressWarnings("RedundantIfStatement") @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } Part part = (Part)o; if ( variable != part.variable ) { return false; } if ( !value.equals(part.value) ) { return false; } return true; } @Override public int hashCode() { int result = value.hashCode(); result = 31 * result + (variable ? 1 : 0); return result; } } public UriSpec() { // NOP } /** * @param rawSpec the spec to parse */ public UriSpec(String rawSpec) { boolean isInsideVariable = false; StringTokenizer tokenizer = new StringTokenizer(rawSpec, "{}", true); while ( tokenizer.hasMoreTokens() ) { String token = tokenizer.nextToken(); if ( token.equals("{") ) { Preconditions.checkState(!isInsideVariable, "{ is not allowed inside of a variable specification"); isInsideVariable = true; } else if ( token.equals("}") ) { Preconditions.checkState(isInsideVariable, "} must be preceded by {"); isInsideVariable = false; } else { if ( isInsideVariable ) { token = token.trim(); } add(new Part(token, isInsideVariable)); } } Preconditions.checkState(!isInsideVariable, "Final variable not closed - expected }"); } /** * Build into a UriSpec string * * @return UriSpec string */ public String build() { return build(null, Maps.newHashMap()); } /** * Build into a UriSpec string * * @param serviceInstance instance to use for pre-defined replacement fields * @return UriSpec string */ public String build(ServiceInstance serviceInstance) { return build(serviceInstance, Maps.newHashMap()); } /** * Build into a UriSpec string * * @param variables a mapping of field replacement names to values. Note: any fields listed * in this map override pre-defined fields * @return UriSpec string */ public String build(Map variables) { return build(null, variables); } /** * Build into a UriSpec string * * @param serviceInstance instance to use for pre-defined replacement fields * @param variables a mapping of field replacement names to values. Note: any fields listed * in this map override pre-defined fields * @return UriSpec string */ public String build(ServiceInstance serviceInstance, Map variables) { Map localVariables = Maps.newHashMap(); localVariables.put(FIELD_OPEN_BRACE, "{"); localVariables.put(FIELD_CLOSE_BRACE, "}"); localVariables.put(FIELD_SCHEME, "http"); if ( serviceInstance != null ) { localVariables.put(FIELD_NAME, nullCheck(serviceInstance.getName())); localVariables.put(FIELD_ID, nullCheck(serviceInstance.getId())); localVariables.put(FIELD_ADDRESS, nullCheck(serviceInstance.getAddress())); localVariables.put(FIELD_PORT, nullCheck(serviceInstance.getPort())); localVariables.put(FIELD_SSL_PORT, nullCheck(serviceInstance.getSslPort())); localVariables.put(FIELD_REGISTRATION_TIME_UTC, nullCheck(serviceInstance.getRegistrationTimeUTC())); localVariables.put(FIELD_SERVICE_TYPE, (serviceInstance.getServiceType() != null) ? serviceInstance.getServiceType().name().toLowerCase() : ""); if ( serviceInstance.getSslPort() != null ) { localVariables.put(FIELD_SCHEME, "https"); } } localVariables.putAll(variables); StringBuilder str = new StringBuilder(); for ( Part p : parts ) { if ( p.isVariable() ) { Object value = localVariables.get(p.getValue()); if ( value == null ) { log.debug("Variable not found: " + p.getValue()); } else { str.append(value); } } else { str.append(p.getValue()); } } return str.toString(); } @Override public Iterator iterator() { return Iterators.unmodifiableIterator(parts.iterator()); } /** * @return the parts */ public List getParts() { return ImmutableList.copyOf(parts); } /** * Add a part to the end of the list * * @param part part to add */ public void add(Part part) { parts.add(part); } /** * Remove the given part * * @param part the part */ public void remove(Part part) { parts.remove(part); } @SuppressWarnings("RedundantIfStatement") @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } UriSpec spec = (UriSpec)o; if ( !parts.equals(spec.parts) ) { return false; } return true; } @Override public int hashCode() { return parts.hashCode(); } private Object nullCheck(Object o) { return (o != null) ? o : ""; } } 000077500000000000000000000000001245521677600340135ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/detailsDownInstanceManager.java000066400000000000000000000062571245521677600405570ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.details; import com.google.common.collect.Maps; import org.apache.curator.x.discovery.DownInstancePolicy; import org.apache.curator.x.discovery.InstanceFilter; import org.apache.curator.x.discovery.ServiceInstance; import java.util.Iterator; import java.util.Map.Entry; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; class DownInstanceManager implements InstanceFilter { private final ConcurrentMap, Status> statuses = Maps.newConcurrentMap(); private final DownInstancePolicy downInstancePolicy; private final AtomicLong lastPurge = new AtomicLong(System.currentTimeMillis()); private static class Status { private final long startMs = System.currentTimeMillis(); private final AtomicInteger errorCount = new AtomicInteger(0); } DownInstanceManager(DownInstancePolicy downInstancePolicy) { this.downInstancePolicy = downInstancePolicy; } void add(ServiceInstance instance) { purge(); Status newStatus = new Status(); Status oldStatus = statuses.putIfAbsent(instance, newStatus); Status useStatus = (oldStatus != null) ? oldStatus : newStatus; useStatus.errorCount.incrementAndGet(); } @Override public boolean apply(ServiceInstance instance) { purge(); Status status = statuses.get(instance); return (status == null) || (status.errorCount.get() < downInstancePolicy.getErrorThreshold()); } private void purge() { long localLastPurge = lastPurge.get(); long ticksSinceLastPurge = System.currentTimeMillis() - localLastPurge; if ( ticksSinceLastPurge < (downInstancePolicy.getTimeoutMs() / 2) ) { return; } if ( !lastPurge.compareAndSet(localLastPurge, System.currentTimeMillis()) ) { return; } Iterator, Status>> it = statuses.entrySet().iterator(); while ( it.hasNext() ) { Entry, Status> entry = it.next(); long elapsedMs = System.currentTimeMillis() - entry.getValue().startMs; if ( elapsedMs >= downInstancePolicy.getTimeoutMs() ) { it.remove(); } } } } FilteredInstanceProvider.java000066400000000000000000000034251245521677600416200ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.details; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import org.apache.curator.x.discovery.InstanceFilter; import org.apache.curator.x.discovery.ServiceInstance; import java.util.List; class FilteredInstanceProvider implements InstanceProvider { private final InstanceProvider instanceProvider; private final Predicate> predicates; FilteredInstanceProvider(InstanceProvider instanceProvider, List> filters) { this.instanceProvider = instanceProvider; predicates = Predicates.and(filters); } @Override public List> getInstances() throws Exception { Iterable> filtered = Iterables.filter(instanceProvider.getInstances(), predicates); return ImmutableList.copyOf(filtered); } } InstanceProvider.java000066400000000000000000000024051245521677600401360ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.details; import org.apache.curator.x.discovery.ServiceInstance; import java.util.List; /** * Provides a set of available instances for a service so that a strategy can pick one of them */ public interface InstanceProvider { /** * Return the current available set of instances * @return instances * @throws Exception any errors */ public List> getInstances() throws Exception; } InstanceSerializer.java000066400000000000000000000027731245521677600404650ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.details; import org.apache.curator.x.discovery.ServiceInstance; /** * Injectable serializer for service instances */ public interface InstanceSerializer { /** * Serialize an instance into bytes * * @param instance the instance * @return byte array representing the instance * @throws Exception any errors */ public byte[] serialize(ServiceInstance instance) throws Exception; /** * Deserialize a byte array into an instance * * @param bytes the bytes * @return service instance * @throws Exception any errors */ public ServiceInstance deserialize(byte[] bytes) throws Exception; } JsonInstanceSerializer.java000066400000000000000000000044241245521677600413120ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.details; import org.apache.curator.x.discovery.ServiceInstance; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.JavaType; import java.io.ByteArrayOutputStream; /** * A serializer that uses Jackson to serialize/deserialize as JSON. IMPORTANT: The instance * payload must support Jackson */ public class JsonInstanceSerializer implements InstanceSerializer { private final ObjectMapper mapper; private final Class payloadClass; private final JavaType type; /** * @param payloadClass used to validate payloads when deserializing */ public JsonInstanceSerializer(Class payloadClass) { this.payloadClass = payloadClass; mapper = new ObjectMapper(); type = mapper.getTypeFactory().constructType(ServiceInstance.class); } @SuppressWarnings({"unchecked"}) @Override public ServiceInstance deserialize(byte[] bytes) throws Exception { ServiceInstance rawServiceInstance = mapper.readValue(bytes, type); payloadClass.cast(rawServiceInstance.getPayload()); // just to verify that it's the correct type return (ServiceInstance)rawServiceInstance; } @Override public byte[] serialize(ServiceInstance instance) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); mapper.writeValue(out, instance); return out.toByteArray(); } } Latch.java000066400000000000000000000022351245521677600357130ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.details; class Latch { private volatile boolean laden = false; synchronized void set() { laden = true; notifyAll(); } synchronized void await() throws InterruptedException { while ( !laden ) { wait(); } laden = false; } } ServiceCacheBuilderImpl.java000066400000000000000000000041641245521677600413400ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.details; import org.apache.curator.x.discovery.ServiceCache; import org.apache.curator.x.discovery.ServiceCacheBuilder; import java.util.concurrent.ThreadFactory; /** * Builder for a service cache */ class ServiceCacheBuilderImpl implements ServiceCacheBuilder { private ServiceDiscoveryImpl discovery; private String name; private ThreadFactory threadFactory; ServiceCacheBuilderImpl(ServiceDiscoveryImpl discovery) { this.discovery = discovery; } /** * Return a new service cache with the current settings * * @return service cache */ @Override public ServiceCache build() { return new ServiceCacheImpl(discovery, name, threadFactory); } /** * The name of the service to cache (required) * * @param name service name * @return this */ @Override public ServiceCacheBuilder name(String name) { this.name = name; return this; } /** * Optional thread factory to use for the cache's internal thread * * @param threadFactory factory * @return this */ @Override public ServiceCacheBuilder threadFactory(ThreadFactory threadFactory) { this.threadFactory = threadFactory; return this; } } ServiceCacheImpl.java000066400000000000000000000152401245521677600400260ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.details; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.listen.ListenerContainer; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.PathChildrenCache; import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent; import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener; import org.apache.curator.utils.ZKPaths; import org.apache.curator.x.discovery.ServiceCache; import org.apache.curator.x.discovery.ServiceInstance; import java.io.IOException; import java.util.List; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicReference; public class ServiceCacheImpl implements ServiceCache, PathChildrenCacheListener { private final ListenerContainer listenerContainer = new ListenerContainer(); private final ServiceDiscoveryImpl discovery; private final AtomicReference state = new AtomicReference(State.LATENT); private final PathChildrenCache cache; private final ConcurrentMap> instances = Maps.newConcurrentMap(); private enum State { LATENT, STARTED, STOPPED } ServiceCacheImpl(ServiceDiscoveryImpl discovery, String name, ThreadFactory threadFactory) { Preconditions.checkNotNull(discovery, "discovery cannot be null"); Preconditions.checkNotNull(name, "name cannot be null"); Preconditions.checkNotNull(threadFactory, "threadFactory cannot be null"); this.discovery = discovery; cache = new PathChildrenCache(discovery.getClient(), discovery.pathForName(name), true, threadFactory); cache.getListenable().addListener(this); } @Override public List> getInstances() { return Lists.newArrayList(instances.values()); } @Override public void start() throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); cache.start(true); for ( ChildData childData : cache.getCurrentData() ) { addInstance(childData, true); } discovery.cacheOpened(this); } @Override public void close() throws IOException { Preconditions.checkState(state.compareAndSet(State.STARTED, State.STOPPED), "Already closed or has not been started"); listenerContainer.forEach ( new Function() { @Override public Void apply(ServiceCacheListener listener) { discovery.getClient().getConnectionStateListenable().removeListener(listener); return null; } } ); listenerContainer.clear(); CloseableUtils.closeQuietly(cache); discovery.cacheClosed(this); } @Override public void addListener(ServiceCacheListener listener) { listenerContainer.addListener(listener); discovery.getClient().getConnectionStateListenable().addListener(listener); } @Override public void addListener(ServiceCacheListener listener, Executor executor) { listenerContainer.addListener(listener, executor); discovery.getClient().getConnectionStateListenable().addListener(listener, executor); } @Override public void removeListener(ServiceCacheListener listener) { listenerContainer.removeListener(listener); discovery.getClient().getConnectionStateListenable().removeListener(listener); } @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { boolean notifyListeners = false; switch ( event.getType() ) { case CHILD_ADDED: case CHILD_UPDATED: { addInstance(event.getData(), false); notifyListeners = true; break; } case CHILD_REMOVED: { instances.remove(instanceIdFromData(event.getData())); notifyListeners = true; break; } } if ( notifyListeners ) { listenerContainer.forEach ( new Function() { @Override public Void apply(ServiceCacheListener listener) { listener.cacheChanged(); return null; } } ); } } private String instanceIdFromData(ChildData childData) { return ZKPaths.getNodeFromPath(childData.getPath()); } private void addInstance(ChildData childData, boolean onlyIfAbsent) throws Exception { String instanceId = instanceIdFromData(childData); ServiceInstance serviceInstance = discovery.getSerializer().deserialize(childData.getData()); if ( onlyIfAbsent ) { instances.putIfAbsent(instanceId, serviceInstance); } else { instances.put(instanceId, serviceInstance); } cache.clearDataBytes(childData.getPath(), childData.getStat().getVersion()); } } ServiceCacheListener.java000066400000000000000000000022241245521677600407100ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.details; import org.apache.curator.framework.state.ConnectionStateListener; /** * Listener for changes to a service cache */ public interface ServiceCacheListener extends ConnectionStateListener { /** * Called when the cache has changed (instances added/deleted, etc.) */ public void cacheChanged(); } ServiceDiscoveryImpl.java000066400000000000000000000360611245521677600407760ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.details; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.cache.NodeCache; import org.apache.curator.framework.recipes.cache.NodeCacheListener; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.utils.ThreadUtils; import org.apache.curator.utils.ZKPaths; import org.apache.curator.x.discovery.ServiceCache; import org.apache.curator.x.discovery.ServiceCacheBuilder; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceProvider; import org.apache.curator.x.discovery.ServiceProviderBuilder; import org.apache.curator.x.discovery.ServiceType; import org.apache.curator.x.discovery.strategies.RoundRobinStrategy; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Watcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; /** * A mechanism to register and query service instances using ZooKeeper */ public class ServiceDiscoveryImpl implements ServiceDiscovery { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework client; private final String basePath; private final InstanceSerializer serializer; private final Map> services = Maps.newConcurrentMap(); private final Map watchedServices; private final Collection> caches = Sets.newSetFromMap(Maps., Boolean>newConcurrentMap()); private final Collection> providers = Sets.newSetFromMap(Maps., Boolean>newConcurrentMap()); private final ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( (newState == ConnectionState.RECONNECTED) || (newState == ConnectionState.CONNECTED) ) { try { log.debug("Re-registering due to reconnection"); reRegisterServices(); } catch ( Exception e ) { log.error("Could not re-register instances after reconnection", e); } } } }; /** * @param client the client * @param basePath base path to store data * @param serializer serializer for instances (e.g. {@link JsonInstanceSerializer}) * @param thisInstance instance that represents the service that is running. The instance will get auto-registered * @param watchInstances if true, watches for changes to locally registered instances */ public ServiceDiscoveryImpl(CuratorFramework client, String basePath, InstanceSerializer serializer, ServiceInstance thisInstance, boolean watchInstances) { this.client = Preconditions.checkNotNull(client, "client cannot be null"); this.basePath = Preconditions.checkNotNull(basePath, "basePath cannot be null"); this.serializer = Preconditions.checkNotNull(serializer, "serializer cannot be null"); watchedServices = watchInstances ? Maps.newConcurrentMap() : null; if ( thisInstance != null ) { setService(thisInstance); } } /** * The discovery must be started before use * * @throws Exception errors */ @Override public void start() throws Exception { try { reRegisterServices(); } catch ( KeeperException e ) { log.error("Could not register instances - will try again later", e); } client.getConnectionStateListenable().addListener(connectionStateListener); } @Override public void close() throws IOException { for ( ServiceCache cache : Lists.newArrayList(caches) ) { CloseableUtils.closeQuietly(cache); } for ( ServiceProvider provider : Lists.newArrayList(providers) ) { CloseableUtils.closeQuietly(provider); } if ( watchedServices != null ) { for ( NodeCache nodeCache : watchedServices.values() ) { CloseableUtils.closeQuietly(nodeCache); } } Iterator> it = services.values().iterator(); while ( it.hasNext() ) { // Should not use unregisterService because of potential ConcurrentModificationException // so we in-line the bulk of the method here ServiceInstance service = it.next(); String path = pathForInstance(service.getName(), service.getId()); boolean doRemove = true; try { client.delete().forPath(path); } catch ( KeeperException.NoNodeException ignore ) { // ignore } catch ( Exception e ) { doRemove = false; log.error("Could not unregister instance: " + service.getName(), e); } if ( doRemove ) { it.remove(); } } client.getConnectionStateListenable().removeListener(connectionStateListener); } /** * Register/re-register/update a service instance * * @param service service to add * @throws Exception errors */ @Override public void registerService(ServiceInstance service) throws Exception { setService(service); internalRegisterService(service); } @Override public void updateService(ServiceInstance service) throws Exception { byte[] bytes = serializer.serialize(service); String path = pathForInstance(service.getName(), service.getId()); client.setData().forPath(path, bytes); services.put(service.getId(), service); } @VisibleForTesting protected void internalRegisterService(ServiceInstance service) throws Exception { byte[] bytes = serializer.serialize(service); String path = pathForInstance(service.getName(), service.getId()); final int MAX_TRIES = 2; boolean isDone = false; for ( int i = 0; !isDone && (i < MAX_TRIES); ++i ) { try { CreateMode mode = (service.getServiceType() == ServiceType.DYNAMIC) ? CreateMode.EPHEMERAL : CreateMode.PERSISTENT; client.create().creatingParentsIfNeeded().withMode(mode).forPath(path, bytes); isDone = true; } catch ( KeeperException.NodeExistsException e ) { client.delete().forPath(path); // must delete then re-create so that watchers fire } } } /** * Unregister/remove a service instance * * @param service the service * @throws Exception errors */ @Override public void unregisterService(ServiceInstance service) throws Exception { String path = pathForInstance(service.getName(), service.getId()); try { client.delete().forPath(path); } catch ( KeeperException.NoNodeException ignore ) { // ignore } services.remove(service.getId()); } /** * Allocate a new builder. {@link ServiceProviderBuilder#providerStrategy} is set to {@link RoundRobinStrategy} * * @return the builder */ @Override public ServiceProviderBuilder serviceProviderBuilder() { return new ServiceProviderBuilderImpl(this) .providerStrategy(new RoundRobinStrategy()) .threadFactory(ThreadUtils.newThreadFactory("ServiceProvider")); } /** * Allocate a new service cache builder. The refresh padding is defaulted to 1 second. * * @return new cache builder */ @Override public ServiceCacheBuilder serviceCacheBuilder() { return new ServiceCacheBuilderImpl(this) .threadFactory(ThreadUtils.newThreadFactory("ServiceCache")); } /** * Return the names of all known services * * @return list of service names * @throws Exception errors */ @Override public Collection queryForNames() throws Exception { List names = client.getChildren().forPath(basePath); return ImmutableList.copyOf(names); } /** * Return all known instances for the given service * * @param name name of the service * @return list of instances (or an empty list) * @throws Exception errors */ @Override public Collection> queryForInstances(String name) throws Exception { return queryForInstances(name, null); } /** * Return a service instance POJO * * @param name name of the service * @param id ID of the instance * @return the instance or null if not found * @throws Exception errors */ @Override public ServiceInstance queryForInstance(String name, String id) throws Exception { String path = pathForInstance(name, id); try { byte[] bytes = client.getData().forPath(path); return serializer.deserialize(bytes); } catch ( KeeperException.NoNodeException ignore ) { // ignore } return null; } void cacheOpened(ServiceCache cache) { caches.add(cache); } void cacheClosed(ServiceCache cache) { caches.remove(cache); } void providerOpened(ServiceProvider provider) { providers.add(provider); } void providerClosed(ServiceProvider cache) { providers.remove(cache); } CuratorFramework getClient() { return client; } String pathForName(String name) { return ZKPaths.makePath(basePath, name); } InstanceSerializer getSerializer() { return serializer; } List> queryForInstances(String name, Watcher watcher) throws Exception { ImmutableList.Builder> builder = ImmutableList.builder(); String path = pathForName(name); List instanceIds; if ( watcher != null ) { instanceIds = getChildrenWatched(path, watcher, true); } else { try { instanceIds = client.getChildren().forPath(path); } catch ( KeeperException.NoNodeException e ) { instanceIds = Lists.newArrayList(); } } for ( String id : instanceIds ) { ServiceInstance instance = queryForInstance(name, id); if ( instance != null ) { builder.add(instance); } } return builder.build(); } private List getChildrenWatched(String path, Watcher watcher, boolean recurse) throws Exception { List instanceIds; try { instanceIds = client.getChildren().usingWatcher(watcher).forPath(path); } catch ( KeeperException.NoNodeException e ) { if ( recurse ) { try { client.create().creatingParentsIfNeeded().forPath(path); } catch ( KeeperException.NodeExistsException ignore ) { // ignore } instanceIds = getChildrenWatched(path, watcher, false); } else { throw e; } } return instanceIds; } @VisibleForTesting String pathForInstance(String name, String id) { return ZKPaths.makePath(pathForName(name), id); } @VisibleForTesting ServiceInstance getRegisteredService(String id) { return services.get(id); } private void reRegisterServices() throws Exception { for ( ServiceInstance service : services.values() ) { internalRegisterService(service); } } private void setService(final ServiceInstance instance) { services.put(instance.getId(), instance); if ( watchedServices != null ) { final NodeCache nodeCache = new NodeCache(client, pathForInstance(instance.getName(), instance.getId())); try { nodeCache.start(true); } catch ( Exception e ) { log.error("Could not start node cache for: " + instance, e); } NodeCacheListener listener = new NodeCacheListener() { @Override public void nodeChanged() throws Exception { if ( nodeCache.getCurrentData() != null ) { ServiceInstance newInstance = serializer.deserialize(nodeCache.getCurrentData().getData()); services.put(newInstance.getId(), newInstance); } else { log.warn("Instance data has been deleted for: " + instance); } } }; nodeCache.getListenable().addListener(listener); watchedServices.put(instance.getId(), nodeCache); } } } ServiceProviderBuilderImpl.java000066400000000000000000000065241245521677600421310ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.details; import com.google.common.collect.Lists; import org.apache.curator.x.discovery.DownInstancePolicy; import org.apache.curator.x.discovery.InstanceFilter; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceProvider; import org.apache.curator.x.discovery.ServiceProviderBuilder; import org.apache.curator.x.discovery.strategies.RoundRobinStrategy; import java.util.List; import java.util.concurrent.ThreadFactory; /** * Builder for service providers */ class ServiceProviderBuilderImpl implements ServiceProviderBuilder { private ServiceDiscoveryImpl discovery; private String serviceName; private ProviderStrategy providerStrategy; private ThreadFactory threadFactory; private List> filters = Lists.newArrayList(); private DownInstancePolicy downInstancePolicy = new DownInstancePolicy(); public ServiceProvider build() { return new ServiceProviderImpl(discovery, serviceName, providerStrategy, threadFactory, filters, downInstancePolicy); } ServiceProviderBuilderImpl(ServiceDiscoveryImpl discovery) { this.discovery = discovery; } /** * required - set the name of the service to be provided * * @param serviceName the name of the service * @return this */ @Override public ServiceProviderBuilder serviceName(String serviceName) { this.serviceName = serviceName; return this; } /** * optional - set the provider strategy. The default is {@link RoundRobinStrategy} * * @param providerStrategy strategy to use * @return this */ @Override public ServiceProviderBuilder providerStrategy(ProviderStrategy providerStrategy) { this.providerStrategy = providerStrategy; return this; } /** * optional - the thread factory to use for creating internal threads * * @param threadFactory factory to use * @return this */ @Override public ServiceProviderBuilder threadFactory(ThreadFactory threadFactory) { this.threadFactory = threadFactory; return this; } @Override public ServiceProviderBuilder downInstancePolicy(DownInstancePolicy downInstancePolicy) { this.downInstancePolicy = downInstancePolicy; return this; } @Override public ServiceProviderBuilder additionalFilter(InstanceFilter filter) { filters.add(filter); return this; } } ServiceProviderImpl.java000066400000000000000000000075461245521677600406270ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.details; import com.google.common.collect.Lists; import org.apache.curator.x.discovery.DownInstancePolicy; import org.apache.curator.x.discovery.InstanceFilter; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceCache; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceProvider; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.ThreadFactory; /** * The main interface for Service Discovery. Encapsulates the discovery service for a particular * named service along with a provider strategy. */ public class ServiceProviderImpl implements ServiceProvider { private final ServiceCache cache; private final InstanceProvider instanceProvider; private final ServiceDiscoveryImpl discovery; private final ProviderStrategy providerStrategy; private final DownInstanceManager downInstanceManager; public ServiceProviderImpl(ServiceDiscoveryImpl discovery, String serviceName, ProviderStrategy providerStrategy, ThreadFactory threadFactory, List> filters, DownInstancePolicy downInstancePolicy) { this.discovery = discovery; this.providerStrategy = providerStrategy; downInstanceManager = new DownInstanceManager(downInstancePolicy); cache = discovery.serviceCacheBuilder().name(serviceName).threadFactory(threadFactory).build(); ArrayList> localFilters = Lists.newArrayList(filters); localFilters.add(downInstanceManager); instanceProvider = new FilteredInstanceProvider(cache, localFilters); } /** * The provider must be started before use * * @throws Exception any errors */ @Override public void start() throws Exception { cache.start(); discovery.providerOpened(this); } /** * {@inheritDoc} */ @Override public void close() throws IOException { discovery.providerClosed(this); cache.close(); } /** * Return the current available set of instances IMPORTANT: users * should not hold on to the instance returned. They should always get a fresh list. * * @return all known instances * @throws Exception any errors */ @Override public Collection> getAllInstances() throws Exception { return instanceProvider.getInstances(); } /** * Return an instance for a single use. IMPORTANT: users * should not hold on to the instance returned. They should always get a fresh instance. * * @return the instance to use * @throws Exception any errors */ @Override public ServiceInstance getInstance() throws Exception { return providerStrategy.getInstance(instanceProvider); } @Override public void noteError(ServiceInstance instance) { downInstanceManager.add(instance); } } 000077500000000000000000000000001245521677600345405ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/strategiesRandomStrategy.java000066400000000000000000000032321245521677600403460ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/strategies/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.strategies; import org.apache.curator.x.discovery.details.InstanceProvider; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceInstance; import java.util.List; import java.util.Random; /** * This strategy always picks a random instance from the list */ public class RandomStrategy implements ProviderStrategy { private final Random random = new Random(); @Override public ServiceInstance getInstance(InstanceProvider instanceProvider) throws Exception { List> instances = instanceProvider.getInstances(); if ( instances.size() == 0 ) { return null; } int thisIndex = random.nextInt(instances.size()); return instances.get(thisIndex); } } RoundRobinStrategy.java000066400000000000000000000033341245521677600412120ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/strategies/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.strategies; import org.apache.curator.x.discovery.details.InstanceProvider; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceInstance; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** * This strategy rotates sequentially through the list of instances */ public class RoundRobinStrategy implements ProviderStrategy { private final AtomicInteger index = new AtomicInteger(0); @Override public ServiceInstance getInstance(InstanceProvider instanceProvider) throws Exception { List> instances = instanceProvider.getInstances(); if ( instances.size() == 0 ) { return null; } int thisIndex = Math.abs(index.getAndIncrement()); return instances.get(thisIndex % instances.size()); } } StickyStrategy.java000066400000000000000000000066311245521677600404020ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/strategies/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.strategies; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.details.InstanceProvider; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; /** * This strategy uses a master strategy to pick the initial instance. Once picked, * that instance is always returned. If, however, the currently selected instance * is no longer in the list, the master strategy is used to pick a new instance. */ public class StickyStrategy implements ProviderStrategy { private final ProviderStrategy masterStrategy; private final AtomicReference> ourInstance = new AtomicReference>(null); private final AtomicInteger instanceNumber = new AtomicInteger(-1); /** * @param masterStrategy the strategy to use for picking the sticky instance */ public StickyStrategy(ProviderStrategy masterStrategy) { this.masterStrategy = masterStrategy; } @Override public ServiceInstance getInstance(InstanceProvider instanceProvider) throws Exception { final List> instances = instanceProvider.getInstances(); { ServiceInstance localOurInstance = ourInstance.get(); if ( !instances.contains(localOurInstance) ) { ourInstance.compareAndSet(localOurInstance, null); } } if ( ourInstance.get() == null ) { ServiceInstance instance = masterStrategy.getInstance ( new InstanceProvider() { @Override public List> getInstances() throws Exception { return instances; } } ); if ( ourInstance.compareAndSet(null, instance) ) { instanceNumber.incrementAndGet(); } } return ourInstance.get(); } /** * Each time a new instance is picked, an internal counter is incremented. This way you * can track when/if the instance changes. The instance can change when the selected instance * is not in the current list of instances returned by the instance provider * * @return instance number */ public int getInstanceNumber() { return instanceNumber.get(); } } curator-apache-curator-2.7.1/curator-x-discovery/src/site/000077500000000000000000000000001245521677600235775ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/site/confluence/000077500000000000000000000000001245521677600257205ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/site/confluence/index.confluence000066400000000000000000000135741245521677600311040ustar00rootroot00000000000000h1. Service Discovery h2. Packaging Curator Service Discovery is in its own package in Maven Central: curator\-x\-discovery h2. What Is a Discovery Service? In SOA/distributed systems, services need to find each other. i.e. a web service might need to find a caching service, etc. DNS can be used for this but it is nowhere near flexible enough for services that are constantly changing. A Service Discovery system provides a mechanism for: * Services to register their availability * Locating a single instance of a particular service * Notifying when the instances of a service change h2. Curator Service Discovery h3. ServiceInstance A service instance is represented by the class: {{ServiceInstance}}. ServiceInstances have a name, id, address, port and/or ssl port, and an optional payload (user defined). ServiceInstances are serialized and stored in ZooKeeper in the following way: {noformat} base path |_______ service A name |__________ instance 1 id --> (serialized ServiceInstance) |__________ instance 2 id --> (serialized ServiceInstance) |__________ ... |_______ service B name |__________ instance 1 id --> (serialized ServiceInstance) |__________ instance 2 id --> (serialized ServiceInstance) |__________ ... |_______ ... {noformat} h3. ServiceProvider The main abstraction class is {{ServiceProvider}}. It encapsulates the discovery service for a particular named service along with a provider strategy. A provider strategy is a scheme for selecting one instance from a set of instances for a given service. There are three bundled strategies: Round Robin, Random and Sticky (always selects the same one). ServiceProviders are allocated by using a {{ServiceProviderBuilder}}. You obtain a ServiceProviderBuilder from the ServiceDiscovery (see below). The ServiceProviderBuilder allows you to set the service name and several other optional values. The ServiceProvider must be started by calling {{start()}}. When finished you should call {{close()}}. The only method in ServiceProvider is: {code} public ServiceInstance getInstance() throws Exception Return an instance for a single use. IMPORTANT: users should not hold on to the instance returned. A fresh instance should always be retrieved. Returns: the instance to use {code} h3. ServiceDiscovery In order to allocate a ServiceProvider, you must have a ServiceDiscovery. It is created by a {{ServiceDiscoveryBuilder}}. You must call {{start()}} on the object and, when done with it, call {{close()}}. h3. Instance Stability If a particular instance has an I/O error, etc. you should call {{ServiceProvider.noteError()}} passing in the instance. The ServiceProvider will temporarily consider instances that have errors to be "down". The thresholds and timeouts for down instances are set via the {{DownInstancePolicy}} which can be passed to {{ServiceProviderBuilder}} (note: a default DownInstancePolicy is used if you don't specify one). ---- h3. Low Level APIs The ServiceProvider API is all you should need for most purposes. However, for finer grained control, you can use these methods: *Registering/Unregistering Services* Normally, you pass your application's service descriptor to the ServiceDiscovery constructor and it will get registered/unregistered automatically. If, though, you need to manually do this, use these methods: {code} public void registerService(ServiceInstance service) throws Exception Register/re-register/update a service instance Parameters: service - service to add {code} {code} public void unregisterService(ServiceInstance service) throws Exception Unregister/remove a service instance Parameters: service - the service {code} *Querying for Services* You can query for all service names, all instances of a particular service, or single service instance. {code} public Collection queryForNames() throws Exception Return the names of all known services Returns: list of service names {code} {code} public Collection> queryForInstances(String name) throws Exception Return all known instances for the given service Parameters: name - name of the service Returns: list of instances (or an empty list) {code} {code} public ServiceInstance queryForInstance(String name, String id) throws Exception Return a service instance POJO Parameters: name - name of the service id - ID of the instance Returns: the instance or null if not found {code} *Service Cache* Each of the above query methods calls ZooKeeper directly. If you need more than occasional querying of services you can use the {{ServiceCache}}. It caches in memory the list of instances for a particular service. It uses a Watcher to keep the list up to date. You allocate a ServiceCache via the builder returned by {{ServiceDiscovery.serviceCacheBuilder()}}. The ServiceCache object must be started by calling {{start()}} and, when done, you should call {{close()}}. You can get the currently known list of instances for the service by calling: {code} public Collection> getInstances() Return the current list of instances. NOTE: there is no guarantee of freshness. This is merely the last known list of instances. However, the list is updated via a ZooKeeper watcher so it should be fresh within a window of a second or two. {code} ServiceCache supports a listener that gets notified when Watcher has updated the list of instances: {code} /** * Listener for changes to a service cache */ public interface ServiceCacheListener extends ConnectionStateListener { /** * Called when the cache has changed (instances added/deleted, etc.) */ public void cacheChanged(); } {code} curator-apache-curator-2.7.1/curator-x-discovery/src/site/site.xml000066400000000000000000000026331245521677600252710ustar00rootroot00000000000000 curator-apache-curator-2.7.1/curator-x-discovery/src/test/000077500000000000000000000000001245521677600236125ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/java/000077500000000000000000000000001245521677600245335ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/java/org/000077500000000000000000000000001245521677600253225ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/java/org/apache/000077500000000000000000000000001245521677600265435ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/java/org/apache/curator/000077500000000000000000000000001245521677600302225ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/java/org/apache/curator/x/000077500000000000000000000000001245521677600304715ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/000077500000000000000000000000001245521677600325005ustar00rootroot00000000000000ServiceCacheLeakTester.java000066400000000000000000000055461245521677600376060ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.TestingServer; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.x.discovery.strategies.RandomStrategy; public class ServiceCacheLeakTester { public static void main(String[] args) throws Exception { TestingServer testingServer = new TestingServer(); final CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(testingServer.getConnectString(), new RetryOneTime(1)); try { curatorFramework.start(); doWork(curatorFramework); System.gc(); System.out.println("Done - get dump"); Thread.currentThread().join(); } finally { CloseableUtils.closeQuietly(curatorFramework); CloseableUtils.closeQuietly(testingServer); } } private static void doWork(CuratorFramework curatorFramework) throws Exception { ServiceInstance thisInstance = ServiceInstance.builder().name("myservice").build(); final ServiceDiscovery serviceDiscovery = ServiceDiscoveryBuilder.builder(Void.class).client(curatorFramework.usingNamespace("dev")).basePath("/instances").thisInstance(thisInstance).build(); serviceDiscovery.start(); for ( int i = 0; i < 100000; i++ ) { final ServiceProvider s = serviceProvider(serviceDiscovery, "myservice"); s.start(); try { s.getInstance().buildUriSpec(); } finally { s.close(); } } } private static ServiceProvider serviceProvider(ServiceDiscovery serviceDiscovery, String name) throws Exception { return serviceDiscovery.serviceProviderBuilder().serviceName(name).providerStrategy(new RandomStrategy()).build(); } }TestJsonInstanceSerializer.java000066400000000000000000000171031245521677600405560ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.curator.x.discovery.details.JsonInstanceSerializer; import org.testng.Assert; import org.testng.annotations.Test; public class TestJsonInstanceSerializer { @Test public void testBasic() throws Exception { JsonInstanceSerializer serializer = new JsonInstanceSerializer(String.class); ServiceInstance instance = new ServiceInstance("name", "id", "address", 10, 20, "payload", 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}")); byte[] bytes = serializer.serialize(instance); ServiceInstance rhs = serializer.deserialize(bytes); Assert.assertEquals(instance, rhs); Assert.assertEquals(instance.getId(), rhs.getId()); Assert.assertEquals(instance.getName(), rhs.getName()); Assert.assertEquals(instance.getPayload(), rhs.getPayload()); Assert.assertEquals(instance.getAddress(), rhs.getAddress()); Assert.assertEquals(instance.getPort(), rhs.getPort()); Assert.assertEquals(instance.getSslPort(), rhs.getSslPort()); Assert.assertEquals(instance.getUriSpec(), rhs.getUriSpec()); } @Test public void testWrongPayloadType() throws Exception { JsonInstanceSerializer stringSerializer = new JsonInstanceSerializer(String.class); JsonInstanceSerializer doubleSerializer = new JsonInstanceSerializer(Double.class); byte[] bytes = stringSerializer.serialize(new ServiceInstance("name", "id", "address", 10, 20, "payload", 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"))); try { doubleSerializer.deserialize(bytes); Assert.fail(); } catch ( ClassCastException e ) { // correct } } @Test public void testNoPayload() throws Exception { JsonInstanceSerializer serializer = new JsonInstanceSerializer(Void.class); ServiceInstance instance = new ServiceInstance("name", "id", "address", 10, 20, null, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}")); byte[] bytes = serializer.serialize(instance); ServiceInstance rhs = serializer.deserialize(bytes); Assert.assertEquals(instance, rhs); Assert.assertEquals(instance.getId(), rhs.getId()); Assert.assertEquals(instance.getName(), rhs.getName()); Assert.assertEquals(instance.getPayload(), rhs.getPayload()); Assert.assertEquals(instance.getAddress(), rhs.getAddress()); Assert.assertEquals(instance.getPort(), rhs.getPort()); Assert.assertEquals(instance.getSslPort(), rhs.getSslPort()); Assert.assertEquals(instance.getUriSpec(), rhs.getUriSpec()); } @Test public void testPayloadAsList() throws Exception { JsonInstanceSerializer serializer = new JsonInstanceSerializer(Object.class); List payload = new ArrayList(); payload.add("Test value 1"); payload.add("Test value 2"); ServiceInstance instance = new ServiceInstance("name", "id", "address", 10, 20, payload, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}")); byte[] bytes = serializer.serialize(instance); ServiceInstance rhs = serializer.deserialize(bytes); Assert.assertEquals(instance, rhs); Assert.assertEquals(instance.getId(), rhs.getId()); Assert.assertEquals(instance.getName(), rhs.getName()); Assert.assertEquals(instance.getPayload(), rhs.getPayload()); Assert.assertEquals(instance.getAddress(), rhs.getAddress()); Assert.assertEquals(instance.getPort(), rhs.getPort()); Assert.assertEquals(instance.getSslPort(), rhs.getSslPort()); Assert.assertEquals(instance.getUriSpec(), rhs.getUriSpec()); } @Test public void testPayloadAsMap() throws Exception { JsonInstanceSerializer serializer = new JsonInstanceSerializer(Object.class); Map payload = new HashMap(); payload.put("1", "Test value 1"); payload.put("2", "Test value 2"); ServiceInstance instance = new ServiceInstance("name", "id", "address", 10, 20, payload, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}")); byte[] bytes = serializer.serialize(instance); ServiceInstance rhs = serializer.deserialize(bytes); Assert.assertEquals(instance, rhs); Assert.assertEquals(instance.getId(), rhs.getId()); Assert.assertEquals(instance.getName(), rhs.getName()); Assert.assertEquals(instance.getPayload(), rhs.getPayload()); Assert.assertEquals(instance.getAddress(), rhs.getAddress()); Assert.assertEquals(instance.getPort(), rhs.getPort()); Assert.assertEquals(instance.getSslPort(), rhs.getSslPort()); Assert.assertEquals(instance.getUriSpec(), rhs.getUriSpec()); } @Test public void testPayloadClass() throws Exception { JsonInstanceSerializer serializer = new JsonInstanceSerializer(Payload.class); Payload payload = new Payload(); payload.setVal("Test value"); ServiceInstance instance = new ServiceInstance("name", "id", "address", 10, 20, payload, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}")); byte[] bytes = serializer.serialize(instance); ServiceInstance rhs = serializer.deserialize(bytes); Assert.assertEquals(instance, rhs); Assert.assertEquals(instance.getId(), rhs.getId()); Assert.assertEquals(instance.getName(), rhs.getName()); Assert.assertEquals(instance.getPayload(), rhs.getPayload()); Assert.assertEquals(instance.getAddress(), rhs.getAddress()); Assert.assertEquals(instance.getPort(), rhs.getPort()); Assert.assertEquals(instance.getSslPort(), rhs.getSslPort()); Assert.assertEquals(instance.getUriSpec(), rhs.getUriSpec()); } public static class Payload { private String val; public String getVal() { return val; } public void setVal(String val) { this.val = val; } @Override public boolean equals(Object other) { if (other == null || !(other instanceof Payload)) return false; String otherVal = ((Payload)other).getVal(); if (val == null) return val == otherVal; return val.equals(otherVal); } } } TestLocalIpFilter.java000066400000000000000000000041461245521677600366220ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import com.google.common.collect.Lists; import org.testng.Assert; import org.testng.annotations.Test; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.List; public class TestLocalIpFilter { @Test public void testFilterEverything() throws SocketException { LocalIpFilter localIpFilter = ServiceInstanceBuilder.getLocalIpFilter(); try { ServiceInstanceBuilder.setLocalIpFilter ( new LocalIpFilter() { @Override public boolean use(NetworkInterface networkInterface, InetAddress address) throws SocketException { return false; } } ); List allLocalIPs = Lists.newArrayList(ServiceInstanceBuilder.getAllLocalIPs()); Assert.assertEquals(allLocalIPs.size(), 0); } finally { ServiceInstanceBuilder.setLocalIpFilter(localIpFilter); } List allLocalIPs = Lists.newArrayList(ServiceInstanceBuilder.getAllLocalIPs()); Assert.assertTrue(allLocalIPs.size() > 0); } } TestServiceCache.java000066400000000000000000000240601245521677600364520ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import com.google.common.collect.Lists; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.TestingServer; import org.apache.curator.x.discovery.details.ServiceCacheListener; import org.testng.Assert; import org.testng.annotations.Test; import java.io.Closeable; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class TestServiceCache extends BaseClassForTests { @Test public void testInitialLoad() throws Exception { List closeables = Lists.newArrayList(); try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/discovery").client(client).build(); closeables.add(discovery); discovery.start(); ServiceCache cache = discovery.serviceCacheBuilder().name("test").build(); closeables.add(cache); final CountDownLatch latch = new CountDownLatch(3); ServiceCacheListener listener = new ServiceCacheListener() { @Override public void cacheChanged() { latch.countDown(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; cache.addListener(listener); cache.start(); ServiceInstance instance1 = ServiceInstance.builder().payload("test").name("test").port(10064).build(); ServiceInstance instance2 = ServiceInstance.builder().payload("test").name("test").port(10065).build(); ServiceInstance instance3 = ServiceInstance.builder().payload("test").name("test").port(10066).build(); discovery.registerService(instance1); discovery.registerService(instance2); discovery.registerService(instance3); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); ServiceCache cache2 = discovery.serviceCacheBuilder().name("test").build(); closeables.add(cache2); cache2.start(); Assert.assertEquals(cache2.getInstances().size(), 3); } finally { Collections.reverse(closeables); for ( Closeable c : closeables ) { CloseableUtils.closeQuietly(c); } } } @Test public void testViaProvider() throws Exception { Timing timing = new Timing(); List closeables = Lists.newArrayList(); try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/discovery").client(client).build(); closeables.add(discovery); discovery.start(); ServiceProvider serviceProvider = discovery.serviceProviderBuilder().serviceName("test").build(); closeables.add(serviceProvider); serviceProvider.start(); ServiceInstance instance = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); discovery.registerService(instance); int count = 0; ServiceInstance foundInstance = null; while ( foundInstance == null ) { Assert.assertTrue(count++ < 5); foundInstance = serviceProvider.getInstance(); timing.sleepABit(); } Assert.assertEquals(foundInstance, instance); ServiceInstance instance2 = ServiceInstance.builder().address("foo").payload("thing").name("test").port(10064).build(); discovery.registerService(instance2); timing.sleepABit(); Collection> allInstances = serviceProvider.getAllInstances(); Assert.assertEquals(allInstances.size(), 2); } finally { Collections.reverse(closeables); for ( Closeable c : closeables ) { CloseableUtils.closeQuietly(c); } } } @Test public void testUpdate() throws Exception { List closeables = Lists.newArrayList(); try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); ServiceInstance instance = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build(); closeables.add(discovery); discovery.start(); final CountDownLatch latch = new CountDownLatch(1); ServiceCache cache = discovery.serviceCacheBuilder().name("test").build(); closeables.add(cache); ServiceCacheListener listener = new ServiceCacheListener() { @Override public void cacheChanged() { latch.countDown(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; cache.addListener(listener); cache.start(); instance = ServiceInstance.builder().payload("changed").name("test").port(10064).id(instance.getId()).build(); discovery.updateService(instance); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); Assert.assertEquals(cache.getInstances().size(), 1); Assert.assertEquals(cache.getInstances().get(0).getPayload(), instance.getPayload()); } finally { Collections.reverse(closeables); for ( Closeable c : closeables ) { CloseableUtils.closeQuietly(c); } } } @Test public void testCache() throws Exception { List closeables = Lists.newArrayList(); try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/discovery").client(client).build(); closeables.add(discovery); discovery.start(); ServiceCache cache = discovery.serviceCacheBuilder().name("test").build(); closeables.add(cache); cache.start(); final Semaphore semaphore = new Semaphore(0); ServiceCacheListener listener = new ServiceCacheListener() { @Override public void cacheChanged() { semaphore.release(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; cache.addListener(listener); ServiceInstance instance1 = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); ServiceInstance instance2 = ServiceInstance.builder().payload("thing").name("test").port(10065).build(); discovery.registerService(instance1); Assert.assertTrue(semaphore.tryAcquire(10, TimeUnit.SECONDS)); discovery.registerService(instance2); Assert.assertTrue(semaphore.tryAcquire(3, TimeUnit.SECONDS)); ServiceInstance instance3 = ServiceInstance.builder().payload("thing").name("another").port(10064).build(); discovery.registerService(instance3); Assert.assertFalse(semaphore.tryAcquire(3, TimeUnit.SECONDS)); // should not get called for a different service } finally { Collections.reverse(closeables); for ( Closeable c : closeables ) { CloseableUtils.closeQuietly(c); } } } } TestServiceDiscovery.java000066400000000000000000000272471245521677600374300ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.KillSession; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.x.discovery.details.JsonInstanceSerializer; import org.apache.curator.x.discovery.details.ServiceDiscoveryImpl; import org.testng.Assert; import org.testng.annotations.Test; import java.io.Closeable; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.Semaphore; public class TestServiceDiscovery extends BaseClassForTests { private static final Comparator> comparator = new Comparator>() { @Override public int compare(ServiceInstance o1, ServiceInstance o2) { return o1.getId().compareTo(o2.getId()); } }; @Test public void testCrashedServerMultiInstances() throws Exception { List closeables = Lists.newArrayList(); try { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); closeables.add(client); client.start(); final Semaphore semaphore = new Semaphore(0); ServiceInstance instance1 = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); ServiceInstance instance2 = ServiceInstance.builder().payload("thing").name("test").port(10065).build(); ServiceDiscovery discovery = new ServiceDiscoveryImpl(client, "/test", new JsonInstanceSerializer(String.class), instance1, false) { @Override protected void internalRegisterService(ServiceInstance service) throws Exception { super.internalRegisterService(service); semaphore.release(); } }; closeables.add(discovery); discovery.start(); discovery.registerService(instance2); timing.acquireSemaphore(semaphore, 2); Assert.assertEquals(discovery.queryForInstances("test").size(), 2); KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString()); server.stop(); server.restart(); closeables.add(server); timing.acquireSemaphore(semaphore, 2); Assert.assertEquals(discovery.queryForInstances("test").size(), 2); } finally { for ( Closeable c : closeables ) { CloseableUtils.closeQuietly(c); } } } @Test public void testCrashedServer() throws Exception { List closeables = Lists.newArrayList(); try { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); closeables.add(client); client.start(); final Semaphore semaphore = new Semaphore(0); ServiceInstance instance = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); ServiceDiscovery discovery = new ServiceDiscoveryImpl(client, "/test", new JsonInstanceSerializer(String.class), instance, false) { @Override protected void internalRegisterService(ServiceInstance service) throws Exception { super.internalRegisterService(service); semaphore.release(); } }; closeables.add(discovery); discovery.start(); timing.acquireSemaphore(semaphore); Assert.assertEquals(discovery.queryForInstances("test").size(), 1); KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString()); server.stop(); server.restart(); closeables.add(server); timing.acquireSemaphore(semaphore); Assert.assertEquals(discovery.queryForInstances("test").size(), 1); } finally { for ( Closeable c : closeables ) { CloseableUtils.closeQuietly(c); } } } @Test public void testCrashedInstance() throws Exception { List closeables = Lists.newArrayList(); try { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); closeables.add(client); client.start(); ServiceInstance instance = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); ServiceDiscovery discovery = new ServiceDiscoveryImpl(client, "/test", new JsonInstanceSerializer(String.class), instance, false); closeables.add(discovery); discovery.start(); Assert.assertEquals(discovery.queryForInstances("test").size(), 1); KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString()); Thread.sleep(timing.multiple(1.5).session()); Assert.assertEquals(discovery.queryForInstances("test").size(), 1); } finally { Collections.reverse(closeables); for ( Closeable c : closeables ) { CloseableUtils.closeQuietly(c); } } } @Test public void testMultipleInstances() throws Exception { final String SERVICE_ONE = "one"; final String SERVICE_TWO = "two"; List closeables = Lists.newArrayList(); try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); ServiceInstance s1_i1 = ServiceInstance.builder().name(SERVICE_ONE).build(); ServiceInstance s1_i2 = ServiceInstance.builder().name(SERVICE_ONE).build(); ServiceInstance s2_i1 = ServiceInstance.builder().name(SERVICE_TWO).build(); ServiceInstance s2_i2 = ServiceInstance.builder().name(SERVICE_TWO).build(); ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(Void.class).client(client).basePath("/test").build(); closeables.add(discovery); discovery.start(); discovery.registerService(s1_i1); discovery.registerService(s1_i2); discovery.registerService(s2_i1); discovery.registerService(s2_i2); Assert.assertEquals(Sets.newHashSet(discovery.queryForNames()), Sets.newHashSet(SERVICE_ONE, SERVICE_TWO)); List> list = Lists.newArrayList(); list.add(s1_i1); list.add(s1_i2); Collections.sort(list, comparator); List> queriedInstances = Lists.newArrayList(discovery.queryForInstances(SERVICE_ONE)); Collections.sort(queriedInstances, comparator); Assert.assertEquals(queriedInstances, list, String.format("Not equal l: %s - d: %s", list, queriedInstances)); list.clear(); list.add(s2_i1); list.add(s2_i2); Collections.sort(list, comparator); queriedInstances = Lists.newArrayList(discovery.queryForInstances(SERVICE_TWO)); Collections.sort(queriedInstances, comparator); Assert.assertEquals(queriedInstances, list, String.format("Not equal 2: %s - d: %s", list, queriedInstances)); } finally { Collections.reverse(closeables); for ( Closeable c : closeables ) { CloseableUtils.closeQuietly(c); } } } @Test public void testBasic() throws Exception { List closeables = Lists.newArrayList(); try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); ServiceInstance instance = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build(); closeables.add(discovery); discovery.start(); Assert.assertEquals(discovery.queryForNames(), Arrays.asList("test")); List> list = Lists.newArrayList(); list.add(instance); Assert.assertEquals(discovery.queryForInstances("test"), list); } finally { Collections.reverse(closeables); for ( Closeable c : closeables ) { CloseableUtils.closeQuietly(c); } } } @Test public void testNoServerOnStart() throws Exception { server.stop(); List closeables = Lists.newArrayList(); try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); ServiceInstance instance = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build(); closeables.add(discovery); discovery.start(); server.restart(); Assert.assertEquals(discovery.queryForNames(), Arrays.asList("test")); List> list = Lists.newArrayList(); list.add(instance); Assert.assertEquals(discovery.queryForInstances("test"), list); } finally { Collections.reverse(closeables); for ( Closeable c : closeables ) { CloseableUtils.closeQuietly(c); } } } } TestStrategies.java000066400000000000000000000116751245521677600362500ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import com.google.common.collect.Lists; import org.apache.curator.x.discovery.details.InstanceProvider; import org.apache.curator.x.discovery.strategies.RandomStrategy; import org.apache.curator.x.discovery.strategies.RoundRobinStrategy; import org.apache.curator.x.discovery.strategies.StickyStrategy; import org.apache.commons.math.stat.descriptive.SummaryStatistics; import org.testng.Assert; import org.testng.annotations.Test; import java.util.List; public class TestStrategies { private static class TestInstanceProvider implements InstanceProvider { private final List> instances; private TestInstanceProvider(int qty) throws Exception { this(qty, 0); } private TestInstanceProvider(int qty, int startingAt) throws Exception { instances = Lists.newArrayList(); for ( int i = 0; i < qty; ++i ) { ServiceInstanceBuilder builder = ServiceInstance.builder(); instances.add(builder.id(Integer.toString(i + startingAt)).name("foo").build()); } } @Override public List> getInstances() throws Exception { return instances; } } @Test public void testRandom() throws Exception { final int QTY = 10; final int ITERATIONS = 1000; TestInstanceProvider instanceProvider = new TestInstanceProvider(QTY, 0); ProviderStrategy strategy = new RandomStrategy(); long[] counts = new long[QTY]; for ( int i = 0; i < ITERATIONS; ++i ) { ServiceInstance instance = strategy.getInstance(instanceProvider); int id = Integer.parseInt(instance.getId()); counts[id]++; } SummaryStatistics statistic = new SummaryStatistics(); for ( int i = 0; i < QTY; ++i ) { statistic.addValue(counts[i]); } Assert.assertTrue(statistic.getStandardDeviation() <= (QTY * 2), "" + statistic.getStandardDeviation()); // meager check for even distribution } @Test public void testRoundRobin() throws Exception { final int QTY = 10; TestInstanceProvider instanceProvider = new TestInstanceProvider(QTY); ProviderStrategy strategy = new RoundRobinStrategy(); for ( int i = 0; i < QTY; ++i ) { ServiceInstance instance = strategy.getInstance(instanceProvider); Assert.assertEquals(instance.getId(), Integer.toString(i)); } for ( int i = 0; i < (1234 * QTY); ++i ) { ServiceInstance instance = strategy.getInstance(instanceProvider); Assert.assertEquals(instance.getId(), Integer.toString(i % QTY)); } } @Test public void testSticky() throws Exception { final int QTY = 10; TestInstanceProvider instanceProvider = new TestInstanceProvider(QTY); StickyStrategy strategy = new StickyStrategy(new RandomStrategy()); ServiceInstance theInstance = strategy.getInstance(instanceProvider); int instanceNumber = strategy.getInstanceNumber(); for ( int i = 0; i < 1000; ++i ) { Assert.assertEquals(strategy.getInstance(instanceProvider), theInstance); } // assert what happens when an instance goes down instanceProvider = new TestInstanceProvider(QTY, QTY); Assert.assertFalse(strategy.getInstance(instanceProvider).equals(theInstance)); Assert.assertFalse(instanceNumber == strategy.getInstanceNumber()); theInstance = strategy.getInstance(instanceProvider); for ( int i = 0; i < 1000; ++i ) { Assert.assertEquals(strategy.getInstance(instanceProvider), theInstance); } } } TestUriSpec.java000066400000000000000000000074571245521677600355130ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery; import com.google.common.collect.Maps; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Iterator; import java.util.Map; public class TestUriSpec { @Test public void testScheme() { UriSpec spec = new UriSpec("{scheme}://foo.com"); ServiceInstanceBuilder builder = new ServiceInstanceBuilder(); builder.id("x"); builder.name("foo"); builder.port(5); ServiceInstance instance = builder.build(); Assert.assertEquals(spec.build(instance), "http://foo.com"); builder.sslPort(5); instance = builder.build(); Assert.assertEquals(spec.build(instance), "https://foo.com"); } @Test public void testFromInstance() { ServiceInstanceBuilder builder = new ServiceInstanceBuilder(); builder.address("1.2.3.4"); builder.name("foo"); builder.id("bar"); builder.port(5); builder.sslPort(6); builder.registrationTimeUTC(789); builder.serviceType(ServiceType.PERMANENT); ServiceInstance instance = builder.build(); UriSpec spec = new UriSpec("{scheme}://{address}:{port}:{ssl-port}/{name}/{id}/{registration-time-utc}/{service-type}"); Map m = Maps.newHashMap(); m.put("scheme", "test"); Assert.assertEquals(spec.build(instance, m), "test://1.2.3.4:5:6/foo/bar/789/permanent"); } @Test public void testEscapes() { UriSpec spec = new UriSpec("{one}two-three-{[}four{]}-five{six}"); Iterator iterator = spec.iterator(); checkPart(iterator.next(), "one", true); checkPart(iterator.next(), "two-three-", false); checkPart(iterator.next(), "[", true); checkPart(iterator.next(), "four", false); checkPart(iterator.next(), "]", true); checkPart(iterator.next(), "-five", false); checkPart(iterator.next(), "six", true); Map m = Maps.newHashMap(); m.put("one", 1); m.put("six", 6); Assert.assertEquals(spec.build(m), "1two-three-{four}-five6"); } @Test public void testBasic() { UriSpec spec = new UriSpec("{one}{two}three-four-five{six}seven{eight}"); Iterator iterator = spec.iterator(); checkPart(iterator.next(), "one", true); checkPart(iterator.next(), "two", true); checkPart(iterator.next(), "three-four-five", false); checkPart(iterator.next(), "six", true); checkPart(iterator.next(), "seven", false); checkPart(iterator.next(), "eight", true); } private void checkPart(UriSpec.Part p, String value, boolean isVariable) { Assert.assertEquals(p.getValue(), value); Assert.assertEquals(p.isVariable(), isVariable); } } 000077500000000000000000000000001245521677600340465ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/detailsTestDownInstanceManager.java000066400000000000000000000071461245521677600414500ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.details; import org.apache.curator.x.discovery.DownInstancePolicy; import org.apache.curator.x.discovery.ServiceInstance; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; public class TestDownInstanceManager { private static final DownInstancePolicy debugDownInstancePolicy = new DownInstancePolicy(1, TimeUnit.SECONDS, 1); private static final DownInstancePolicy debugMultiDownInstancePolicy = new DownInstancePolicy(1, TimeUnit.SECONDS, 2); @Test public void testBasic() throws Exception { ServiceInstance instance1 = ServiceInstance.builder().name("hey").id("1").build(); ServiceInstance instance2 = ServiceInstance.builder().name("hey").id("2").build(); DownInstanceManager downInstanceManager = new DownInstanceManager(debugDownInstancePolicy); Assert.assertTrue(downInstanceManager.apply(instance1)); Assert.assertTrue(downInstanceManager.apply(instance2)); downInstanceManager.add(instance1); Assert.assertFalse(downInstanceManager.apply(instance1)); Assert.assertTrue(downInstanceManager.apply(instance2)); } @Test public void testThreshold() throws Exception { ServiceInstance instance1 = ServiceInstance.builder().name("hey").id("1").build(); ServiceInstance instance2 = ServiceInstance.builder().name("hey").id("2").build(); DownInstanceManager downInstanceManager = new DownInstanceManager(debugMultiDownInstancePolicy); Assert.assertTrue(downInstanceManager.apply(instance1)); Assert.assertTrue(downInstanceManager.apply(instance2)); downInstanceManager.add(instance1); Assert.assertTrue(downInstanceManager.apply(instance1)); Assert.assertTrue(downInstanceManager.apply(instance2)); downInstanceManager.add(instance1); Assert.assertFalse(downInstanceManager.apply(instance1)); Assert.assertTrue(downInstanceManager.apply(instance2)); } @Test public void testExpiration() throws Exception { ServiceInstance instance1 = ServiceInstance.builder().name("hey").id("1").build(); ServiceInstance instance2 = ServiceInstance.builder().name("hey").id("2").build(); DownInstanceManager downInstanceManager = new DownInstanceManager(debugDownInstancePolicy); downInstanceManager.add(instance1); Assert.assertFalse(downInstanceManager.apply(instance1)); Assert.assertTrue(downInstanceManager.apply(instance2)); Thread.sleep(debugDownInstancePolicy.getTimeoutMs()); Assert.assertTrue(downInstanceManager.apply(instance1)); Assert.assertTrue(downInstanceManager.apply(instance2)); } } TestServiceDiscoveryBuilder.java000066400000000000000000000055761245521677600423650ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.details; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; import org.apache.curator.x.discovery.ServiceInstance; import org.testng.Assert; import org.testng.annotations.Test; public class TestServiceDiscoveryBuilder extends BaseClassForTests { @Test public void testDefaultSerializer() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); ServiceDiscoveryBuilder builder = ServiceDiscoveryBuilder.builder(Object.class).client(client); ServiceDiscoveryImpl discovery = (ServiceDiscoveryImpl) builder.basePath("/path").build(); Assert.assertNotNull(discovery.getSerializer(), "default serializer not set"); Assert.assertTrue(discovery.getSerializer() instanceof JsonInstanceSerializer, "default serializer not JSON"); } @Test public void testSetSerializer() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); ServiceDiscoveryBuilder builder = ServiceDiscoveryBuilder.builder(Object.class).client(client); builder.serializer(new InstanceSerializer() { @Override public byte[] serialize(ServiceInstance instance) { return null; } @Override public ServiceInstance deserialize(byte[] bytes) { return null; } }); ServiceDiscoveryImpl discovery = (ServiceDiscoveryImpl) builder.basePath("/path").build(); Assert.assertNotNull(discovery.getSerializer(), "default serializer not set"); Assert.assertFalse(discovery.getSerializer() instanceof JsonInstanceSerializer, "set serializer is JSON"); } } TestWatchedInstances.java000066400000000000000000000074231245521677600410060ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.discovery.details; import com.google.common.collect.Lists; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; import org.apache.curator.x.discovery.ServiceInstance; import org.testng.Assert; import org.testng.annotations.Test; import java.io.Closeable; import java.util.Arrays; import java.util.Collections; import java.util.List; public class TestWatchedInstances extends BaseClassForTests { @Test public void testWatchedInstances() throws Exception { Timing timing = new Timing(); List closeables = Lists.newArrayList(); try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); ServiceInstance instance = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); ServiceDiscovery discovery = ServiceDiscoveryBuilder .builder(String.class) .basePath("/test") .client(client) .thisInstance(instance) .watchInstances(true) .build(); closeables.add(discovery); discovery.start(); Assert.assertEquals(discovery.queryForNames(), Arrays.asList("test")); List> list = Lists.newArrayList(); list.add(instance); Assert.assertEquals(discovery.queryForInstances("test"), list); ServiceDiscoveryImpl discoveryImpl = (ServiceDiscoveryImpl)discovery; ServiceInstance changedInstance = ServiceInstance.builder() .id(instance.getId()) .address(instance.getAddress()) .payload("different") .name(instance.getName()) .port(instance.getPort()) .build(); String path = discoveryImpl.pathForInstance("test", instance.getId()); byte[] bytes = discoveryImpl.getSerializer().serialize(changedInstance); client.setData().forPath(path, bytes); timing.sleepABit(); ServiceInstance registeredService = discoveryImpl.getRegisteredService(instance.getId()); Assert.assertNotNull(registeredService); Assert.assertEquals(registeredService.getPayload(), "different"); } finally { Collections.reverse(closeables); for ( Closeable c : closeables ) { CloseableUtils.closeQuietly(c); } } } } curator-apache-curator-2.7.1/curator-x-discovery/src/test/resources/000077500000000000000000000000001245521677600256245ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-discovery/src/test/resources/log4j.properties000066400000000000000000000021131245521677600307560ustar00rootroot00000000000000# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # log4j.rootLogger=ERROR, console log4j.logger.org.apache.curator=DEBUG, console log4j.additivity.org.apache.curator=false log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%-5p %c %x %m [%t]%n curator-apache-curator-2.7.1/curator-x-rpc/000077500000000000000000000000001245521677600206215ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/pom.xml000066400000000000000000000131321245521677600221360ustar00rootroot00000000000000 apache-curator org.apache.curator 2.7.1 4.0.0 curator-x-rpc 2.7.1 Curator RPC Proxy A proxy that bridges non-java environments with the Curator framework and recipes 2014 org.apache.curator curator-recipes org.slf4j log4j-over-slf4j org.slf4j slf4j-log4j12 log4j log4j org.apache.curator curator-x-discovery org.slf4j log4j-over-slf4j org.slf4j slf4j-log4j12 log4j log4j com.facebook.swift swift-service com.fasterxml.jackson.core jackson-annotations io.dropwizard dropwizard-configuration io.dropwizard dropwizard-logging org.apache.curator curator-test org.slf4j log4j-over-slf4j org.slf4j slf4j-log4j12 log4j log4j test ${project.basedir}/src/main/resources curator/help.txt ${project.basedir}/src/main/thrift curator.thrift org.apache.maven.plugins maven-shade-plugin false *:* META-INF/*.SF META-INF/*.DSA META-INF/*.RSA package shade org.apache.curator.x.rpc.CuratorProjectionServer curator-apache-curator-2.7.1/curator-x-rpc/src/000077500000000000000000000000001245521677600214105ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/000077500000000000000000000000001245521677600223345ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/000077500000000000000000000000001245521677600232555ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/000077500000000000000000000000001245521677600240445ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/000077500000000000000000000000001245521677600252655ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/000077500000000000000000000000001245521677600267445ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/000077500000000000000000000000001245521677600272135ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/000077500000000000000000000000001245521677600277775ustar00rootroot00000000000000CuratorProjectionServer.java000066400000000000000000000133151245521677600354310ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc; import com.codahale.metrics.MetricRegistry; import com.facebook.swift.codec.ThriftCodecManager; import com.facebook.swift.service.ThriftEventHandler; import com.facebook.swift.service.ThriftServer; import com.facebook.swift.service.ThriftServiceProcessor; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.io.Files; import com.google.common.io.Resources; import org.apache.curator.x.rpc.configuration.Configuration; import org.apache.curator.x.rpc.configuration.ConfigurationBuilder; import org.apache.curator.x.rpc.connections.ConnectionManager; import org.apache.curator.x.rpc.idl.discovery.DiscoveryService; import org.apache.curator.x.rpc.idl.discovery.DiscoveryServiceLowLevel; import org.apache.curator.x.rpc.idl.services.EventService; import org.apache.curator.x.rpc.idl.services.CuratorProjectionService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.charset.Charset; import java.util.concurrent.atomic.AtomicReference; public class CuratorProjectionServer { private final Logger log = LoggerFactory.getLogger(getClass()); private final ConnectionManager connectionManager; private final ThriftServer server; private final AtomicReference state = new AtomicReference(State.LATENT); private final Configuration configuration; private enum State { LATENT, STARTED, STOPPED } public static void main(String[] args) throws Exception { if ( (args.length != 1) || args[0].equalsIgnoreCase("?") || args[0].equalsIgnoreCase("-h") || args[0].equalsIgnoreCase("--help") ) { printHelp(); return; } String configurationSource; File f = new File(args[0]); if ( f.exists() ) { configurationSource = Files.toString(f, Charset.defaultCharset()); } else { System.out.println("First argument is not a file. Treating the command line as a json/yaml object"); configurationSource = args[0]; } final CuratorProjectionServer server = startServer(configurationSource); Runnable shutdown = new Runnable() { @Override public void run() { server.stop(); } }; Thread hook = new Thread(shutdown); Runtime.getRuntime().addShutdownHook(hook); } public static CuratorProjectionServer startServer(String configurationSource) throws Exception { Configuration configuration = new ConfigurationBuilder(configurationSource).build(); final CuratorProjectionServer server = new CuratorProjectionServer(configuration); server.start(); return server; } public CuratorProjectionServer(Configuration configuration) { this.configuration = configuration; connectionManager = new ConnectionManager(configuration.getConnections(), configuration.getProjectionExpiration().toMillis()); EventService eventService = new EventService(connectionManager, configuration.getPingTime().toMillis()); DiscoveryService discoveryService = new DiscoveryService(connectionManager); CuratorProjectionService projectionService = new CuratorProjectionService(connectionManager); DiscoveryServiceLowLevel discoveryServiceLowLevel = new DiscoveryServiceLowLevel(connectionManager); ThriftServiceProcessor processor = new ThriftServiceProcessor(new ThriftCodecManager(), Lists.newArrayList(), projectionService, eventService, discoveryService, discoveryServiceLowLevel); server = new ThriftServer(processor, configuration.getThrift()); } public void start() { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Already started"); configuration.getLogging().configure(new MetricRegistry(), "curator-rpc"); connectionManager.start(); server.start(); log.info("Server listening on port: " + configuration.getThrift().getPort()); } public void stop() { if ( state.compareAndSet(State.STARTED, State.STOPPED) ) { log.info("Stopping..."); server.close(); connectionManager.close(); configuration.getLogging().stop(); log.info("Stopped"); } } private static void printHelp() throws IOException { URL helpUrl = Resources.getResource("curator/help.txt"); System.out.println(Resources.toString(helpUrl, Charset.defaultCharset())); System.out.println(); System.out.println("======= Curator Thrift IDL ======="); System.out.println(); URL idlUrl = Resources.getResource("curator.thrift"); System.out.println(Resources.toString(idlUrl, Charset.defaultCharset())); } } curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/configuration/000077500000000000000000000000001245521677600326465ustar00rootroot00000000000000AuthorizationConfiguration.java000066400000000000000000000023321245521677600410220ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/configuration/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.configuration; public class AuthorizationConfiguration { private String scheme; private String auth; public String getScheme() { return scheme; } public void setScheme(String scheme) { this.scheme = scheme; } public String getAuth() { return auth; } public void setAuth(String auth) { this.auth = auth; } } BoundedExponentialBackoffRetryConfiguration.java000066400000000000000000000041421245521677600442540ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/configuration/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.configuration; import com.fasterxml.jackson.annotation.JsonTypeName; import io.airlift.units.Duration; import org.apache.curator.RetryPolicy; import org.apache.curator.retry.BoundedExponentialBackoffRetry; import java.util.concurrent.TimeUnit; @JsonTypeName("bounded-exponential-backoff") public class BoundedExponentialBackoffRetryConfiguration extends RetryPolicyConfiguration { private Duration baseSleepTime = new Duration(100, TimeUnit.MILLISECONDS); private Duration maxSleepTime = new Duration(30, TimeUnit.SECONDS); private int maxRetries = 3; @Override public RetryPolicy build() { return new BoundedExponentialBackoffRetry((int)baseSleepTime.toMillis(), (int)maxSleepTime.toMillis(), maxRetries); } public Duration getBaseSleepTime() { return baseSleepTime; } public void setBaseSleepTime(Duration baseSleepTime) { this.baseSleepTime = baseSleepTime; } public int getMaxRetries() { return maxRetries; } public void setMaxRetries(int maxRetries) { this.maxRetries = maxRetries; } public Duration getMaxSleepTime() { return maxSleepTime; } public void setMaxSleepTime(Duration maxSleepTime) { this.maxSleepTime = maxSleepTime; } } Configuration.java000066400000000000000000000047271245521677600362530ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/configuration/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.configuration; import com.facebook.swift.service.ThriftServerConfig; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import io.airlift.units.Duration; import io.dropwizard.logging.LoggingFactory; import java.util.List; import java.util.concurrent.TimeUnit; public class Configuration { private ThriftServerConfig thrift = new ThriftServerConfig(); private LoggingFactory logging = new LoggingFactory(); private Duration projectionExpiration = new Duration(3, TimeUnit.MINUTES); private Duration pingTime = new Duration(5, TimeUnit.SECONDS); private List connections = Lists.newArrayList(); public LoggingFactory getLogging() { return logging; } public void setLogging(LoggingFactory logging) { this.logging = logging; } public ThriftServerConfig getThrift() { return thrift; } public void setThrift(ThriftServerConfig thrift) { this.thrift = thrift; } public Duration getProjectionExpiration() { return projectionExpiration; } public void setProjectionExpiration(Duration projectionExpiration) { this.projectionExpiration = projectionExpiration; } public Duration getPingTime() { return pingTime; } public void setPingTime(Duration pingTime) { this.pingTime = pingTime; } public List getConnections() { return ImmutableList.copyOf(connections); } public void setConnections(List connections) { this.connections = connections; } } ConfigurationBuilder.java000066400000000000000000000071551245521677600375600ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/configuration/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.configuration; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.SubtypeResolver; import com.fasterxml.jackson.databind.jsontype.impl.StdSubtypeResolver; import io.dropwizard.configuration.ConfigurationFactory; import io.dropwizard.configuration.ConfigurationFactoryFactory; import io.dropwizard.configuration.ConfigurationSourceProvider; import io.dropwizard.configuration.DefaultConfigurationFactoryFactory; import io.dropwizard.jackson.AnnotationSensitivePropertyNamingStrategy; import io.dropwizard.jackson.LogbackModule; import io.dropwizard.logging.ConsoleAppenderFactory; import io.dropwizard.logging.FileAppenderFactory; import io.dropwizard.logging.LoggingFactory; import io.dropwizard.logging.SyslogAppenderFactory; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.logging.Slf4JLoggerFactory; import javax.validation.Validation; import javax.validation.ValidatorFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; public class ConfigurationBuilder { private final String configurationSource; static { LoggingFactory.bootstrap(); InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory()); } public ConfigurationBuilder(String configurationSource) { this.configurationSource = configurationSource; } public Configuration build() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new LogbackModule()); mapper.setPropertyNamingStrategy(new AnnotationSensitivePropertyNamingStrategy()); SubtypeResolver subtypeResolver = new StdSubtypeResolver(); subtypeResolver.registerSubtypes ( ConsoleAppenderFactory.class, FileAppenderFactory.class, SyslogAppenderFactory.class, ExponentialBackoffRetryConfiguration.class, RetryNTimesConfiguration.class ); mapper.setSubtypeResolver(subtypeResolver); ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); ConfigurationFactoryFactory factoryFactory = new DefaultConfigurationFactoryFactory(); ConfigurationFactory configurationFactory = factoryFactory.create(Configuration.class, validatorFactory.getValidator(), mapper, "curator"); ConfigurationSourceProvider provider = new ConfigurationSourceProvider() { @Override public InputStream open(String path) throws IOException { return new ByteArrayInputStream(configurationSource.getBytes(Charset.defaultCharset())); } }; return configurationFactory.build(provider, ""); } } ConnectionConfiguration.java000066400000000000000000000074011245521677600402630ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/configuration/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.configuration; import com.google.common.base.Preconditions; import io.airlift.units.Duration; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import javax.validation.constraints.NotNull; import java.util.concurrent.TimeUnit; public class ConnectionConfiguration { @NotNull private String name; private String connectionString = null; private Duration sessionLength = new Duration(1, TimeUnit.MINUTES); private Duration connectionTimeout = new Duration(15, TimeUnit.SECONDS); private AuthorizationConfiguration authorization = null; private String namespace = null; private RetryPolicyConfiguration retry = new ExponentialBackoffRetryConfiguration(); public String getName() { return name; } public void setName(String name) { this.name = name; } public String getConnectionString() { return connectionString; } public void setConnectionString(String connectionString) { this.connectionString = connectionString; } public Duration getSessionLength() { return sessionLength; } public void setSessionLength(Duration sessionLength) { this.sessionLength = sessionLength; } public Duration getConnectionTimeout() { return connectionTimeout; } public void setConnectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; } public AuthorizationConfiguration getAuthorization() { return authorization; } public void setAuthorization(AuthorizationConfiguration authorization) { this.authorization = authorization; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public RetryPolicyConfiguration getRetry() { return retry; } public void setRetry(RetryPolicyConfiguration retry) { this.retry = retry; } public CuratorFramework build() { Preconditions.checkState((connectionString != null) && (connectionString.length() > 0), "You must specify a connection string for connection: " + name); Preconditions.checkNotNull(retry, "retry cannot be null"); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); builder = builder .connectString(connectionString) .sessionTimeoutMs((int)sessionLength.toMillis()) .connectionTimeoutMs((int)connectionTimeout.toMillis()) .retryPolicy(retry.build()); if ( authorization != null ) { builder = builder.authorization(authorization.getScheme(), authorization.getAuth().getBytes()); } if ( namespace != null ) { builder = builder.namespace(namespace); } return builder.build(); } } ExponentialBackoffRetryConfiguration.java000066400000000000000000000034411245521677600427540ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/configuration/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.configuration; import com.fasterxml.jackson.annotation.JsonTypeName; import io.airlift.units.Duration; import org.apache.curator.RetryPolicy; import org.apache.curator.retry.ExponentialBackoffRetry; import java.util.concurrent.TimeUnit; @JsonTypeName("exponential-backoff") public class ExponentialBackoffRetryConfiguration extends RetryPolicyConfiguration { private Duration baseSleepTime = new Duration(100, TimeUnit.MILLISECONDS); private int maxRetries = 3; @Override public RetryPolicy build() { return new ExponentialBackoffRetry((int)baseSleepTime.toMillis(), maxRetries); } public Duration getBaseSleepTime() { return baseSleepTime; } public void setBaseSleepTime(Duration baseSleepTime) { this.baseSleepTime = baseSleepTime; } public int getMaxRetries() { return maxRetries; } public void setMaxRetries(int maxRetries) { this.maxRetries = maxRetries; } } RetryNTimesConfiguration.java000066400000000000000000000033301245521677600404060ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/configuration/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.configuration; import com.fasterxml.jackson.annotation.JsonTypeName; import io.airlift.units.Duration; import org.apache.curator.RetryPolicy; import org.apache.curator.retry.RetryNTimes; import java.util.concurrent.TimeUnit; @JsonTypeName("ntimes") public class RetryNTimesConfiguration extends RetryPolicyConfiguration { private Duration sleepBetweenRetries = new Duration(100, TimeUnit.MILLISECONDS); private int n = 3; @Override public RetryPolicy build() { return new RetryNTimes(n, (int)sleepBetweenRetries.toMillis()); } public Duration getSleepBetweenRetries() { return sleepBetweenRetries; } public void setSleepBetweenRetries(Duration sleepBetweenRetries) { this.sleepBetweenRetries = sleepBetweenRetries; } public int getN() { return n; } public void setN(int n) { this.n = n; } } RetryPolicyConfiguration.java000066400000000000000000000021211245521677600404430ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/configuration/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.configuration; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.apache.curator.RetryPolicy; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") public abstract class RetryPolicyConfiguration { public abstract RetryPolicy build(); } curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/connections/000077500000000000000000000000001245521677600323215ustar00rootroot00000000000000Closer.java000066400000000000000000000016151245521677600343370ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/connections/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.connections; public interface Closer { public void close(); } ConnectionManager.java000066400000000000000000000117201245521677600365000ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/connections/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.connections; import com.google.common.base.Preconditions; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalListener; import com.google.common.cache.RemovalNotification; import com.google.common.collect.ImmutableMap; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.ThreadUtils; import org.apache.curator.x.rpc.configuration.ConnectionConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.util.List; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; public class ConnectionManager implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final Cache cache; private final AtomicReference state = new AtomicReference(State.LATENT); private final Map connections; private final ScheduledExecutorService service = ThreadUtils.newSingleThreadScheduledExecutor("ConnectionManager"); private static final int FORCED_CLEANUP_SECONDS = 30; private enum State { LATENT, STARTED, CLOSED } public ConnectionManager(List connections, long expirationMs) { this.connections = buildConnectionsMap(connections); RemovalListener listener = new RemovalListener() { @SuppressWarnings("NullableProblems") @Override public void onRemoval(RemovalNotification notification) { if ( notification != null ) { log.debug(String.format("Entry being removed. id (%s), reason (%s)", notification.getKey(), notification.getCause())); CuratorEntry entry = notification.getValue(); if ( entry != null ) { entry.close(); } } } }; cache = CacheBuilder.newBuilder().expireAfterAccess(expirationMs, TimeUnit.MILLISECONDS).removalListener(listener).build(); } public void start() { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Already started"); Runnable cleanup = new Runnable() { @Override public void run() { cache.cleanUp(); } }; service.scheduleWithFixedDelay(cleanup, FORCED_CLEANUP_SECONDS, 30, TimeUnit.SECONDS); } @Override public void close() { if ( state.compareAndSet(State.STARTED, State.CLOSED) ) { service.shutdownNow(); cache.invalidateAll(); cache.cleanUp(); } } public CuratorFramework newConnection(String name) { ConnectionConfiguration configuration = connections.get(name); return (configuration != null) ? configuration.build() : null; } public void add(String id, CuratorFramework client) { Preconditions.checkState(state.get() == State.STARTED, "Not started"); cache.put(id, new CuratorEntry(client)); } public CuratorEntry get(String id) { return (state.get() == State.STARTED) ? cache.getIfPresent(id) : null; } public CuratorEntry remove(String id) { Preconditions.checkState(state.get() == State.STARTED, "Not started"); return cache.asMap().remove(id); } private Map buildConnectionsMap(List connections) { Preconditions.checkArgument(connections.size() > 0, "You must have at least one connection configured"); ImmutableMap.Builder builder = ImmutableMap.builder(); for ( ConnectionConfiguration configuration : connections ) { builder.put(configuration.getName(), configuration); } return builder.build(); } } CuratorEntry.java000066400000000000000000000120441245521677600355470ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/connections/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.connections; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.google.common.collect.Queues; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.x.rpc.idl.exceptions.ExceptionType; import org.apache.curator.x.rpc.idl.exceptions.RpcException; import org.apache.curator.x.rpc.idl.structs.CuratorProjection; import org.apache.curator.x.rpc.idl.structs.RpcCuratorEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.util.Map; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; public class CuratorEntry implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework client; private final BlockingQueue events = Queues.newLinkedBlockingQueue(); private final AtomicReference state = new AtomicReference(State.OPEN); private final Map things = Maps.newConcurrentMap(); public static T mustGetThing(CuratorEntry entry, String id, Class clazz) { T thing = entry.getThing(id, clazz); Preconditions.checkNotNull(thing, "No item of type " + clazz.getSimpleName() + " found with id " + id); return thing; } private static class Entry { final Object thing; final Closer closer; private Entry(Object thing, Closer closer) { this.thing = thing; this.closer = closer; } } private enum State { OPEN, CLOSED } public CuratorEntry(CuratorFramework client) { this.client = client; } @Override public void close() { if ( state.compareAndSet(State.OPEN, State.CLOSED) ) { for ( Map.Entry mapEntry : things.entrySet() ) { Entry entry = mapEntry.getValue(); if ( entry.closer != null ) { log.debug(String.format("Closing left over thing. Type: %s - Id: %s", entry.thing.getClass(), mapEntry.getKey())); entry.closer.close(); } } things.clear(); client.close(); events.clear(); } } public RpcCuratorEvent pollForEvent(long maxWaitMs) throws InterruptedException { if ( state.get() == State.OPEN ) { return events.poll(maxWaitMs, TimeUnit.MILLISECONDS); } return null; } public void addEvent(RpcCuratorEvent event) { if ( state.get() == State.OPEN ) { events.offer(event); } } public static CuratorEntry mustGetEntry(ConnectionManager connectionManager, CuratorProjection projection) throws RpcException { CuratorEntry entry = connectionManager.get(projection.id); if ( entry == null ) { throw new RpcException(ExceptionType.GENERAL, null, null, "No CuratorProjection found with the id: " + projection.id); } return entry; } public CuratorFramework getClient() { return (state.get() == State.OPEN) ? client : null; } public String addThing(Object thing, Closer closer) { return addThing(newId(), thing, closer); } public static String newId() { return UUID.randomUUID().toString(); } public T getThing(String id, Class clazz) { Entry entry = (id != null) ? things.get(id) : null; return cast(clazz, entry); } public boolean closeThing(String id) { Entry entry = (id != null) ? things.remove(id) : null; if ( entry != null ) { entry.closer.close(); } return false; } private String addThing(String id, T thing, Closer closer) { things.put(id, new Entry(thing, closer)); return id; } private T cast(Class clazz, Entry entry) { if ( entry != null ) { return clazz.cast(entry.thing); } return null; } } curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/details/000077500000000000000000000000001245521677600314245ustar00rootroot00000000000000RpcBackgroundCallback.java000066400000000000000000000034101245521677600363470ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/details/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.details; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.x.rpc.idl.structs.RpcCuratorEvent; import org.apache.curator.x.rpc.idl.structs.CuratorProjection; import org.apache.curator.x.rpc.idl.services.CuratorProjectionService; public class RpcBackgroundCallback implements BackgroundCallback { private final CuratorProjection projection; private final CuratorProjectionService projectionService; public RpcBackgroundCallback(CuratorProjectionService projectionService, CuratorProjection projection) { this.projection = projection; this.projectionService = projectionService; } @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { projectionService.addEvent(projection, new RpcCuratorEvent(event)); } } RpcWatcher.java000066400000000000000000000031361245521677600342550ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/details/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.details; import org.apache.curator.x.rpc.idl.structs.RpcCuratorEvent; import org.apache.curator.x.rpc.idl.structs.CuratorProjection; import org.apache.curator.x.rpc.idl.services.CuratorProjectionService; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; public class RpcWatcher implements Watcher { private final CuratorProjection projection; private final CuratorProjectionService projectionService; public RpcWatcher(CuratorProjectionService projectionService, CuratorProjection projection) { this.projection = projection; this.projectionService = projectionService; } @Override public void process(WatchedEvent event) { projectionService.addEvent(projection, new RpcCuratorEvent(event)); } } curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/000077500000000000000000000000001245521677600305475ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/discovery/000077500000000000000000000000001245521677600325565ustar00rootroot00000000000000DiscoveryInstance.java000066400000000000000000000060101245521677600367730ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.discovery; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; import com.google.common.base.Objects; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceType; import org.apache.curator.x.discovery.UriSpec; @ThriftStruct public class DiscoveryInstance { @ThriftField(1) public String name; @ThriftField(2) public String id; @ThriftField(3) public String address; @ThriftField(4) public int port; @ThriftField(5) public int sslPort; @ThriftField(6) public byte[] payload; @ThriftField(7) public long registrationTimeUTC; @ThriftField(8) public DiscoveryInstanceType serviceType; @ThriftField(9) public String uriSpec; public DiscoveryInstance() { } public DiscoveryInstance(ServiceInstance instance) { if ( instance != null ) { this.name = instance.getName(); this.id = instance.getId(); this.address = instance.getAddress(); this.port = Objects.firstNonNull(instance.getPort(), 0); this.sslPort = Objects.firstNonNull(instance.getSslPort(), 0); this.payload = instance.getPayload(); this.registrationTimeUTC = instance.getRegistrationTimeUTC(); this.serviceType = DiscoveryInstanceType.valueOf(instance.getServiceType().name()); this.uriSpec = instance.buildUriSpec(); } } public DiscoveryInstance(String name, String id, String address, int port, int sslPort, byte[] payload, long registrationTimeUTC, DiscoveryInstanceType serviceType, String uriSpec) { this.name = name; this.id = id; this.address = address; this.port = port; this.sslPort = sslPort; this.payload = payload; this.registrationTimeUTC = registrationTimeUTC; this.serviceType = serviceType; this.uriSpec = uriSpec; } public ServiceInstance toReal() { return new ServiceInstance(name, id, address, port, sslPort, payload, registrationTimeUTC, ServiceType.valueOf(serviceType.name()), new UriSpec(uriSpec)); } } DiscoveryInstanceType.java000066400000000000000000000016471245521677600376500ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.discovery; public enum DiscoveryInstanceType { DYNAMIC, STATIC, PERMANENT } DiscoveryProjection.java000066400000000000000000000022161245521677600373470ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.discovery; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class DiscoveryProjection { @ThriftField(1) public String id; public DiscoveryProjection() { } public DiscoveryProjection(String id) { this.id = id; } } DiscoveryProviderProjection.java000066400000000000000000000022461245521677600410650ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.discovery; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class DiscoveryProviderProjection { @ThriftField(1) public String id; public DiscoveryProviderProjection() { } public DiscoveryProviderProjection(String id) { this.id = id; } } DiscoveryService.java000066400000000000000000000222221245521677600366320ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.discovery; import com.facebook.swift.service.ThriftMethod; import com.facebook.swift.service.ThriftService; import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import org.apache.curator.x.discovery.DownInstancePolicy; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceProvider; import org.apache.curator.x.discovery.ServiceType; import org.apache.curator.x.discovery.strategies.RandomStrategy; import org.apache.curator.x.discovery.strategies.RoundRobinStrategy; import org.apache.curator.x.discovery.strategies.StickyStrategy; import org.apache.curator.x.rpc.connections.Closer; import org.apache.curator.x.rpc.connections.ConnectionManager; import org.apache.curator.x.rpc.connections.CuratorEntry; import org.apache.curator.x.rpc.idl.exceptions.RpcException; import org.apache.curator.x.rpc.idl.structs.CuratorProjection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Collection; import java.util.concurrent.TimeUnit; @ThriftService public class DiscoveryService { private final Logger log = LoggerFactory.getLogger(getClass()); private final ConnectionManager connectionManager; public DiscoveryService(ConnectionManager connectionManager) { this.connectionManager = connectionManager; } @ThriftMethod public DiscoveryInstance makeDiscoveryInstance(String name, byte[] payload, int port) throws RpcException { try { ServiceInstance serviceInstance = ServiceInstance.builder() .serviceType(ServiceType.DYNAMIC) .name(name) .payload(payload) .port(port) .build(); return new DiscoveryInstance(serviceInstance); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public DiscoveryProjection startDiscovery(CuratorProjection projection, final String basePath, DiscoveryInstance yourInstance) throws RpcException { try { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); final ServiceDiscovery serviceDiscovery = ServiceDiscoveryBuilder .builder(byte[].class) .basePath(basePath) .client(entry.getClient()) .thisInstance((yourInstance != null) ? yourInstance.toReal() : null) .build(); serviceDiscovery.start(); Closer closer = new Closer() { @Override public void close() { try { serviceDiscovery.close(); } catch ( IOException e ) { log.error("Could not close ServiceDiscovery with basePath: " + basePath, e); } } }; String id = entry.addThing(serviceDiscovery, closer); return new DiscoveryProjection(id); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public DiscoveryProviderProjection startProvider(CuratorProjection projection, DiscoveryProjection discoveryProjection, final String serviceName, ProviderStrategyType providerStrategy, int downTimeoutMs, int downErrorThreshold) throws RpcException { ProviderStrategy strategy; switch ( providerStrategy ) { default: case RANDOM: { strategy = new RandomStrategy(); break; } case STICKY_RANDOM: { strategy = new StickyStrategy(new RandomStrategy()); break; } case STICKY_ROUND_ROBIN: { strategy = new StickyStrategy(new RoundRobinStrategy()); break; } case ROUND_ROBIN: { strategy = new RoundRobinStrategy(); break; } } CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); @SuppressWarnings("unchecked") ServiceDiscovery serviceDiscovery = CuratorEntry.mustGetThing(entry, discoveryProjection.id, ServiceDiscovery.class); final ServiceProvider serviceProvider = serviceDiscovery .serviceProviderBuilder() .downInstancePolicy(new DownInstancePolicy(downTimeoutMs, TimeUnit.MILLISECONDS, downErrorThreshold)) .providerStrategy(strategy) .serviceName(serviceName) .build(); try { serviceProvider.start(); Closer closer = new Closer() { @Override public void close() { try { serviceProvider.close(); } catch ( IOException e ) { log.error("Could not close ServiceProvider with serviceName: " + serviceName, e); } } }; String id = entry.addThing(serviceProvider, closer); return new DiscoveryProviderProjection(id); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public DiscoveryInstance getInstance(CuratorProjection projection, DiscoveryProviderProjection providerProjection) throws RpcException { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); @SuppressWarnings("unchecked") ServiceProvider serviceProvider = CuratorEntry.mustGetThing(entry, providerProjection.id, ServiceProvider.class); try { return new DiscoveryInstance(serviceProvider.getInstance()); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public Collection getAllInstances(CuratorProjection projection, DiscoveryProviderProjection providerProjection) throws RpcException { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); @SuppressWarnings("unchecked") ServiceProvider serviceProvider = CuratorEntry.mustGetThing(entry, providerProjection.id, ServiceProvider.class); try { Collection> allInstances = serviceProvider.getAllInstances(); Collection transformed = Collections2.transform ( allInstances, new Function, DiscoveryInstance>() { @Override public DiscoveryInstance apply(ServiceInstance instance) { return new DiscoveryInstance(instance); } } ); return Lists.newArrayList(transformed); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public void noteError(CuratorProjection projection, DiscoveryProviderProjection providerProjection, String instanceId) throws RpcException { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); @SuppressWarnings("unchecked") ServiceProvider serviceProvider = CuratorEntry.mustGetThing(entry, providerProjection.id, ServiceProvider.class); try { for ( ServiceInstance instance : serviceProvider.getAllInstances() ) { if ( instance.getId().equals(instanceId) ) { serviceProvider.noteError(instance); break; } } } catch ( Exception e ) { throw new RpcException(e); } } } DiscoveryServiceLowLevel.java000066400000000000000000000137231245521677600403120ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.discovery; import com.facebook.swift.service.ThriftMethod; import com.facebook.swift.service.ThriftService; import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.rpc.connections.ConnectionManager; import org.apache.curator.x.rpc.connections.CuratorEntry; import org.apache.curator.x.rpc.idl.exceptions.RpcException; import org.apache.curator.x.rpc.idl.structs.CuratorProjection; import java.util.Collection; @ThriftService public class DiscoveryServiceLowLevel { private final ConnectionManager connectionManager; public DiscoveryServiceLowLevel(ConnectionManager connectionManager) { this.connectionManager = connectionManager; } @ThriftMethod public void registerInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance) throws RpcException { try { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); @SuppressWarnings("unchecked") ServiceDiscovery serviceDiscovery = CuratorEntry.mustGetThing(entry, discoveryProjection.id, ServiceDiscovery.class); serviceDiscovery.registerService(instance.toReal()); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public void updateInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance) throws RpcException { try { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); @SuppressWarnings("unchecked") ServiceDiscovery serviceDiscovery = CuratorEntry.mustGetThing(entry, discoveryProjection.id, ServiceDiscovery.class); serviceDiscovery.updateService(instance.toReal()); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public void unregisterInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance) throws RpcException { try { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); @SuppressWarnings("unchecked") ServiceDiscovery serviceDiscovery = CuratorEntry.mustGetThing(entry, discoveryProjection.id, ServiceDiscovery.class); serviceDiscovery.unregisterService(instance.toReal()); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public Collection queryForNames(CuratorProjection projection, DiscoveryProjection discoveryProjection) throws RpcException { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); @SuppressWarnings("unchecked") ServiceDiscovery serviceDiscovery = CuratorEntry.mustGetThing(entry, discoveryProjection.id, ServiceDiscovery.class); try { return serviceDiscovery.queryForNames(); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public DiscoveryInstance queryForInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, String name, String id) throws RpcException { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); @SuppressWarnings("unchecked") ServiceDiscovery serviceDiscovery = CuratorEntry.mustGetThing(entry, discoveryProjection.id, ServiceDiscovery.class); try { return new DiscoveryInstance(serviceDiscovery.queryForInstance(name, id)); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public Collection queryForInstances(CuratorProjection projection, DiscoveryProjection discoveryProjection, String name) throws RpcException { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); @SuppressWarnings("unchecked") ServiceDiscovery serviceDiscovery = CuratorEntry.mustGetThing(entry, discoveryProjection.id, ServiceDiscovery.class); try { Collection> instances = serviceDiscovery.queryForInstances(name); Collection transformed = Collections2.transform ( instances, new Function, DiscoveryInstance>() { @Override public DiscoveryInstance apply(ServiceInstance instance) { return new DiscoveryInstance(instance); } } ); return Lists.newArrayList(transformed); } catch ( Exception e ) { throw new RpcException(e); } } } ProviderStrategyType.java000066400000000000000000000017061245521677600375250ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/discovery/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.discovery; public enum ProviderStrategyType { RANDOM, STICKY_RANDOM, STICKY_ROUND_ROBIN, ROUND_ROBIN } curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/exceptions/000077500000000000000000000000001245521677600327305ustar00rootroot00000000000000ExceptionType.java000066400000000000000000000016361245521677600363220ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/exceptions/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.exceptions; public enum ExceptionType { GENERAL, ZOOKEEPER, NODE } NodeExceptionType.java000066400000000000000000000016661245521677600371330ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/exceptions/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.exceptions; public enum NodeExceptionType { NONODE, BADVERSION, NODEEXISTS, NOTEMPTY } RpcException.java000066400000000000000000000060571245521677600361270ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/exceptions/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.exceptions; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; import com.facebook.swift.service.ThriftException; import org.apache.zookeeper.KeeperException; import java.io.PrintWriter; import java.io.StringWriter; @ThriftException(id = 1, type = RpcException.class, name = "CuratorException") @ThriftStruct("CuratorException") public class RpcException extends Exception { @ThriftField(1) public ExceptionType type; @ThriftField(2) public ZooKeeperExceptionType zooKeeperException; @ThriftField(3) public NodeExceptionType nodeException; @ThriftField(4) public String message; public RpcException() { } public RpcException(Exception e) { this.message = e.getLocalizedMessage(); if ( this.message == null ) { StringWriter str = new StringWriter(); e.printStackTrace(new PrintWriter(str)); this.message = str.toString(); } if ( KeeperException.class.isAssignableFrom(e.getClass()) ) { KeeperException keeperException = (KeeperException)e; switch ( keeperException.code() ) { default: { type = ExceptionType.ZOOKEEPER; zooKeeperException = ZooKeeperExceptionType.valueOf(keeperException.code().name()); nodeException = null; break; } case NONODE: case NODEEXISTS: case NOTEMPTY: case BADVERSION: { type = ExceptionType.NODE; zooKeeperException = null; nodeException = NodeExceptionType.valueOf(keeperException.code().name()); break; } } } else { type = ExceptionType.GENERAL; } } public RpcException(ExceptionType type, ZooKeeperExceptionType zooKeeperException, NodeExceptionType nodeException, String message) { this.type = type; this.zooKeeperException = zooKeeperException; this.nodeException = nodeException; this.message = message; } } ZooKeeperExceptionType.java000066400000000000000000000023131245521677600401370ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/exceptions/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.exceptions; public enum ZooKeeperExceptionType { SYSTEMERROR, RUNTIMEINCONSISTENCY, DATAINCONSISTENCY, CONNECTIONLOSS, MARSHALLINGERROR, UNIMPLEMENTED, OPERATIONTIMEOUT, BADARGUMENTS, APIERROR, NOAUTH, NOCHILDRENFOREPHEMERALS, INVALIDACL, AUTHFAILED, SESSIONEXPIRED, INVALIDCALLBACK, SESSIONMOVED, NOTREADONLY } curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/services/000077500000000000000000000000001245521677600323725ustar00rootroot00000000000000CuratorProjectionService.java000066400000000000000000000640331245521677600401610ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/services /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.services; import com.facebook.swift.service.ThriftMethod; import com.facebook.swift.service.ThriftService; import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.*; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.NodeCache; import org.apache.curator.framework.recipes.cache.NodeCacheListener; import org.apache.curator.framework.recipes.cache.PathChildrenCache; import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent; import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener; import org.apache.curator.framework.recipes.leader.LeaderLatch; import org.apache.curator.framework.recipes.leader.LeaderLatchListener; import org.apache.curator.framework.recipes.leader.Participant; import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex; import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreV2; import org.apache.curator.framework.recipes.locks.Lease; import org.apache.curator.framework.recipes.nodes.PersistentEphemeralNode; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.utils.ThreadUtils; import org.apache.curator.x.rpc.connections.Closer; import org.apache.curator.x.rpc.connections.ConnectionManager; import org.apache.curator.x.rpc.connections.CuratorEntry; import org.apache.curator.x.rpc.details.RpcBackgroundCallback; import org.apache.curator.x.rpc.details.RpcWatcher; import org.apache.curator.x.rpc.idl.exceptions.ExceptionType; import org.apache.curator.x.rpc.idl.exceptions.RpcException; import org.apache.curator.x.rpc.idl.structs.*; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; @ThriftService("CuratorService") public class CuratorProjectionService { private final Logger log = LoggerFactory.getLogger(getClass()); private final ConnectionManager connectionManager; public CuratorProjectionService(ConnectionManager connectionManager) { this.connectionManager = connectionManager; } @ThriftMethod public CuratorProjection newCuratorProjection(String connectionName) throws RpcException { CuratorFramework client = connectionManager.newConnection(connectionName); if ( client == null ) { throw new RpcException(ExceptionType.GENERAL, null, null, "No connection configuration was found with the name: " + connectionName); } String id = CuratorEntry.newId(); client.start(); connectionManager.add(id, client); final CuratorProjection projection = new CuratorProjection(id); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { addEvent(projection, new RpcCuratorEvent(newState)); } }; client.getConnectionStateListenable().addListener(listener); return projection; } @ThriftMethod public void closeCuratorProjection(CuratorProjection projection) { CuratorEntry entry = connectionManager.remove(projection.id); if ( entry != null ) { entry.close(); } } @ThriftMethod(oneway = true) public void pingCuratorProjection(CuratorProjection projection) { connectionManager.get(projection.id); } @ThriftMethod public OptionalPath createNode(CuratorProjection projection, CreateSpec spec) throws RpcException { try { CuratorFramework client = CuratorEntry.mustGetEntry(connectionManager, projection).getClient(); Object builder = client.create(); if ( spec.creatingParentsIfNeeded ) { builder = castBuilder(builder, CreateBuilder.class).creatingParentsIfNeeded(); } if ( spec.compressed ) { builder = castBuilder(builder, Compressible.class).compressed(); } if ( spec.withProtection ) { builder = castBuilder(builder, CreateBuilder.class).withProtection(); } if ( spec.mode != null ) { builder = castBuilder(builder, CreateModable.class).withMode(CreateMode.valueOf(spec.mode.name())); } if ( spec.asyncContext != null ) { BackgroundCallback backgroundCallback = new RpcBackgroundCallback(this, projection); builder = castBuilder(builder, Backgroundable.class).inBackground(backgroundCallback, spec.asyncContext); } Object path = castBuilder(builder, PathAndBytesable.class).forPath(spec.path, spec.data); return new OptionalPath((path != null) ? String.valueOf(path) : null); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public void deleteNode(CuratorProjection projection, DeleteSpec spec) throws RpcException { try { CuratorFramework client = CuratorEntry.mustGetEntry(connectionManager, projection).getClient(); Object builder = client.delete(); if ( spec.guaranteed ) { builder = castBuilder(builder, DeleteBuilder.class).guaranteed(); } if ( spec.version != null ) { builder = castBuilder(builder, Versionable.class).withVersion(spec.version.version); } if ( spec.asyncContext != null ) { BackgroundCallback backgroundCallback = new RpcBackgroundCallback(this, projection); builder = castBuilder(builder, Backgroundable.class).inBackground(backgroundCallback, spec.asyncContext); } castBuilder(builder, Pathable.class).forPath(spec.path); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public OptionalData getData(CuratorProjection projection, GetDataSpec spec) throws RpcException { try { CuratorFramework client = CuratorEntry.mustGetEntry(connectionManager, projection).getClient(); Object builder = client.getData(); if ( spec.watched ) { builder = castBuilder(builder, Watchable.class).usingWatcher(new RpcWatcher(this, projection)); } if ( spec.decompressed ) { builder = castBuilder(builder, Decompressible.class).decompressed(); } if ( spec.asyncContext != null ) { BackgroundCallback backgroundCallback = new RpcBackgroundCallback(this, projection); builder = castBuilder(builder, Backgroundable.class).inBackground(backgroundCallback); } Stat stat = new Stat(); builder = castBuilder(builder, Statable.class).storingStatIn(stat); byte[] bytes = (byte[])castBuilder(builder, Pathable.class).forPath(spec.path); return new OptionalData(bytes); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public OptionalRpcStat setData(CuratorProjection projection, SetDataSpec spec) throws RpcException { try { CuratorFramework client = CuratorEntry.mustGetEntry(connectionManager, projection).getClient(); Object builder = client.setData(); if ( spec.watched ) { builder = castBuilder(builder, Watchable.class).usingWatcher(new RpcWatcher(this, projection)); } if ( spec.version != null ) { builder = castBuilder(builder, Versionable.class).withVersion(spec.version.version); } if ( spec.compressed ) { builder = castBuilder(builder, Compressible.class).compressed(); } if ( spec.asyncContext != null ) { BackgroundCallback backgroundCallback = new RpcBackgroundCallback(this, projection); builder = castBuilder(builder, Backgroundable.class).inBackground(backgroundCallback); } Stat stat = (Stat)castBuilder(builder, PathAndBytesable.class).forPath(spec.path, spec.data); return new OptionalRpcStat(RpcCuratorEvent.toRpcStat(stat)); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public OptionalRpcStat exists(CuratorProjection projection, ExistsSpec spec) throws RpcException { try { CuratorFramework client = CuratorEntry.mustGetEntry(connectionManager, projection).getClient(); Object builder = client.checkExists(); if ( spec.watched ) { builder = castBuilder(builder, Watchable.class).usingWatcher(new RpcWatcher(this, projection)); } if ( spec.asyncContext != null ) { BackgroundCallback backgroundCallback = new RpcBackgroundCallback(this, projection); castBuilder(builder, Backgroundable.class).inBackground(backgroundCallback); } Stat stat = (Stat)castBuilder(builder, Pathable.class).forPath(spec.path); return new OptionalRpcStat((stat != null) ? RpcCuratorEvent.toRpcStat(stat) : null); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public OptionalChildrenList getChildren(CuratorProjection projection, GetChildrenSpec spec) throws RpcException { try { CuratorFramework client = CuratorEntry.mustGetEntry(connectionManager, projection).getClient(); Object builder = client.getChildren(); if ( spec.watched ) { builder = castBuilder(builder, Watchable.class).usingWatcher(new RpcWatcher(this, projection)); } if ( spec.asyncContext != null ) { BackgroundCallback backgroundCallback = new RpcBackgroundCallback(this, projection); builder = castBuilder(builder, Backgroundable.class).inBackground(backgroundCallback); } @SuppressWarnings("unchecked") List children = (List)castBuilder(builder, Pathable.class).forPath(spec.path); return new OptionalChildrenList(children); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public void sync(CuratorProjection projection, String path, String asyncContext) throws RpcException { try { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); BackgroundCallback backgroundCallback = new RpcBackgroundCallback(this, projection); entry.getClient().sync().inBackground(backgroundCallback, asyncContext).forPath(path); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public boolean closeGenericProjection(CuratorProjection projection, String id) throws RpcException { try { if ( id.equals(projection.id) ) { closeCuratorProjection(projection); return true; } else { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); return entry.closeThing(id); } } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public OptionalLockProjection acquireLock(CuratorProjection projection, final String path, int maxWaitMs) throws RpcException { try { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); final InterProcessSemaphoreMutex lock = new InterProcessSemaphoreMutex(entry.getClient(), path); if ( !lock.acquire(maxWaitMs, TimeUnit.MILLISECONDS) ) { return new OptionalLockProjection(); } Closer closer = new Closer() { @Override public void close() { if ( lock.isAcquiredInThisProcess() ) { try { lock.release(); } catch ( Exception e ) { log.error("Could not release left-over lock for path: " + path, e); } } } }; String id = entry.addThing(lock, closer); return new OptionalLockProjection(new LockProjection(id)); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public LeaderResult startLeaderSelector(final CuratorProjection projection, final String path, final String participantId, int waitForLeadershipMs) throws RpcException { try { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); final LeaderLatch leaderLatch = new LeaderLatch(entry.getClient(), path, participantId); leaderLatch.start(); Closer closer = new Closer() { @Override public void close() { try { leaderLatch.close(); } catch ( IOException e ) { log.error("Could not close left-over leader latch for path: " + path, e); } } }; String id = entry.addThing(leaderLatch, closer); LeaderLatchListener listener = new LeaderLatchListener() { @Override public void isLeader() { addEvent(projection, new RpcCuratorEvent(new LeaderEvent(path, participantId, true))); } @Override public void notLeader() { addEvent(projection, new RpcCuratorEvent(new LeaderEvent(path, participantId, false))); } }; leaderLatch.addListener(listener); if ( waitForLeadershipMs > 0 ) { leaderLatch.await(waitForLeadershipMs, TimeUnit.MILLISECONDS); } return new LeaderResult(new LeaderProjection(id), leaderLatch.hasLeadership()); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public Collection getLeaderParticipants(CuratorProjection projection, LeaderProjection leaderProjection) throws RpcException { try { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); LeaderLatch leaderLatch = CuratorEntry.mustGetThing(entry, leaderProjection.id, LeaderLatch.class); Collection participants = leaderLatch.getParticipants(); Collection transformed = Collections2.transform ( participants, new Function() { @Override public RpcParticipant apply(Participant participant) { return new RpcParticipant(participant.getId(), participant.isLeader()); } } ); return Lists.newArrayList(transformed); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public boolean isLeader(CuratorProjection projection, LeaderProjection leaderProjection) throws RpcException { try { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); LeaderLatch leaderLatch = CuratorEntry.mustGetThing(entry, leaderProjection.id, LeaderLatch.class); return leaderLatch.hasLeadership(); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public PathChildrenCacheProjection startPathChildrenCache(final CuratorProjection projection, final String path, boolean cacheData, boolean dataIsCompressed, PathChildrenCacheStartMode startMode) throws RpcException { try { final CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); final PathChildrenCache cache = new PathChildrenCache(entry.getClient(), path, cacheData, dataIsCompressed, ThreadUtils.newThreadFactory("PathChildrenCacheResource")); cache.start(PathChildrenCache.StartMode.valueOf(startMode.name())); Closer closer = new Closer() { @Override public void close() { try { cache.close(); } catch ( IOException e ) { log.error("Could not close left-over PathChildrenCache for path: " + path, e); } } }; String id = entry.addThing(cache, closer); PathChildrenCacheListener listener = new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws RpcException { entry.addEvent(new RpcCuratorEvent(new RpcPathChildrenCacheEvent(path, event))); } }; cache.getListenable().addListener(listener); return new PathChildrenCacheProjection(id); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public List getPathChildrenCacheData(CuratorProjection projection, PathChildrenCacheProjection cacheProjection) throws RpcException { try { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); PathChildrenCache pathChildrenCache = CuratorEntry.mustGetThing(entry, cacheProjection.id, PathChildrenCache.class); return Lists.transform ( pathChildrenCache.getCurrentData(), new Function() { @Override public RpcChildData apply(ChildData childData) { return new RpcChildData(childData); } } ); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public RpcChildData getPathChildrenCacheDataForPath(CuratorProjection projection, PathChildrenCacheProjection cacheProjection, String path) throws RpcException { try { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); PathChildrenCache pathChildrenCache = CuratorEntry.mustGetThing(entry, cacheProjection.id, PathChildrenCache.class); return new RpcChildData(pathChildrenCache.getCurrentData(path)); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public NodeCacheProjection startNodeCache(CuratorProjection projection, final String path, boolean dataIsCompressed, boolean buildInitial) throws RpcException { try { final CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); final NodeCache cache = new NodeCache(entry.getClient(), path, dataIsCompressed); cache.start(buildInitial); Closer closer = new Closer() { @Override public void close() { try { cache.close(); } catch ( IOException e ) { log.error("Could not close left-over NodeCache for path: " + path, e); } } }; String id = entry.addThing(cache, closer); NodeCacheListener listener = new NodeCacheListener() { @Override public void nodeChanged() { entry.addEvent(new RpcCuratorEvent(RpcCuratorEventType.NODE_CACHE, path)); } }; cache.getListenable().addListener(listener); return new NodeCacheProjection(id); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public RpcChildData getNodeCacheData(CuratorProjection projection, NodeCacheProjection cacheProjection) throws RpcException { try { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); NodeCache nodeCache = CuratorEntry.mustGetThing(entry, cacheProjection.id, NodeCache.class); return new RpcChildData(nodeCache.getCurrentData()); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public PersistentEphemeralNodeProjection startPersistentEphemeralNode(CuratorProjection projection, final String path, byte[] data, RpcPersistentEphemeralNodeMode mode) throws RpcException { try { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); final PersistentEphemeralNode node = new PersistentEphemeralNode(entry.getClient(), PersistentEphemeralNode.Mode.valueOf(mode.name()), path, data); node.start(); Closer closer = new Closer() { @Override public void close() { try { node.close(); } catch ( Exception e ) { log.error("Could not release left-over persistent ephemeral node for path: " + path, e); } } }; String id = entry.addThing(node, closer); return new PersistentEphemeralNodeProjection(id); } catch ( Exception e ) { throw new RpcException(e); } } @ThriftMethod public List acquireSemaphore(CuratorProjection projection, final String path, int acquireQty, int maxWaitMs, int maxLeases) throws RpcException { try { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); final InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(entry.getClient(), path, maxLeases); final Collection leases = semaphore.acquire(acquireQty, maxWaitMs, TimeUnit.MILLISECONDS); if ( leases == null ) { return Lists.newArrayList(); } List leaseProjections = Lists.newArrayList(); for ( final Lease lease : leases ) { Closer closer = new Closer() { @Override public void close() { try { semaphore.returnLease(lease); } catch ( Exception e ) { log.error("Could not release semaphore leases for path: " + path, e); } } }; leaseProjections.add(new LeaseProjection(entry.addThing(lease, closer))); } return leaseProjections; } catch ( Exception e ) { throw new RpcException(e); } } public void addEvent(CuratorProjection projection, RpcCuratorEvent event) { CuratorEntry entry = connectionManager.get(projection.id); if ( entry != null ) { entry.addEvent(event); } } private static T castBuilder(Object createBuilder, Class clazz) throws Exception { if ( clazz.isAssignableFrom(createBuilder.getClass()) ) { return clazz.cast(createBuilder); } throw new Exception("That operation is not available"); } } EventService.java000066400000000000000000000040311245521677600355560ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/services/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.services; import com.facebook.swift.service.ThriftMethod; import com.facebook.swift.service.ThriftService; import org.apache.curator.x.rpc.connections.CuratorEntry; import org.apache.curator.x.rpc.connections.ConnectionManager; import org.apache.curator.x.rpc.idl.exceptions.RpcException; import org.apache.curator.x.rpc.idl.structs.CuratorProjection; import org.apache.curator.x.rpc.idl.structs.RpcCuratorEvent; @ThriftService("EventService") public class EventService { private final ConnectionManager connectionManager; private final long pingTimeMs; public EventService(ConnectionManager connectionManager, long pingTimeMs) { this.connectionManager = connectionManager; this.pingTimeMs = pingTimeMs; } @ThriftMethod public RpcCuratorEvent getNextEvent(CuratorProjection projection) throws RpcException { try { CuratorEntry entry = CuratorEntry.mustGetEntry(connectionManager, projection); RpcCuratorEvent event = entry.pollForEvent(pingTimeMs); return (event != null) ? event : new RpcCuratorEvent(); } catch ( InterruptedException e ) { throw new RpcException(e); } } } curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/000077500000000000000000000000001245521677600322565ustar00rootroot00000000000000CreateSpec.java000066400000000000000000000034611245521677600350640ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class CreateSpec { @ThriftField(1) public String path; @ThriftField(2) public byte[] data; @ThriftField(3) public RpcCreateMode mode; @ThriftField(4) public String asyncContext; @ThriftField(5) public boolean compressed; @ThriftField(6) public boolean creatingParentsIfNeeded; @ThriftField(7) public boolean withProtection; public CreateSpec() { } public CreateSpec(String path, byte[] data, RpcCreateMode mode, String asyncContext, boolean compressed, boolean creatingParentsIfNeeded, boolean withProtection) { this.path = path; this.data = data; this.mode = mode; this.asyncContext = asyncContext; this.compressed = compressed; this.creatingParentsIfNeeded = creatingParentsIfNeeded; this.withProtection = withProtection; } } CuratorProjection.java000066400000000000000000000022061245521677600365160ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class CuratorProjection { @ThriftField(1) public String id; public CuratorProjection() { } public CuratorProjection(String id) { this.id = id; } } DeleteSpec.java000066400000000000000000000026751245521677600350710ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class DeleteSpec { @ThriftField(1) public String path; @ThriftField(2) public boolean guaranteed; @ThriftField(3) public String asyncContext; @ThriftField(4) public Version version; public DeleteSpec() { } public DeleteSpec(String path, boolean guaranteed, String asyncContext, Version version) { this.path = path; this.guaranteed = guaranteed; this.asyncContext = asyncContext; this.version = version; } } ExistsSpec.java000066400000000000000000000025171245521677600351410ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class ExistsSpec { @ThriftField(1) public String path; @ThriftField(2) public boolean watched; @ThriftField(3) public String asyncContext; public ExistsSpec() { } public ExistsSpec(String path, boolean watched, String asyncContext) { this.path = path; this.watched = watched; this.asyncContext = asyncContext; } } GetChildrenSpec.java000066400000000000000000000025361245521677600360530ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class GetChildrenSpec { @ThriftField(1) public String path; @ThriftField(2) public boolean watched; @ThriftField(3) public String asyncContext; public GetChildrenSpec() { } public GetChildrenSpec(String path, boolean watched, String asyncContext) { this.path = path; this.watched = watched; this.asyncContext = asyncContext; } } GetDataSpec.java000066400000000000000000000027101245521677600351660ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class GetDataSpec { @ThriftField(1) public String path; @ThriftField(2) public boolean watched; @ThriftField(3) public String asyncContext; @ThriftField(4) public boolean decompressed; public GetDataSpec() { } public GetDataSpec(String path, boolean watched, String asyncContext, boolean decompressed) { this.path = path; this.watched = watched; this.asyncContext = asyncContext; this.decompressed = decompressed; } } LeaderEvent.java000066400000000000000000000025321245521677600352420ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class LeaderEvent { @ThriftField(1) public String path; @ThriftField(2) public String participantId; @ThriftField(3) public boolean isLeader; public LeaderEvent() { } public LeaderEvent(String path, String participantId, boolean isLeader) { this.path = path; this.participantId = participantId; this.isLeader = isLeader; } } LeaderProjection.java000066400000000000000000000022031245521677600362700ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class LeaderProjection { @ThriftField(1) public String id; public LeaderProjection() { } public LeaderProjection(String id) { this.id = id; } } LeaderResult.java000066400000000000000000000024211245521677600354340ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class LeaderResult { @ThriftField(1) public LeaderProjection projection; @ThriftField(2) public boolean isLeader; public LeaderResult() { } public LeaderResult(LeaderProjection projection, boolean isLeader) { this.projection = projection; this.isLeader = isLeader; } } LeaseProjection.java000066400000000000000000000022001245521677600361220ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class LeaseProjection { @ThriftField(1) public String id; public LeaseProjection() { } public LeaseProjection(String id) { this.id = id; } } LockProjection.java000066400000000000000000000021751245521677600357740ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class LockProjection { @ThriftField(1) public String id; public LockProjection() { } public LockProjection(String id) { this.id = id; } } NodeCacheProjection.java000066400000000000000000000022141245521677600367070ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class NodeCacheProjection { @ThriftField(1) public String id; public NodeCacheProjection() { } public NodeCacheProjection(String id) { this.id = id; } } OptionalChildrenList.java000066400000000000000000000023121245521677600371320ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; import java.util.List; @ThriftStruct public class OptionalChildrenList { @ThriftField(1) public List children; public OptionalChildrenList() { } public OptionalChildrenList(List children) { this.children = children; } } OptionalData.java000066400000000000000000000021771245521677600354300ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class OptionalData { @ThriftField(1) public byte[] data; public OptionalData() { } public OptionalData(byte[] data) { this.data = data; } } OptionalLockProjection.java000066400000000000000000000023251245521677600374770ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class OptionalLockProjection { @ThriftField(1) public LockProjection lockProjection; public OptionalLockProjection() { } public OptionalLockProjection(LockProjection lockProjection) { this.lockProjection = lockProjection; } } OptionalPath.java000066400000000000000000000021771245521677600354530ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class OptionalPath { @ThriftField(1) public String path; public OptionalPath() { } public OptionalPath(String path) { this.path = path; } } OptionalRpcStat.java000066400000000000000000000022321245521677600361270ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct("OptionalStat") public class OptionalRpcStat { @ThriftField(1) public RpcStat stat; public OptionalRpcStat() { } public OptionalRpcStat(RpcStat stat) { this.stat = stat; } } PathChildrenCacheProjection.java000066400000000000000000000022441245521677600403720ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class PathChildrenCacheProjection { @ThriftField(1) public String id; public PathChildrenCacheProjection() { } public PathChildrenCacheProjection(String id) { this.id = id; } } PathChildrenCacheStartMode.java000066400000000000000000000017031245521677600401570ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; public enum PathChildrenCacheStartMode { NORMAL, BUILD_INITIAL_CACHE, POST_INITIALIZED_EVENT } PersistentEphemeralNodeProjection.java000066400000000000000000000022661245521677600416760ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class PersistentEphemeralNodeProjection { @ThriftField(1) public String id; public PersistentEphemeralNodeProjection() { } public PersistentEphemeralNodeProjection(String id) { this.id = id; } } RpcAcl.java000066400000000000000000000022741245521677600342130ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct("Acl") public class RpcAcl { @ThriftField(1) public int perms; @ThriftField(2) public RpcId id; public RpcAcl() { } public RpcAcl(int perms, RpcId id) { this.perms = perms; this.id = id; } } RpcChildData.java000066400000000000000000000031531245521677600353260ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; import org.apache.curator.framework.recipes.cache.ChildData; @ThriftStruct("ChildData") public class RpcChildData { @ThriftField(1) public String path; @ThriftField(2) public RpcStat stat; @ThriftField(3) public byte[] data; public RpcChildData() { } public RpcChildData(ChildData data) { if ( data != null ) { this.path = data.getPath(); this.stat = RpcCuratorEvent.toRpcStat(data.getStat()); this.data = data.getData(); } } public RpcChildData(String path, RpcStat stat, byte[] data) { this.path = path; this.stat = stat; this.data = data; } } RpcCreateMode.java000066400000000000000000000020201245521677600355110ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftEnum; @ThriftEnum("CreateMode") public enum RpcCreateMode { PERSISTENT, PERSISTENT_SEQUENTIAL, EPHEMERAL, EPHEMERAL_SEQUENTIAL } RpcCuratorEvent.java000066400000000000000000000146601245521677600361370ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; import com.google.common.base.Function; import com.google.common.collect.Lists; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.state.ConnectionState; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; import javax.annotation.Nullable; import java.util.List; @SuppressWarnings("deprecation") @ThriftStruct("CuratorEvent") public class RpcCuratorEvent { @ThriftField(2) public RpcCuratorEventType type; @ThriftField(3) public int resultCode; @ThriftField(4) public String path; @ThriftField(5) public String context; @ThriftField(6) public RpcStat stat; @ThriftField(7) public byte[] data; @ThriftField(8) public String name; @ThriftField(9) public List children; @ThriftField(10) public List aclList; @ThriftField(11) public RpcWatchedEvent watchedEvent; @ThriftField(12) public LeaderEvent leaderEvent; @ThriftField(13) public RpcPathChildrenCacheEvent childrenCacheEvent; public RpcCuratorEvent() { this.type = RpcCuratorEventType.PING; this.resultCode = 0; this.path = null; this.context = null; this.stat = null; this.data = null; this.name = null; this.children = null; this.aclList = null; this.watchedEvent = null; this.leaderEvent = null; this.childrenCacheEvent = null; } public RpcCuratorEvent(RpcCuratorEventType type, String path) { this.type = type; this.resultCode = 0; this.path = path; this.context = null; this.stat = null; this.data = null; this.name = null; this.children = null; this.aclList = null; this.watchedEvent = null; this.leaderEvent = null; this.childrenCacheEvent = null; } public RpcCuratorEvent(RpcPathChildrenCacheEvent childrenCacheEvent) { this.type = RpcCuratorEventType.PATH_CHILDREN_CACHE; this.resultCode = 0; this.path = null; this.context = null; this.stat = null; this.data = null; this.name = null; this.children = null; this.aclList = null; this.watchedEvent = null; this.leaderEvent = null; this.childrenCacheEvent = childrenCacheEvent; } public RpcCuratorEvent(CuratorEvent event) { this.type = RpcCuratorEventType.valueOf(event.getType().name()); this.resultCode = event.getResultCode(); this.path = event.getPath(); this.context = (event.getContext() != null) ? String.valueOf(event.getContext()) : null; this.stat = toRpcStat(event.getStat()); this.data = event.getData(); this.name = event.getName(); this.children = event.getChildren(); this.aclList = toRpcAclList(event.getACLList()); this.watchedEvent = toRpcWatchedEvent(event.getWatchedEvent()); this.leaderEvent = null; this.childrenCacheEvent = null; } public RpcCuratorEvent(ConnectionState newState) { this.type = RpcCuratorEventType.valueOf("CONNECTION_" + newState.name()); this.resultCode = 0; this.path = null; this.context = null; this.stat = null; this.data = null; this.name = null; this.children = null; this.aclList = null; this.watchedEvent = null; this.leaderEvent = null; this.childrenCacheEvent = null; } public RpcCuratorEvent(WatchedEvent event) { this.type = RpcCuratorEventType.WATCHED; this.resultCode = 0; this.path = event.getPath(); this.context = null; this.stat = null; this.data = null; this.name = null; this.children = null; this.aclList = null; this.watchedEvent = new RpcWatchedEvent(RpcKeeperState.valueOf(event.getState().name()), RpcEventType.valueOf(event.getType().name()), event.getPath()); this.leaderEvent = null; this.childrenCacheEvent = null; } public RpcCuratorEvent(LeaderEvent event) { this.type = RpcCuratorEventType.LEADER; this.resultCode = 0; this.path = event.path; this.context = null; this.stat = null; this.data = null; this.name = null; this.children = null; this.aclList = null; this.watchedEvent = null; this.leaderEvent = event; this.childrenCacheEvent = null; } public static RpcStat toRpcStat(Stat stat) { if ( stat != null ) { return new RpcStat(stat); } return null; } private List toRpcAclList(List aclList) { if ( aclList != null ) { return Lists.transform ( aclList, new Function() { @Nullable @Override public RpcAcl apply(ACL acl) { RpcId id = new RpcId(acl.getId().getScheme(), acl.getId().getId()); return new RpcAcl(acl.getPerms(), id); } } ); } return null; } private RpcWatchedEvent toRpcWatchedEvent(WatchedEvent watchedEvent) { if ( watchedEvent != null ) { return new RpcWatchedEvent(watchedEvent); } return null; } } RpcCuratorEventType.java000066400000000000000000000024221245521677600367720ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftEnum; @ThriftEnum("CuratorEventType") public enum RpcCuratorEventType { PING, CREATE, DELETE, EXISTS, GET_DATA, SET_DATA, CHILDREN, SYNC, GET_ACL, SET_ACL, WATCHED, CLOSING, CONNECTION_CONNECTED, CONNECTION_SUSPENDED, CONNECTION_RECONNECTED, CONNECTION_LOST, CONNECTION_READ_ONLY, LEADER, PATH_CHILDREN_CACHE, NODE_CACHE } RpcEventType.java000066400000000000000000000020241245521677600354300ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftEnum; @ThriftEnum("EventType") public enum RpcEventType { None, NodeCreated, NodeDeleted, NodeDataChanged, NodeChildrenChanged } RpcId.java000066400000000000000000000023041245521677600340420ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct("Id") public class RpcId { @ThriftField(1) public String scheme; @ThriftField(2) public String id; public RpcId() { } public RpcId(String scheme, String id) { this.scheme = scheme; this.id = id; } } RpcKeeperState.java000066400000000000000000000021201245521677600357160ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftEnum; @ThriftEnum("KeeperState") public enum RpcKeeperState { Unknown, Disconnected, NoSyncConnected, SyncConnected, AuthFailed, ConnectedReadOnly, SaslAuthenticated, Expired } RpcParticipant.java000066400000000000000000000023621245521677600357700ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct("Participant") public class RpcParticipant { @ThriftField(1) public String id; @ThriftField(2) public boolean isLeader; public RpcParticipant() { } public RpcParticipant(String id, boolean isLeader) { this.id = id; this.isLeader = isLeader; } } RpcPathChildrenCacheEvent.java000066400000000000000000000034601245521677600400050ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent; @ThriftStruct("PathChildrenCacheEvent") public class RpcPathChildrenCacheEvent { @ThriftField(1) public String cachedPath; @ThriftField(2) public RpcPathChildrenCacheEventType type; @ThriftField(3) public RpcChildData data; public RpcPathChildrenCacheEvent() { } public RpcPathChildrenCacheEvent(String cachedPath, PathChildrenCacheEvent event) { this.cachedPath = cachedPath; type = RpcPathChildrenCacheEventType.valueOf(event.getType().name()); data = (event.getData() != null) ? new RpcChildData(event.getData()) : null; } public RpcPathChildrenCacheEvent(String cachedPath, RpcPathChildrenCacheEventType type, RpcChildData data) { this.cachedPath = cachedPath; this.type = type; this.data = data; } } RpcPathChildrenCacheEventType.java000066400000000000000000000021571245521677600406510ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftEnum; @ThriftEnum("PathChildrenCacheEventType") public enum RpcPathChildrenCacheEventType { CHILD_ADDED, CHILD_UPDATED, CHILD_REMOVED, CONNECTION_SUSPENDED, CONNECTION_RECONNECTED, CONNECTION_LOST, INITIALIZED } RpcPersistentEphemeralNodeMode.java000066400000000000000000000021041245521677600411020ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftEnum; @ThriftEnum("PersistentEphemeralNodeMode") public enum RpcPersistentEphemeralNodeMode { EPHEMERAL, EPHEMERAL_SEQUENTIAL, PROTECTED_EPHEMERAL, PROTECTED_EPHEMERAL_SEQUENTIAL } RpcStat.java000066400000000000000000000050361245521677600344260ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; import org.apache.zookeeper.data.Stat; @ThriftStruct("Stat") public class RpcStat { @ThriftField(1) public long czxid; @ThriftField(2) public long mzxid; @ThriftField(3) public long ctime; @ThriftField(4) public long mtime; @ThriftField(5) public int version; @ThriftField(6) public int cversion; @ThriftField(7) public int aversion; @ThriftField(8) public long ephemeralOwner; @ThriftField(9) public int dataLength; @ThriftField(10) public int numChildren; @ThriftField(11) public long pzxid; public RpcStat() { } public RpcStat(Stat stat) { czxid = stat.getCzxid(); mzxid = stat.getMzxid(); ctime = stat.getCtime(); mtime = stat.getMtime(); version = stat.getVersion(); cversion = stat.getCversion(); aversion = stat.getAversion(); ephemeralOwner = stat.getEphemeralOwner(); dataLength = stat.getDataLength(); numChildren = stat.getNumChildren(); pzxid = stat.getPzxid(); } public RpcStat(long czxid, long mzxid, long ctime, long mtime, int version, int cversion, int aversion, long ephemeralOwner, int dataLength, int numChildren, long pzxid) { this.czxid = czxid; this.mzxid = mzxid; this.ctime = ctime; this.mtime = mtime; this.version = version; this.cversion = cversion; this.aversion = aversion; this.ephemeralOwner = ephemeralOwner; this.dataLength = dataLength; this.numChildren = numChildren; this.pzxid = pzxid; } } RpcWatchedEvent.java000066400000000000000000000032671245521677600361000ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; import org.apache.zookeeper.WatchedEvent; @ThriftStruct("WatchedEvent") public class RpcWatchedEvent { @ThriftField(1) public RpcKeeperState keeperState; @ThriftField(2) public RpcEventType eventType; @ThriftField(3) public String path; public RpcWatchedEvent() { } public RpcWatchedEvent(WatchedEvent watchedEvent) { keeperState = RpcKeeperState.valueOf(watchedEvent.getState().name()); eventType = RpcEventType.valueOf(watchedEvent.getType().name()); path = watchedEvent.getPath(); } public RpcWatchedEvent(RpcKeeperState keeperState, RpcEventType eventType, String path) { this.keeperState = keeperState; this.eventType = eventType; this.path = path; } } SetDataSpec.java000066400000000000000000000031661245521677600352100ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class SetDataSpec { @ThriftField(1) public String path; @ThriftField(2) public boolean watched; @ThriftField(3) public String asyncContext; @ThriftField(4) public boolean compressed; @ThriftField(5) public Version version; @ThriftField(6) public byte[] data; public SetDataSpec() { } public SetDataSpec(String path, boolean watched, String asyncContext, boolean compressed, Version version, byte[] data) { this.path = path; this.watched = watched; this.asyncContext = asyncContext; this.compressed = compressed; this.version = version; this.data = data; } } Version.java000066400000000000000000000021661245521677600344740ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/java/org/apache/curator/x/rpc/idl/structs/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc.idl.structs; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; @ThriftStruct public class Version { @ThriftField(1) public int version; public Version() { } public Version(int version) { this.version = version; } } curator-apache-curator-2.7.1/curator-x-rpc/src/main/resources/000077500000000000000000000000001245521677600243465ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/resources/curator/000077500000000000000000000000001245521677600260255ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/resources/curator/help.txt000066400000000000000000000061721245521677600275240ustar00rootroot00000000000000Curator RPC - an RPC server for using Apache Curator APIs and recipes from non JVM languages. Arguments: show this help either a path to a JSON or YAML configuration file or a JSON/YAML object for configuration Curator RPC uses Dropwizard for configuration. The format is JSON or YAML (your choice). Here is the model configuration shown in JSON with added comments. Required fields have "*" in the comment. { "thrift": { // * Thrift server configuration "bindAddress": "string", // address to bind to. Default is "localhost" "port": int, // * port to listen on "acceptBacklog": int, // default is 1024 "connectionLimit": int, // max concurrent connections. Default is unlimited. "acceptorThreadCount": int, // default is 1 "ioThreadCount": int, // default is 2 * number of processors "idleConnectionTimeout": "Duration", // default is 60 seconds "transportName": "string", // default is "framed" "protocolName": "string" // default is "binary" }, "projectionExpiration": "Duration", // time for projections to expire if unused. Default is 3 // minutes. "pingTime": "Duration", // time that the EventService will return PING if no other events. // Default is 5 seconds. "connections": [ // * list of ZooKeeper connections "name": "string", // * unique name for the connection "connectionString": "string", // * ZooKeeper connection string (e.g. "host1:2181,host2:2181") "sessionLength": "Duration", // duration for the session. Default is 1 minute. "connectionTimeout": "Duration", // duration for connecting. Default is 15 seconds. "authorization": { // Authorization spec. Default is NULL. "scheme": "string", // * the authorization scheme "auth": "string" // * the authorization auth }, "namespace": "string", // Curator namespace. Default is NULL. "retry": { // Retry policy. Default is an exponential-backoff policy. "type": "string", // Policy type. Either "exponential-backoff", // "bounded-exponential-backoff" or "ntimes" -- Remaining values depending on type. See below -- }, ], "logging": { // logging config - Dropwizard's logging library is used See http://dropwizard.readthedocs.org/en/latest/manual/configuration.html#logging } } "Duration" is a string. E.g. "1s" (1 second), "10m" (10 minutes) Retry Policy Specs: For type: "exponential-backoff" { "baseSleepTime": "Duration", // default is 100 milliseconds "maxRetries": int // default is 3 } For type: "bounded-exponential-backoff" { "baseSleepTime": "Duration", // default is 100 milliseconds "maxSleepTime": "Duration", // default is 30 seconds "maxRetries": int // default is 3 } For type: "ntimes" { "sleepBetweenRetries": "Duration", // default is 100 milliseconds "n": int // default is 3 } curator-apache-curator-2.7.1/curator-x-rpc/src/main/scripts/000077500000000000000000000000001245521677600240235ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/scripts/apply-thrift.sh000077500000000000000000000023071245521677600270070ustar00rootroot00000000000000#!/bin/bash # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # if (( $# == 0 )); then echo -e "usage:\n\tapply-thrift.sh " exit fi DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" BASE_DIR="$( cd "$DIR/../../../.." && pwd )" if (( $# == 2 )); then TARGET_DIR="$2" else TARGET_DIR="$BASE_DIR/curator-x-rpc/src/test/java" fi thrift -gen $1 -out "$TARGET_DIR" "$BASE_DIR/curator-x-rpc/src/main/thrift/curator.thrift" curator-apache-curator-2.7.1/curator-x-rpc/src/main/scripts/generate.sh000077500000000000000000000037451245521677600261650ustar00rootroot00000000000000#!/bin/bash # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # if (( $# != 2 )); then echo -e "usage:\n\tgenerate.sh " exit fi DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" BASE_DIR="$( cd "$DIR/../../../.." && pwd )" RPC_PATH="$BASE_DIR/curator-x-rpc/target/classes" CLASSES="" for p in services structs exceptions discovery; do for f in `ls -m1 $RPC_PATH/org/apache/curator/x/rpc/idl/$p/*.class | xargs -n 1 basename | sed s/\.[^\.]*$//`; do if [[ $f != *[\$]* ]]; then CLASSES="$CLASSES org.apache.curator.x.rpc.idl.$p.$f"; fi; done; done; THRIFT_DIR="$BASE_DIR/curator-x-rpc/src/main/thrift" PATHS="$1:$2" PATHS="$PATHS:$BASE_DIR/curator-client/target/classes" PATHS="$PATHS:$BASE_DIR/curator-framework/target/classes" PATHS="$PATHS:$BASE_DIR/curator-recipes/target/classes" PATHS="$PATHS:$BASE_DIR/curator-x-discovery/target/classes" PATHS="$PATHS:$RPC_PATH" java -cp $PATHS com.facebook.swift.generator.swift2thrift.Main \ -allow_multiple_packages org.apache.curator \ -namespace cpp org.apache.curator.generated \ -namespace java org.apache.curator.generated \ -out "$THRIFT_DIR/curator.thrift" \ $CLASSES curator-apache-curator-2.7.1/curator-x-rpc/src/main/thrift/000077500000000000000000000000001245521677600236345ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/main/thrift/curator.thrift000066400000000000000000000232411245521677600265370ustar00rootroot00000000000000namespace java.swift org.apache.curator namespace cpp org.apache.curator.generated namespace java org.apache.curator.generated enum PathChildrenCacheStartMode { NORMAL, BUILD_INITIAL_CACHE, POST_INITIALIZED_EVENT } enum CreateMode { PERSISTENT, PERSISTENT_SEQUENTIAL, EPHEMERAL, EPHEMERAL_SEQUENTIAL } enum CuratorEventType { PING, CREATE, DELETE, EXISTS, GET_DATA, SET_DATA, CHILDREN, SYNC, GET_ACL, SET_ACL, WATCHED, CLOSING, CONNECTION_CONNECTED, CONNECTION_SUSPENDED, CONNECTION_RECONNECTED, CONNECTION_LOST, CONNECTION_READ_ONLY, LEADER, PATH_CHILDREN_CACHE, NODE_CACHE } enum EventType { None, NodeCreated, NodeDeleted, NodeDataChanged, NodeChildrenChanged } enum KeeperState { Unknown, Disconnected, NoSyncConnected, SyncConnected, AuthFailed, ConnectedReadOnly, SaslAuthenticated, Expired } enum PathChildrenCacheEventType { CHILD_ADDED, CHILD_UPDATED, CHILD_REMOVED, CONNECTION_SUSPENDED, CONNECTION_RECONNECTED, CONNECTION_LOST, INITIALIZED } enum PersistentEphemeralNodeMode { EPHEMERAL, EPHEMERAL_SEQUENTIAL, PROTECTED_EPHEMERAL, PROTECTED_EPHEMERAL_SEQUENTIAL } enum ExceptionType { GENERAL, ZOOKEEPER, NODE } enum NodeExceptionType { NONODE, BADVERSION, NODEEXISTS, NOTEMPTY } enum ZooKeeperExceptionType { SYSTEMERROR, RUNTIMEINCONSISTENCY, DATAINCONSISTENCY, CONNECTIONLOSS, MARSHALLINGERROR, UNIMPLEMENTED, OPERATIONTIMEOUT, BADARGUMENTS, APIERROR, NOAUTH, NOCHILDRENFOREPHEMERALS, INVALIDACL, AUTHFAILED, SESSIONEXPIRED, INVALIDCALLBACK, SESSIONMOVED, NOTREADONLY } enum DiscoveryInstanceType { DYNAMIC, STATIC, PERMANENT } enum ProviderStrategyType { RANDOM, STICKY_RANDOM, STICKY_ROUND_ROBIN, ROUND_ROBIN } struct CuratorProjection { 1: string id; } struct ExistsSpec { 1: string path; 2: bool watched; 3: string asyncContext; } struct GetChildrenSpec { 1: string path; 2: bool watched; 3: string asyncContext; } struct GetDataSpec { 1: string path; 2: bool watched; 3: string asyncContext; 4: bool decompressed; } struct LeaderEvent { 1: string path; 2: string participantId; 3: bool isLeader; } struct LeaderProjection { 1: string id; } struct LeaderResult { 1: LeaderProjection projection; 2: bool isLeader; } struct LeaseProjection { 1: string id; } struct LockProjection { 1: string id; } struct NodeCacheProjection { 1: string id; } struct OptionalChildrenList { 1: list children; } struct OptionalData { 1: binary data; } struct OptionalLockProjection { 1: LockProjection lockProjection; } struct OptionalPath { 1: string path; } struct PathChildrenCacheProjection { 1: string id; } struct PersistentEphemeralNodeProjection { 1: string id; } struct Id { 1: string scheme; 2: string id; } struct Participant { 1: string id; 2: bool isLeader; } struct Stat { 1: i64 czxid; 2: i64 mzxid; 3: i64 ctime; 4: i64 mtime; 5: i32 version; 6: i32 cversion; 7: i32 aversion; 8: i64 ephemeralOwner; 9: i32 dataLength; 10: i32 numChildren; 11: i64 pzxid; } struct WatchedEvent { 1: KeeperState keeperState; 2: EventType eventType; 3: string path; } struct Version { 1: i32 version; } struct DiscoveryProjection { 1: string id; } struct DiscoveryProviderProjection { 1: string id; } struct CreateSpec { 1: string path; 2: binary data; 3: CreateMode mode; 4: string asyncContext; 5: bool compressed; 6: bool creatingParentsIfNeeded; 7: bool withProtection; } struct DeleteSpec { 1: string path; 2: bool guaranteed; 3: string asyncContext; 4: Version version; } struct OptionalStat { 1: Stat stat; } struct Acl { 1: i32 perms; 2: Id id; } struct ChildData { 1: string path; 2: Stat stat; 3: binary data; } struct PathChildrenCacheEvent { 1: string cachedPath; 2: PathChildrenCacheEventType type; 3: ChildData data; } struct SetDataSpec { 1: string path; 2: bool watched; 3: string asyncContext; 4: bool compressed; 5: Version version; 6: binary data; } exception CuratorException { 1: ExceptionType type; 2: ZooKeeperExceptionType zooKeeperException; 3: NodeExceptionType nodeException; 4: string message; } struct DiscoveryInstance { 1: string name; 2: string id; 3: string address; 4: i32 port; 5: i32 sslPort; 6: binary payload; 7: i64 registrationTimeUTC; 8: DiscoveryInstanceType serviceType; 9: string uriSpec; } struct CuratorEvent { 2: CuratorEventType type; 3: i32 resultCode; 4: string path; 5: string context; 6: Stat stat; 7: binary data; 8: string name; 9: list children; 10: list aclList; 11: WatchedEvent watchedEvent; 12: LeaderEvent leaderEvent; 13: PathChildrenCacheEvent childrenCacheEvent; } service CuratorService { OptionalLockProjection acquireLock(1: CuratorProjection projection, 2: string path, 3: i32 maxWaitMs) throws (1: CuratorException ex1); list acquireSemaphore(1: CuratorProjection projection, 2: string path, 3: i32 acquireQty, 4: i32 maxWaitMs, 5: i32 maxLeases) throws (1: CuratorException ex1); void closeCuratorProjection(1: CuratorProjection projection); bool closeGenericProjection(1: CuratorProjection projection, 2: string id) throws (1: CuratorException ex1); OptionalPath createNode(1: CuratorProjection projection, 2: CreateSpec spec) throws (1: CuratorException ex1); void deleteNode(1: CuratorProjection projection, 2: DeleteSpec spec) throws (1: CuratorException ex1); OptionalStat exists(1: CuratorProjection projection, 2: ExistsSpec spec) throws (1: CuratorException ex1); OptionalChildrenList getChildren(1: CuratorProjection projection, 2: GetChildrenSpec spec) throws (1: CuratorException ex1); OptionalData getData(1: CuratorProjection projection, 2: GetDataSpec spec) throws (1: CuratorException ex1); list getLeaderParticipants(1: CuratorProjection projection, 2: LeaderProjection leaderProjection) throws (1: CuratorException ex1); ChildData getNodeCacheData(1: CuratorProjection projection, 2: NodeCacheProjection cacheProjection) throws (1: CuratorException ex1); list getPathChildrenCacheData(1: CuratorProjection projection, 2: PathChildrenCacheProjection cacheProjection) throws (1: CuratorException ex1); ChildData getPathChildrenCacheDataForPath(1: CuratorProjection projection, 2: PathChildrenCacheProjection cacheProjection, 3: string path) throws (1: CuratorException ex1); bool isLeader(1: CuratorProjection projection, 2: LeaderProjection leaderProjection) throws (1: CuratorException ex1); CuratorProjection newCuratorProjection(1: string connectionName) throws (1: CuratorException ex1); oneway void pingCuratorProjection(1: CuratorProjection projection); OptionalStat setData(1: CuratorProjection projection, 2: SetDataSpec spec) throws (1: CuratorException ex1); LeaderResult startLeaderSelector(1: CuratorProjection projection, 2: string path, 3: string participantId, 4: i32 waitForLeadershipMs) throws (1: CuratorException ex1); NodeCacheProjection startNodeCache(1: CuratorProjection projection, 2: string path, 3: bool dataIsCompressed, 4: bool buildInitial) throws (1: CuratorException ex1); PathChildrenCacheProjection startPathChildrenCache(1: CuratorProjection projection, 2: string path, 3: bool cacheData, 4: bool dataIsCompressed, 5: PathChildrenCacheStartMode startMode) throws (1: CuratorException ex1); PersistentEphemeralNodeProjection startPersistentEphemeralNode(1: CuratorProjection projection, 2: string path, 3: binary data, 4: PersistentEphemeralNodeMode mode) throws (1: CuratorException ex1); void sync(1: CuratorProjection projection, 2: string path, 3: string asyncContext) throws (1: CuratorException ex1); } service EventService { CuratorEvent getNextEvent(1: CuratorProjection projection) throws (1: CuratorException ex1); } service DiscoveryService { list getAllInstances(1: CuratorProjection projection, 2: DiscoveryProviderProjection providerProjection) throws (1: CuratorException ex1); DiscoveryInstance getInstance(1: CuratorProjection projection, 2: DiscoveryProviderProjection providerProjection) throws (1: CuratorException ex1); DiscoveryInstance makeDiscoveryInstance(1: string name, 2: binary payload, 3: i32 port) throws (1: CuratorException ex1); void noteError(1: CuratorProjection projection, 2: DiscoveryProviderProjection providerProjection, 3: string instanceId) throws (1: CuratorException ex1); DiscoveryProjection startDiscovery(1: CuratorProjection projection, 2: string basePath, 3: DiscoveryInstance yourInstance) throws (1: CuratorException ex1); DiscoveryProviderProjection startProvider(1: CuratorProjection projection, 2: DiscoveryProjection discoveryProjection, 3: string serviceName, 4: ProviderStrategyType providerStrategy, 5: i32 downTimeoutMs, 6: i32 downErrorThreshold) throws (1: CuratorException ex1); } service DiscoveryServiceLowLevel { DiscoveryInstance queryForInstance(1: CuratorProjection projection, 2: DiscoveryProjection discoveryProjection, 3: string name, 4: string id) throws (1: CuratorException ex1); list queryForInstances(1: CuratorProjection projection, 2: DiscoveryProjection discoveryProjection, 3: string name) throws (1: CuratorException ex1); list queryForNames(1: CuratorProjection projection, 2: DiscoveryProjection discoveryProjection) throws (1: CuratorException ex1); void registerInstance(1: CuratorProjection projection, 2: DiscoveryProjection discoveryProjection, 3: DiscoveryInstance instance) throws (1: CuratorException ex1); void unregisterInstance(1: CuratorProjection projection, 2: DiscoveryProjection discoveryProjection, 3: DiscoveryInstance instance) throws (1: CuratorException ex1); void updateInstance(1: CuratorProjection projection, 2: DiscoveryProjection discoveryProjection, 3: DiscoveryInstance instance) throws (1: CuratorException ex1); } curator-apache-curator-2.7.1/curator-x-rpc/src/site/000077500000000000000000000000001245521677600223545ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/site/confluence/000077500000000000000000000000001245521677600244755ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/site/confluence/configuration.confluence000066400000000000000000000112151245521677600314070ustar00rootroot00000000000000[[Curator RPC Proxy|index.html]] / Configuration h1. Configuration h2. Introduction Curator RPC uses [[Dropwizard|http://dropwizard.readthedocs.org/en/latest/]] for configuration. You can write the configuration in JSON or YAML. It can be passed to Curator RPC via a file or directly on the command line. i.e. {noformat} # via command line java -jar curator-x-rpc-VERSION.jar '{"thrift":{"port": 8080}}' {noformat} {noformat} # via file java -jar curator-x-rpc-VERSION.jar path/to/config.json {noformat} h2. Example Here is an example JSON configuration file {noformat} { "projectionExpiration": "15s", "thrift": { "port": 1234 }, "pingTime": "10s", "logging": { "level": "INFO", "appenders": [ { "type": "file", "currentLogFilename": "logs/curator-rpc.log", "archivedLogFilenamePattern": "logs/curator-rpc-%d.log.gz", "archivedFileCount": 10, "timeZone": "UTC" }, { "type": "console" } ] }, "connections": [ { "name": "main", "connectionString": "one:1,two:2", "sessionLength": "3m", "connectionTimeout": "20s", "retry": { "type": "exponential-backoff", "baseSleepTime": "1s", "maxRetries": 10 } }, { "name": "alt", "connectionString": "three:3,four:4", "sessionLength": "4m", "connectionTimeout": "30s", "retry": { "type": "ntimes", "sleepBetweenRetries": "1m", "n": 10 } } ] } {noformat} h2. Main ||Name||Type||Default Value||Description|| |thrift|Thrift|n/a|Thrift server configuration| |logging|Logging|n/a|log file configuration| |projectionExpiration|Duration|3 minutes|Curator Projection instances will be automatically closed if not accessed within this amount of time| |pingTime|Duration|5 seconds|The EventService will return a PING event if this time elapses without some other event being generated| |connections|List of Connection|n/a|List of ZooKeeper connections| h2. Duration Durations are strings that specify a time duration. Examples: * "10s" \- 10 seconds * "100ms" \- 100 milliseconds * "3h" \- 3 hours h2. Thrift ||Name||Type||Default Value||Required||Description|| |port|int|_none_|*Y*|port to listen on.| |bindAddress|string|"localhost"|\-|Address for server to bind to| |idleConnectionTimeout|int|60 seconds|\-|timeout period between receiving requests from a client connection. If the timeout is exceeded (no complete requests have arrived from the client within the timeout), the server will disconnect the idle client.| |transportName|string|"framed"|\-|the name of the transport (frame codec) that this server will handle. The available options by default are 'unframed', 'buffered', and 'framed'. Additional modules may install other options.| |protocolName|string|"binary"|\-|name of the protocol that this server will speak. The available options by default are 'binary' and 'compact'. Additional modules may install other options.| h2. Logging Dropwizard's logging module is used. See the [[Dropwizard Logging Doc|http://dropwizard.readthedocs.org/en/latest/manual/configuration.html#logging]] for details on specifying the logging configuration. h2. Connection ||Name||Type||Default Value||Required||Description|| |name|string|_none_|*Y*|Unique name for the connection.| |connectionString|string|_none_|*Y*|ZooKeeper connection string (e.g. "host1:2181,host2:2181").| |sessionLength|Duration|1 minute|\-|duration for the ZooKeeper session| |connectionTimeout|Duration|15 seconds|\-|duration for connecting| |retry|Retry|an exponential\-backoff policy|\-|The Retry Policy to use| |authorization|Authorization|null|\-|Authorization spec| h2. Retry The retry policy configuration depends on what type is used. There are three types supported: ||Name||Type||Default Value||Description|| |type|string|n/a|*exponential\-backoff*| |baseSleepTime|Duration|100 milliseconds|The base sleep time| |maxRetries|int|3|The max retries| |\_|\_|\_|\_| |type|string|n/a|*bounded\-exponential\-backoff*| |baseSleepTime|Duration|100 milliseconds|The base sleep time| |maxSleepTime|Duration|30 seconds|The max sleep time| |maxRetries|int|3|The max retries| |\_|\_|\_|\_| |type|string|n/a|*ntimes*| |sleepBetweenRetries|int|100 milliseconds|sleep time between retries| |n|int|3|the number of retries| h2. Authorization ||Name||Type||Description|| |scheme|string|the authorization scheme| |auth|string|the authorization auth| curator-apache-curator-2.7.1/curator-x-rpc/src/site/confluence/deploy.confluence000066400000000000000000000026431245521677600300410ustar00rootroot00000000000000[[Curator RPC Proxy|index.html]] / Deployment h1. Deployment h2. Running Curator RPC is built as an "uber" Java JAR and can be downloaded from Maven Central. Go to [[http://search.maven.org/|http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.apache.curator%22%20AND%20a%3A%22curator-x-rpc%22]] and search for "curator\-x\-rpc" and download the JAR for the latest version. This JAR can be run directly ala: {noformat} java -jar curator-x-rpc-VERSION.jar {noformat} The argument is either a configuration file or a JSON or YAML string. Call without the argument for help text. See [[Configuration|configuration.html]] for details. h2. Deploying Curator RPC is designed to have an instance of its Thrift Server co\-located on each client instance that needs to connect to ZooKeeper (see the figure below). Each Curator RPC instance is configured (see [[Configuration|configuration.html]]) to connect to one or more ZooKeeper clusters. The Curator Framework instances are maintained inside of the Curator RPC instances and RPC clients reference these instances by name. How you configure your server to launch depends on your environment and other needs. Here are some suggestions: * [Airlift Launcher|https://github.com/airlift/airlift/tree/master/launcher] * [Docker|https://www.docker.io/] * [One-JAR|http://one-jar.sourceforge.net/] * [Capsule|https://github.com/puniverse/capsule] h2. Topology !images/topology.png! curator-apache-curator-2.7.1/curator-x-rpc/src/site/confluence/events.confluence000066400000000000000000000065171245521677600300550ustar00rootroot00000000000000[[Curator RPC Proxy|index.html]] / Events h1. Events h2. Event Loop In order to receive out\-of\-bounds messages (connection state changes, watcher triggers, etc.) you must have an event loop to recieve messages from the EventService. Here is pseudo code: {code} inThread => { while isOpen { event = eventService.getNextEvent(curatorProjection) ... process event ... } } {code} *IMPORTANT:* your event handling should operate as quickly as possible. You should return to calling getNextEvent() as soon as possible. h2. Schema h3. CuratorEvent ||Field||Type||Description|| |type|CuratorEventType|The event type| |resultCode|int|some event types have a result code (i.e. async API calls)| |path|string|if there is a path associated with the event| |context|string|async context for async API calls| |stat|Stat|some event types have a ZooKeeper Stat object| |data|bytes|ZNode data if the event type has it| |name|string|ZNode name if the event type has it| |children|list of string|list of node names if the event type has it| |aclList|list of Acl|list of ACL data if the event type has it| |watchedEvent|WatchedEvent|if the event type is WATCHED| |leaderEvent|LeaderEvent|if the event type is LEADER| |childrenCacheEvent|PathChildrenCacheEvent|if the event type is PATH\_CHILDREN\_CACHE| h3. CuratorEventType ||Value||Description|| |PING|Returned if no events have been generated within the [[configured|configuration.html]] pingTime| |CREATE|Async createNode() API completion| |DELETE|Async deleteNode() API completion| |EXISTS|Async exists() API completion| |GET\_DATA|Async getData() API completion| |SET\_DATA|Async setData() API completion| |CHILDREN|Async getChildren() API completion| |SYNC|Async sync() API completion| |WATCHED|A watcher has triggered| |CONNECTION\_CONNECTED|A Curator ConnectionStateListener is installed. This event is for the initial successful connection.| |CONNECTION\_SUSPENDED|A Curator ConnectionStateListener is installed. This event means the connection has been suspended.| |CONNECTION\_RECONNECTED|A Curator ConnectionStateListener is installed. This event means the connection has been reconnected.| |CONNECTION\_LOST|A Curator ConnectionStateListener is installed. This event means the connection has been lost.| |CONNECTION\_READ\_ONLY|A Curator ConnectionStateListener is installed. This event means the connection has changed to read only.| |LEADER|A Leader recipe event| |PATH\_CHILDREN\_CACHE|A path children cache event| |NODE\_CACHE|The node for a node cache has changed| h3. LeaderEvent ||Field||Type||Description|| |path|string|The leader's path| |participantId|string|The participant ID for the event being reported| |isLeader|bool|if true, this participant is being made leader. If false, it is losing leadership.| h3. PathChildrenCacheEvent ||Field||Type||Description|| |cachedPath|name|The path being cached| |type|PathChildrenCacheEventType|cache event type| |data|ChildData|data for the child ZNode| h3. PathChildrenCacheEventType Values: CHILD\_ADDED, CHILD\_UPDATED, CHILD\_REMOVED, CONNECTION\_SUSPENDED, CONNECTION\_RECONNECTED, CONNECTION\_LOST, INITIALIZED h3. ChildData ||Field||Type||Description|| |path|string|The ZNode path| |stat|Stat|ZooKeeper Stat object| |data|bytes|ZNode data (if the cache is configured to cache data)| curator-apache-curator-2.7.1/curator-x-rpc/src/site/confluence/index.confluence000066400000000000000000000033751245521677600276570ustar00rootroot00000000000000h1. Curator RPC Proxy h2. Packaging Curator RPC Proxy is in its own package in Maven Central: curator\-x\-rpc h2. What Is a Curator RPC? The Curator RPC module implements a proxy that bridges non\-java environments with the Curator framework and recipes. It uses [[Apache Thrift|http://thrift.apache.org]] which supports a large set of languages and environments. The benefits of Curator RPC are: * Gives access to Curator to non JVM languages/environments ** Curator has become the de\-facto JVM client library for ZooKeeper ** Curator makes using Apache ZooKeeper much easier ** Curator contains well\-tested recipes for many common ZooKeeper usages * Organizations can unify their ZooKeeper usage across languages/environments (i.e. use Curator's Service Discovery recipe) * The quality of ZooKeeper clients for some non\-JVM languages is lacking * There are Thrift implementations for a large number of languages/environments h2. Thrift File The current Curator RPC Thrift File can be found here: [[https://raw.githubusercontent.com/apache/curator/master/curator-x-rpc/src/main/thrift/curator.thrift]]. Use this to generate code for the language/environment you need. h2. Deployment See the [[Deployment Page|deploy.html]] for details on deploying the RPC proxy. h2. Usage See the [[Usage Page|usage.html]] for details on using the RPC proxy. h2. Configuration See [[Configuration|configuration.html]] for details on configuring the RPC proxy. h2. Events See [[Events|events.html]] for details on the Curator RPC event loop and its structure. h2. Reference See [[API Reference Page|reference.html]] for the API reference. ---- Special thanks to the [[Facebook Swift|https://github.com/facebook/swift/]] project which makes writing a Java Thrift server much easier. curator-apache-curator-2.7.1/curator-x-rpc/src/site/confluence/reference.confluence000066400000000000000000000161371245521677600305060ustar00rootroot00000000000000[[Curator RPC Proxy|index.html]] / Reference h1. API Reference h2. CuratorService ||API||Arguments||Return Value||Description|| |newCuratorProjection|connectionName|CuratorProjection|Allocates a projection to a configured CuratorFramework instance in the RPC server. "connectionName" is the name of a [[configured|configuration.html]] connection.| |closeCuratorProjection|CuratorProjection|void|Close a CuratorProjection. Also closes any recipes, etc. created for the projection.| |pingCuratorProjection|CuratorProjection|void|Keeps the CuratorProjection from timing out. NOTE: your [[EventService|events.html]] event loop will do this for you.| |createNode|CreateSpec|Created path name|Create a ZNode| |deleteNode|DeleteSpec|void|Delete a ZNode| |getData|GetDataSpec|bytes|Return a ZNode's data| |setData|SetDataSpec|Stat|Set a ZNode's data| |exists|ExistsSpec|Stat|Check if a ZNode exists| |getChildren|GetChildrenSpec|List of nodes|Get the child nodes for a ZNode| |sync|path and async context|void|Do a ZooKeeper sync| |closeGenericProjection|id|void|Closes any projection. All projections have an "id" field. This is the value to pass.| |acquireLock|path, maxWaitMs|optional lock projection|Acquire a lock for the given path. Will wait at most maxWaitMs to acquire the lock. If the acquisition fails, result will be null.| |startLeaderSelector|path, participantId, waitForLeadershipMs|LeaderResult|Start a leader selector on the given path. The instance will be assigned the specified participantId. If waitForLeadershipMs is non\-zero, the method will block for that amount of time waiting for leadership.| |getLeaderParticipants|leaderProjection|List of Participant|Return the participants in a leader selector| |isLeader|leaderProjection|bool|Return true if the specified projection is the current leader| |startPathChildrenCache|path, cacheData, dataIsCompressed, startMode|cache projection|Start a PathChildrenCache for the given path. Can optionally cache data, use compressed data.| |getPathChildrenCacheData|cacheProjection|List of ChildData|Get all the data for a path cache| |getPathChildrenCacheDataForPath|cacheProjection, path|ChildData|Get the data for a single ZNode in a path cache| |startNodeCache|path, dataIsCompressed, buildInitial|node cache projection|Start a node cache for the given path. Can optionally use compressed data and build the initial cache.| |getNodeCacheData|node cache projection|ChildData|Return the data for the cached node. If the node doesn't exist, the fields of the ChildData object will be null.| |startPersistentEphemeralNode|path, data, mode|projection|Start a PersistentEphemeralNode for the given path using the given data and mode.| |acquireSemaphore|path, acquireQty, maxWaitMs, maxLeases|List of lease projections|Acquire one or more leases for a semaphore on the given path. acquireQty is the number of leases to acquire. maxWaitMs is the max time to wait to get the leases. maxLeases is the maximum leases to allow for the semaphore. If the number of leases cannot be acquired within the max time, an empty list is returned.| h2. EventService ||API||Arguments||Return Value||Description|| |getNextEvent|CuratorProjection|CuratorEvent|Returns the next queued event for the given CuratorProjection. If no events are queued within the [[configured|configuration.html]] ping time, a PING event is returned.| See the [[Events Page|events.html]] for the CuratorEvent schema reference. h2. DiscoveryService ||API||Arguments||Return Value||Description|| |makeDiscoveryInstance|name, payload, port|DiscoveryInstance|Return a completed DiscoveryInstance using the RPC server's address and the given name, payload and port.| |startDiscovery|basePath, yourInstance|discovery projection|Start a Service Discovery instance on the given path. If yourInstance is not null it will be registered as the local service.| |startProvider|discoveryProjection, serviceName, providerStrategy, downTimeoutMs, downErrorThreshold|provider projection|start a Service Discovery Provider to return instances for the given service name using the given provider strategy. Specify "down" instance characteristics with downTimeoutMs and downErrorThreshold.| |getInstance|provider projection|DiscoveryInstance|Return a single instance for the given service| |getAllInstances|provider projection|list of DiscoveryInstance|Return all instances for the given service| |noteError|provider projection, service id|void|Note an error for the given service instance| h1. Struct Reference h2. CreateSpec ||Field||Type||Required||Description|| |path|string|*Y*|the ZNode path| |data|bytes|\-|data for the node| |mode|CreateMode|\-|PERSISTENT, PERSISTENT\_SEQUENTIAL, EPHEMERAL, or EPHEMERAL\_SEQUENTIAL| |asyncContext|string|\-|if not null, createNode() is performed asynchronously and this is the context used in the async message| |compressed|bool|\-|if true, compress the data| |creatingParentsIfNeeded|bool|\-|if true, create any needed parent nodes| |withProtection|bool|\-|if true, use Curator protection| h2. DeleteSpec ||Field||Type||Required||Description|| |path|string|*Y*|the ZNode path| |guaranteed|bool|\-|if true, use guaranteed deletion| |asyncContext|string|\-|if not null, createNode() is performed asynchronously and this is the context used in the async message| |compressed|bool|\-|if true, compress the data| |version|Version|\-|if not null, uses Version.version when deleting the node. Otherwise, \-1 is used.| h2. GetDataSpec ||Field||Type||Required||Description|| |path|string|*Y*|the ZNode path| |watched|bool|\-|if true, trigger watch events for this node| |asyncContext|string|\-|if not null, createNode() is performed asynchronously and this is the context used in the async message| |decompressed|bool|\-|if true, decompress the data| h2. SetDataSpec ||Field||Type||Required||Description|| |path|string|*Y*|the ZNode path| |data|bytes|*Y*|data for the node| |watched|bool|\-|if true, trigger watch events for this node| |asyncContext|string|\-|if not null, createNode() is performed asynchronously and this is the context used in the async message| |compressed|bool|\-|if true, compress the data| |version|Version|\-|if not null, uses Version.version when setting the node data. Otherwise, \-1 is used.| h2. ExistsSpec ||Field||Type||Required||Description|| |path|string|*Y*|the ZNode path| |watched|bool|\-|if true, trigger watch events for this node| |asyncContext|string|\-|if not null, createNode() is performed asynchronously and this is the context used in the async message| h2. GetChildrenSpec ||Field||Type||Required||Description|| |path|string|*Y*|the ZNode path| |watched|bool|\-|if true, trigger watch events for this node| |asyncContext|string|\-|if not null, createNode() is performed asynchronously and this is the context used in the async message| h2. LeaderResult ||Field||Type||Description|| |projection|LeaderProjection|the projection of the leader| |isLeader|bool|true if this projection is the leader| h2. Participant ||Field||Type||Description|| |id|string|participant id| |isLeader|bool|true if this participant is the leader| h2. ChildData ||Field||Type||Description|| |path|string|the ZNode path| |stat|Stat|ZooKeeper stat for the node| |data|bytes|node data or null| curator-apache-curator-2.7.1/curator-x-rpc/src/site/confluence/usage.confluence000066400000000000000000000101651245521677600276470ustar00rootroot00000000000000[[Curator RPC Proxy|index.html]] / Usage h1. Usage h2. Thrift File The first step in using the RPC Proxy is to process the Curator RPC Thrift file into your desired language/environment. The current Curator RPC Thrift File can be found here: [[https://raw.githubusercontent.com/apache/curator/master/curator-x-rpc/src/main/thrift/curator.thrift]]. Details on using Apache Thrift can be found here: [[http://thrift.apache.org]]. h2. Prerequisites It's assumed you are already familiar with ZooKeeper and Curator. Also, familiarity with writing Thrift applications is helpful. h2. Services Three Thrift Services are included with the Curator RPC: ||Service||Description|| |CuratorService|The main service for accessing the Curator APIs and recipes| |EventService|Used to receive out\-of\-band messages for callbacks, watchers, etc. See [Events|events.html] for details.| |DiscoveryService|Curator's ServiceDiscovery recipe| h2. Concepts h4. Projections Many of the Curator RPC APIs refer to "projections" (e.g. CuratorProjection). A projection is an id that refers to a real object instance inside of the RPC server. The projection is a "handle" or "cookie" that directly refers to that instance. h4. Thrift Client Equals a Thread It's important to remember that each thrift client is the equivalent of a system thread. i.e. you cannot have multiple outstanding calls in multiple threads with a given client. For each thread, you should allocate a separate client. A Thrift Client maps directly to a single TCP/IP socket. h4. Event Loop You must dedicate a separate thread for getting events via the Curator RPC [EventService|events.html]. Curator will report async results, connection state changes, watcher triggers, etc. via this event loop. h4. CuratorProjection Expiration If you don't make an API call using a CuratorProjection within the [configured timeout|configuration.html] the projection instance will be closed and any open recipes, etc. associated with it will be closed. NOTE: calls to the EventService will cause the CuratorProjection to be "touched". So, as long as your event loop is running your CuratorProjection instance will be kept open. h2. Initialization After setting up Thrift, create a connection to the CuratorService and the EventService. If you plan on using Curator Discovery, create a connection to DiscoveryService. Allocate a CuratorProjection instance and then start a thread watching events for that instance. Here is pseudo code: {code} CuratorService.Client curatorService = new CuratorService.Client() EventService.Client eventService = new EventService.Client() curatorProjection = curatorService.newCuratorProjection(name) inThread => { while isOpen { event = eventService.getNextEvent(curatorProjection) ... process event ... } } ... in your application shutdown client.closeCuratorProjection(curatorProjection) {code} h2. Usage Once initialized, use recipes/APIs as needed. Here is an example of using the lock recipe: {code} optionalLock = client.acquireLock(curatorProjection, "/mylock", 10000) if optionalLock.lockProjection == null { // lock attempt failed. Throw exception, etc. } lockProjection = optionalLock.lockProjection try // you now own the lock finally client.closeGenericProjection(curatorProjection, lockProjection.id) {code} Here is an example of using the path cache: {code} cacheProjection = client.startPathChildrenCache(curatorProjection, "/path", true, false, BUILD_INITIAL_CACHE) ... data = client.getPathChildrenCacheDataForPath(curatorProjection, cacheProjection, "/path/child") ... // in your event loop, you will get events for the cache. e.g. event = eventService.getNextEvent(curatorProjection) if event.type == PATH_CHILDREN_CACHE { if event.childrenCacheEvent.type == CHILD_UPDATED { // node described by event.childrenCacheEvent.data has changed // event.childrenCacheEvent.cachedPath is the path that was passed to startPathChildrenCache() } } ... // when done with the cache, close it client.closeGenericProjection(curatorProjection, cacheProjection.id) {code} h2. Reference See [[API Reference Page|reference.html]] for the API reference. curator-apache-curator-2.7.1/curator-x-rpc/src/site/resources/000077500000000000000000000000001245521677600243665ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/site/resources/images/000077500000000000000000000000001245521677600256335ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/site/resources/images/topology.png000066400000000000000000004105561245521677600302300ustar00rootroot00000000000000PNG  IHDR VL/iCCPICC Profile(c``2ptqre``+) rwRR` ``\\yy | 2 U +'300%@q9@HR6. r!+ v.z H}:b'A2 vIj^ʢ#ǔTbϼĒZ@! A!ahii "q(v!( cd2f` G1G)I/15C}}sïPo% pHYs  @IDATx} VUrgY!ͬ!,shY,5+55+,L3yBQQADQAAPy^ϳ^gfg{yb#iD@.{lr-Z@rYgzogrxd_V޻: t9mXhko}_3oقՙ}*I҈yҿ7Jr+_UeYa+F`}!ޗoju]WVTU-=zdfE<oǁЀ1<K_ƈChU'l(u(+Et]-M/Y_HNS,KI~+8dlKC Be~\)S+21L p>hQ5X ܚQB܁1^im/Nj։Wvɳ=Fr%# Xh1&ڵvAv@ ǶdQy/^Z,|nѽ[7mSV-kPQY)KUGeEP)j&ZC~,y'v)%2&B|RY ͪlJEzźʢf>yfҮd2Jja'JFg^0xm I `"`vLD)ceGU651xsbW2%I-u1 \e8nk)ݨe2eoVڠ-IL0/sCP7cG5O+*+rj|Ø4?ܹs)9 6@y"ފo_WЦu֭_Okd)5۠ͲU :a'jG݁a%e,T6;yl>x\ylczJ㊑]/i~2%I˦$jV-eNRvn3_.Ť)yJ>S%U&891p)nbT- #MfNFM)6,сTZtb[MHgT[ m E29RĤQӁ&eQwk,Nd2>v2L:p$&)bSS)!̤|sCt~`'Y+塛tᚪKT+ cvDgT~Ǜuo|_EeUy(oib4ަFE|w~O~8thWu֣LIpH$:_&=1X Tf.CLF3B0{f-%$fK.VIIJs'Q26HJ$s[V1qiYlf­,OU] +$)/VWzޮ'.w)o۰ YfkZM͏T6$SEAN"H{j: P1 SY53Fy6d ж~a9b(}3s+*kٵ6E+cX `*+bS'H('oOEߪ% a*I b8F Y7.646?mxFʵm͍'IoؽwIx]!fc}.uژ-STTDY2C`,0XSES])k$C~T,UOtiDL䇪L43RKIfT}*I7Lտbp,7彭1 i@֔X7Z*'~2[2McT\*jlFM)Ooiv[Bs\޼OdRBXw²,kny ddP<jg1   ْW" .֯oDߞpqvYpoDo&0b ]b%vy5yI>Oԕ=ԁR*Q E;Rot!+$pbpp_s[6`s"7%۬$9Rl"3fK$Tlгv8S7fJiAf2ci# W|%c+8@aS{rL|& Lh˖>RUQ/ʥX6@$l0fIWfnURR]q'm WQl 0i8mQ"6DA Iu䘹*$3&?$$+)XB׹cX[b$]yHP2{jְJ(tMN0m[.l'4XGëX'sEŲM2QϵҶ |uB8Qt P%kѹCGE,g10o jJi[]D $ N(lsc%%DlɎdl4o&ii绝TjNǪ^㨞'1%H>}tšOɆ"#f890a[ fsqO3;tI}Lly,CJJHɩqbl"*g-$)a=W93"]v3M/Wu9 7a+'Qt9y)=A% 53l{ռB |;D=ti4uX:-wR|@h($M7&(K*g8&Da*ά6 9:)!oԙ7 A1R#-Ĥm1|N){̼Ffd yތe%A#V.o]V_ y76>dupS$뢡 0x=iTq,Ts#$=cEj Tf, hIIExz*a DnZ`2#yIg #`R'+Ti ltI mA"n вo's?Y6\/&%_ԦrW&+ix90轖)*̄@QE76T z6'B>A -z WJI׵M:G.PI>8i6zCbY[P]iNNUr9%ј@jNK 95JyՑ:VKN:ɡ >x Kvn+v3t KmPM#fo\깸$IzRt "^K}# +V( vޘ@]sܸwM% Me&̻$d$Ƕ O] 2c~7%GOz*'VgyK|L _W͒ ACȶ-Q"fC'id5XL$ZR ZObn5=nRnLO m4f* !:}2WNiJABrNHkY?Ƚ+dWF <,E:&ԽuYUrb'hf>(cč($2*ɰ|\KUfaپRE}6gDMM b$T54 &LE oZ.h} ql0s}oK[ڈ`69:X&Ȓ]&`t|TrDe\S\ 旖֓! HXnNgX"SO;JSw?3tn&C-2t 'H N T9%#4Noo- EM ?e8d$&'$cZP201Cqaj+m7!+t ?a3խcii j qVO ?&ɛNc1#̬GUv%!;i 2%ͲӜj[,^etI~[HfQƇ~5QKo -c%>W%fieЎVT)}w I2 ^*d6[{%-ӂ?Ypz#{*ŬmxAu9ck}"t5hz;#'LV XnMAĐ´"QS.O K pY&T,JSR YrE -}pv)Gࢺ/ՇO2MIm⭒,!<@7? :b 0XdY'Z=2 ҆Gg&jn'noꞌ/^’!p ;64)I>SGmqKgݪrPD N 'X?XRAEHqd"#͊z—RQs0]:e}M*Dn}^)zS 1ZUb}zɊ$X5m2SM8I' a+ PC7 [ O e6"|#]a8}(9~\ $7rr3<-B# 2?IG“d\N*)EzVms\7a$I ;CJTo#u^ #JgΙG a&Q9aF| Z,T<c-pb^%VXɦ yIhMHcW[3t:MVg!:u8oJ !tpi۟FVŐ!.] gMX\y'ђUJ1ѣ$<N *!Z&OYIj,< ZbRL Kؘj aIvnu^z\BvF`%_RYry)NvL/VpYQµt T?F5JlU)}[E$*tl4c%gT/(~a3¿䗳s )m)򮖔Eq#i/ӗ,RHʴ,沒#CY.nrt{qtgH# `BBIjQ$%Zi%4wЂ $͚ސ3Lk {u,փԙLL?I'-YfukE%pH$}%`S"R`)M%ܕB1 Ljb 6 ߱THvϲXK|] %KyeV7alP|%/pv { yd匒ߘ)iJ 9褦}X2>ʡ,nY*Xuy2}/CHrR64!U#=7Uceݞ"sJ󇲦fOv!7Y48$" Tm=n,&P~r9<&Z* ҡ^j$,dQ%ESLf# 9n]@vL4IlaTNH&+)7nΔTXηuVx.Td<>O$}c3+%c$bnDi3Y2 ɂ~%hM-WW6YjчVK,KĒF04X2T$#?WS}Sa̐8f,kXԟ*pd|5ŗ-7Dɍ9> 6$ù"S=?(+P 3 کQ7 g_Σ>E=ba$j,$F^KMғ-S1X0 ]ƒsP̥D$j7O#d bQ5]6+Sa " u4XlMIu(&]%#,@y*+*QQɁRSF4qܸ ;6bm5klJucFUAuM5ףm6ĭBee%JTU.#~cS }LPSM̭"X;MP]./>!ڮҐe꒵XN0՘L`U'AWYDɡ G>c}mlb\xҥ˰_q_~񮩩Eu5ކqo׎6mBgmVհ in2Rh̼;msmP?{Jm&?'Y\Hm1}nc3!(%vy.<Δ"IL#g]ɎwOEe Kx,&Ƽ;㲱Qd42K-Cذ~cq5UUh] ۶5<:C4/Uj9qoӾ,za*"q x;M3MǏ-D5%{ 1hM)\c v&*Bl 1-|;tt F$fzZAf֮^oYs1kr,\oE:4ks@a_קy&. ͨ lkxѫ{v;vк-8(AP\5ޜͷ8RDyM(J܆`(J_)1NU5'J4[+Wqg4`;ƛ치`5l^ْf]64rSO;YI-k8)~Zzm*лgG#.]sa[U:o؈fN06)sp͚ƚ!>MY)]gB ]H& <%69T%)FP׺ vN#yNi1F;Yb"D_ک,9R13$6+4$?(S٬X򤧲 k9Λq1MRM A4HKd55`X0]<;99-v<}iۿlu 2RL[m(F ,`9X4o&[ݼߊ#-kC}бK'N Mb%tb y4ƪi2u4b 1-۪Z p^ޜ> >:d i :qs~hٺVTѕDQ}WxSg݋֪h-% fcѢyx{λm>|  F< 5nX,2Wbʝ胑3{M.%b&32zr=$]U+` xx~ xkkqxAwjKmm&-gqzjtnJ?]w+.] -c͟wOߏ/ZѣÐ!0l.ZsF@hI]#YƢ)NXlRP93ɢEԤ!Q|bgQe(I/IOqT{[_l>|^aͪL~i |5!ֹtd.i?{Z42wUW 񴱸xO WyL,Z0 -Ocq3F ݙ+V-"ۭB Lv|({dVq d-p96 M^z&V)MeOAU'wJi\w3aK99_{V?er4844뉹9*KgVL$JtDTQlSѮ^jvK؆'= r:;xg.7ki#W^F$!RJ6US]l4}[⮴bb&~8z <5rOTa0-ea&Ǡ4*ݟ3N J?tMAr.ۨ墎? +W,gńssCxۣ35CmQ;J[mX6n5o)Vz y̿4ev ^}F{SMI)Wm6IFqGoe SY1HKC1}]gG~D(nTl"4Ӳ>{^L6>T05$j/\>6<9쇽?=֊G q>aߐ8gfN[ /V{aذn-^<c8#Ӏ6Sńk)ճbr.p9lT˒M!) F&iU.yV<{|/톑rs յ+">t4-a:n僵9u%@fȐc'+l.xc 21H^ FWWl:\ͫƏm>i ;`^coV3K+=ϼ]w9,S079 ?%MGӆf32ޚ7 '}t}WIپR(ݛw(Đ-+,gGeW\+-DoM 1'.MiaujOTl]DNc{`x SKLup8FpA}ά^9Sq qs^^D T2j}UO Z2\Ϋ)?>ڞDB)V>X-k6Vpͧe@rH@E uŸn<3q j>[NNw6FQĤ`}wVGI!&MnaNg/+kúWW^:aԡNvyC,v9> -[n)S^9߰{wp GbAh6)o9edW&'RbxŘ/^:UUFE,M'bvږ'sukP(NJe僈)}_l)xkzAc,9AMbRT/5;Q<0'c PFex/;ٴ:>">W)&tJSQ7J-4r;\۝9czL8$pؕ_!;+-mܖX%4.T-#L(qI/[w{z5܍/z"vtЉ[Q#Jv#yA1-m[%NxҴ&b#.Oi?nGLU &o~ޝ݇ 7Tk{6hbРԒKы]_\sxmԹ6|$e* XxafNjȚSePNK~&h3ə-h%?d~ cmYz;`øKȝc]. JOzv\'gt{@b6&[ͷW% ZJ?+>jc>}>cY<W8!O1>E[4,O7#w \Vi߱#Fok12=vX I~؟z7 o$/&mF*n.izA_yp9hUǮ'bF,qWxXRMsbȎ$Vw{=ߘ6|(,kˍh[ ;sBWXIMy Qt؞YYE2iZi_Lo^N%<'+ԁb@ [i(4~K.gϞV_II#SI"=%I)!S-qzŠO?U7? 4+~fiUf2r=k^d~?MͅE~%fznS)yDZ1"3}#7#9i?(ĸWsÏ{3_>aJ +PL 5i~**dj9jR NrV+I778v9ݯ?֭x7Aw^9"O,-zyfI9^=;jAc_ℏ}+UO{9O!ե<%M~PrqF<o`NddCzK݋~gSGlR\+)_*\֧]nha61SL x3 p'@ׁJp/hW9bQNd!̀˺M؆f(#6$D'\׬Y?zy=3@/ђ鿔$r%HRآ8Q/H%Z^d)WF~/a?Wt!|]'?,Ɋuje3欟Dzd*[~I+Gk,XMSr?aD3 "/UM퍝w蹳^}g_o^x=~=>O}\{3|̜RCWO&M MU'6\(O"_6,y/kzʅK[}c>TLF\nBA%+F!äoƢ(VrHD68oS5|T*xO>%[\p9.89b7_\6 ȜҴ*nyn;N4@i2rտ Li;nm#ݱ_&W"Nx)EZ'Ś܎tjQr/? ]!80qȡ7r G(R*Us-E~ۭYgN\XIXWW@ :8V!](dzW%uu*Dup2shZyUft^IWO8j__х``^7AYICVį"fF^ɂ~@>_\ekZ𾦢"LC|LH";A"%-e߰8(V5[sE̳X)1: Ϙj05e)/~2D݌VŽl(ldvs_#OEȅ&{S['ǠLӓ'Kk88lȟh/M9D3EhO8&̰n2FF(O,G|\{4}l,=N,…\> hi o{-YXݵ+-?<Kv6ƫ<5{ -C@rt-%qo/,V;.:{_=[bgQg?۵.~`o%W YGk F[ML=!Yܵ?B7fmw܁3<&T3;!lqBdⰓx׻~2f>?Kc셧aN#1n!^2K&qam!Imcp&ƆWpyġg܋v)w?F۱{z;H5<{wծ%ᑡnb_߸umq; LOe R,Āۡ|}%bPN :NjXRηY6BAP]B?|envРŎuGu]sEo#zbÊ9|Imx~@{:7*7O>01j.sc ppۯ8 3/hr弗19,DAG<]Vah]i0lx "Zu,v Kf>'3E=/ǧkNxox1OW]ØqOP>qݟ#B>yOp0AJ' αG42 ` wu>ߛݕ'MnTlϽ?wHTo\M}-w~#C5vcSOaZ8Q\o(%Fow$|ʅOG=_|xn͘t|8#ӥV}/ϘCġ: U'a¸'?p[@\io?cnsc=AM=N0gOVU&R`D<W/`Q{kՙܞ#Zr )۹ 83 &Ji8ynF/g_.75KO܁>ƚqI1oڸ> OU;8|??އc{>zM'p WZ/>v<}c1a 2}:qOSL|,lbAC+yana>#pQ`ǚŘpܡ'_Gg`Ђ;/=S{P8?¥4XtX(ͩ^RgzOxq]Zqو}m};섦eoqG3G~ޗhM%M1~tyXNWzۧIoqye?>C?r%8hg7߅бgWLUŋgce7.=bo㾫5_|\}oWfkxG`簒7^\cߵYKb{|ƨN]<&-JQ??!II!0s=s])V:{w~m|SZD:']{tBͺ\|~s1=Gsg0?acڌ9X2}G7Vrl\4֠kdw?8tЭ vbx'ovݻ㭻_oK/-\|sԽ+^~]Xڰ.W .j1{.)}-_U䉯஻is+K9 = 6?ڏwlG;1gq׊\jM{9?|W]bn "f,:3Ă*^3C|>aHm9,~L4aߑbxuM!~5K^A#¬m0k߮ŰڹعV\6v*F| i:3 {0+o_߄=N5?SOg<}1|XE\qxބϹ ~cv/ό<^.>k՝Kvu)Dv|eq&@a g0xW^#)j*/)J>x1*\\rNim9m/zʵœ.2l'7-~o`ٌq畟k#̹\ð^=o un˟V k=vFm꺠QYB^4ٛϼ 7[o;K7؉BKq<,]}F^?? Va`:]B\._h^6]v@;^lۖ'}ރXv50`8yWpL}Ptkǁ&Z}uE1 1D{ A3gN8xN X(TB<_vr%ޚ7 !.K'@m>mj{#'܉w|zeG#/kkzГ'R;uAG`%۴z9z-Q׮:tKp/>xy8wK_]:C?Ƨe Z4-z8eC|MszV.\J.V]勗aǓ~v- Ū8Cxug>oW3]w}w?̞( ,Huo}Iھ&h"d-'"rнaq5/~^~蠸sKѡtd;wA?,òeiء^\mK_-W܍hۼ?uɥ=yRϡii /\g|#Ezlw;s-Z^mllT(Nѻm%];%?V=]DV5h$W:ZqďiUbJ !oDo~gOǽg<Q=T2kltq0zg:6!!7|O[5pO`7ぇ ·`>x՗ʄNOG^Aq^xL{!\kWN 9F_x6pǞ:;lV}1?&o7d?va)Zu.u0+bʤxv_`ﯠO~[ma~0m_VjٛWJkQ5{<kYzcOryWÊU d ^=xa?rl'ſt4s7^xe|׌/Nz7v83x}sxe=h݇W|`k2xs=;Wk{ Э5!Vע>QS}DI/I1a]QpVOҮ&.z4/οo1q9N{1tPN=|c卑?8th*.ƚ~)q7}îN7?o.:tO3\1kx㺣%L~td إ=.޷py]k9YE77)&R 6ۤmәDx{ =$h-=^O,ؿ;g.[E+DECb)rVhWK gtp2y>}8KeG:0ўmmyȹƑf[6y6a3^bg'܉_\zFn{x%S«'KW׵,}O X>p%WNѿW~dl(>}X1 %ן/_ :Vw_r=^&qV⒟>Y'~t/lVp#M[x`;uż\ 40*0+}I0Z&\~(ҿ9T?xR(x^]ӫnDeqćb߯s8]q=VGyK:/iB^m]{jFÊXTBy%SaV,[ըo~Vy 5R_t9VP:: WjvN`Xl mDѵ}K̛t)>c`.qKW|g㼈'jXހ؄胇1v 4[b^E9HR\ DmmB'CʾGL(zh5_n7u8OIԮa?ZoGs 4UazxXj%6Vq)3oi}b,c;V|]z4q"lX1nk?/_1׮E#W V/ϗpl݅Kk\\Y/໙y9փ>Z/wAmM;u7WV7`EXհ5mr@o%~UK&1"]ǵ^h2W~C dꢊRaWx3u$Y)@:zRܵ_Z͓ ]b3ӊ֌q-֬Z6.GsE-&l+ާDv%+x_oj٦3$ESǁnYk_Юm+Z:2Q}nS \g:ZCg>~4\v.{p>{a#ZX߱;6D3phn7fѯ3˹uu !_/ĿwFowWlvxwqȾ|q}h64%]__zt}9mf }4&UvռYسm;[~XSHZmI~Z[u:ɻ?m&w=+6;pڛw[s"18@$8}ݤ-=Z-׵`xq }3>;v-.Jy*Sު`7F۝L\D%$Ƹ|mv&%fQ xr5q0wՠ1fG#r|Gcm(+YSϰ:Z&-&kLs5DuNϯ45Mxr;'6lrf7ܟ[aR`~HH|4q@">K xǛO2 |=.U }剮7f6Ϝ*mdݒ7BaE%b 8!F_Z P U= )Rg< S^ݿ(mE `!Z&$'ƕ0| #c^P"vnqՃ 4$$0U L;/7\X"@oܮ,8 Q$+bv?;'~$=,dU ̸%TA -.ː]pgNcR, r1#+{9Ѐ_+J7 ʈ6OT <-TnHQUǽaG(Lx  AY'KK:Dz8wg!mz쪵IW,TRz"L?~9y*ælU' M*.akKMK@q;2l~v_:۝*.82=K1&~bwD0J߿u旾:hHl"#^5katz ̡G1bEv`OIYSIPo!pژc_t=f$i|0B䔼y& G4iKGVf ;F'$rPp%V,~x|rr,I`dgee 4ĭ+X֍mbcu+Uxx~q#؋w\gr9L'ONXٓO1(8j3[f޲ ;p?zR0F\:OI7đg.~#рw&p$r1M# LLa'X3 ,6*W$p k)6%@f7=ʆ/Џkcn`/l~7 mD\m>إѶpvB<Ʋ=# AVL{w0N<<_Eg ?anwI<}'}{uVL?0P!»xNʵ5/z{|>x\p̯ϣ^}wS-acC*wmH[^fǼbk7c&{%ek7ȃ6v8^ Fyo_e~ϚصVH+[T3 O0oxHd|x}2[3.W|׎lM K^TQ1C#*c'wdHScK Ƀc_la-g`+b ߋ{`F'J 8i7{navobƽPiò0,rU,%o!deiJ/ ]3 m`n(̳eK =(p`gVBW> oa Lx 21 dy!ʪ6= 0[ςax߃8`SڈlߺY/Ol5Wp6ޫY$ߏq||nl{ '[=8`#̝R9ґJ[bw-Oit{G7mބ8zkG3IszO?1^6*xڒs1{jתY.Cel\hv_OE" C7㎟3[ 悐9 P]aS 3;γfc z|̣*$/$Y81\VJ=~=C.Z}'6wV&{w.b/#۴#{Q|~{>io>dtn߽dښ{m˒[?]f<rpVpTd&>m7wM=h۴ ˟R5vv7 [iSM=T1(}! +mj%ֻgOD7?]**Є8)s~~֢Yc9mJlF< ;)կiWδ'~z=|uvQGySWq4yv잛!qaY-7..o!ݱjo[Glƪe|6{Y+>O?|rm6쁗F%>>YM 9(.oI[H'[O)jֱq9L8G1D^ r>-ų'j"M҇NnhEmY{Yy5޻Vl]ϭB{_}Ϲ}ٚw=~6mC^Klմu3aN ZcG `=vjoN~fQw\nc,V \ezܟztYA^68l:aLw{l 'O#X$'i[11V*.D=)'[zh7_lۦ=jN~]56o6sJ{7چ}~jk Ko+Y-oد-hmc|jugv/?~'\ͷ=l7n<.~'69[n?ޏed~)ۧ:Iʍ~֯[kڃ95'qeɟۈu^Xx,w-ǜq/<k=%w"6l3Gn(Gb^(zc3-p MJPvߵou/랳_﷟lC=m.=[kв5Zΰ޽OӚ۱GmܱM?x5GWNUd߸IA*yUֻNu ”ߵ9hۿ [/EoJ"H'=Wڊ\oaOo~$֗VQwѳ^I R(`0I֣ݤ={h ^oO3 FN~n}|hsJ0m<累iUf\oln`.״6{C[t״u5+j[8gTƐPh.D;ywmsV*Xgobv+휡'>+­mxح C T ;z^8bՠ%;'0/ᮍ80YE_m ? e׳(cEDp /uv>6e$E+KRqQ-mݳv+«η;l=#l_&浰Ls;wkzڀCsfvgVxĬNEu?+dg\{]~EAn=+2Ӧo;l>S}lG>62lZ4fm_ayqn0fsbcm #.1 *wJˬBX^1_8Mص T鷔i3wSG:A?Ҧ2ޯ̥w,-Es &f d"^v] Ȣ`!rڏ:ݒ1u~u-;4V/u uOo?1nluv+x_劖S6c/Gm?Xg6hQ봙Zm0.͂&)!8ȡhO> @cGPXt~ۇm@FLLCE*`1MDZ[uSשup BN&2cp /<{gqZMam^G`xlnVagTg״ngu5M?YKPNV Xm^y>Y3ooU+"&G.&|qbZPC%m!Lԯc-;%ٝc|>δ(]wNdN8aܫYH/r]>PB>?m18@b%vg=λH ؠ:Z|fl)6V]X]goVyx`ݫm-i?qa 9X;Y%%x+F71VvrnZ`w=W1Ю?Lo0qʣ*_huyƩfC6| 0l <G gܱz8,n6ً o+cw6pXʑ]cvF&lߢ\L]oG16pxC#w0'~Tmq;hO-[ 0zxSVXE凱ѧw^{F\p} &uN>Ƌ }GhT@& ӕt–ft]t1x?| *SSMqS#PE ݺڰA'k&*S\G{kЯh&^(ׁ1ZY%b>ƴ?[=tc0+!&7'da|kҮ=& قs_d>{>ͯ3+ %gҤa#{?F8yzch$K9&ē< d w?-l׺퀭Qa0yaDrC񃙘<|IbMĄ(qY3q*2d T; Vlgk0޸kapkVmXYv,G6y۹gNNp"Jhy\ֿ{w׻͘6֯DZoXA82<ɶ.#a rJmVv;siֲ{c[8q-S..>zvjnuTc -f/!OZh!iQp?*]4>**WBi7og7@QʤLHig9h,4Z5oa|q*Wպtm8>l#k IWpgϳy9sI}/\~/M6Z.lwՃj>u]yjKnjr+icm6!UuSpA۴Uul߳ XIԆNjS&Ә|fa";ޙgW1?`~~*83 7*Kq ˅HE8ziږ.f-Xa>`]' `M[YƝm'މ:ZXuP3y`Mz{߼ժv9ݾyw}֡Fluzuj O%7YqnֶzCؾ 6Y nM;ly#G7lsΊCǏl}0ԶyC6gM5m`]yuhZ aҶ_hwIv;~v?nm+ :SֺG%v4dnzD@C:\|4| 9㎇2>|VW3I?US_СP>@4+ɱ)~=:9J[ĥPt)ASŁwƗw.f:*Ũ[)6l7KRҊ+GέRx7/)Bk8[h7)R.r>k<7njg^p=rvEQv"Of$r@) +\gѽ63 ݀8D^蜥B.ЕrlX tRЀJ`{l]b%>aFzq Ua!Dġ\ xP ^e:BKйA}XoDofMN$.%7s9fgWm۶ۯ}˯һvk} F띍 ҍ6bo1hgF$  <pB)fb栵wLCG5%<l;rկS(N(ttXH.pJӍX zn{vg,dܱ Be!1[xʀC?.oڞ{֪us,Ix!C ~S2[O `&g!W9/j zFʳY( I-B,TY \ m 4\KJh oݲ~;ζK.<rA$z 2bGkN]]-[]z٥ q& XGtpFaOJ{WDpBlDT ㆴVD{t3 D݉ZHUn.yx^-ɱ2*{8oQ;.ޅ眀^j*Eqg%Q ĂL_0rƤ&v-7ڟWoicbT!ݩ>ErQӒ ༌ ǑR#VL( & ҹj)M V \IGGQ) gVSױI/i^k3aN'u[aG|+? d*b{/$'XA(džq]?Uȶ;~C;fV|ޒ-3'2H, +g*(],qOzy'`aXG@8BA,$ SpS5<Ue7ˆ.BƊIpUdd*M(AI8RH2qm:u1T >m0*E@dѥ)OJtewJUeEG:U"py$? ֑=[A!=5A@IDATF% :ϖsxg?G\/-YV.={t(Qkn䉸h{[j}뷿,Jx˘ceL2tŀzJd.P9"ǚEP/yAhmYmLEuX<ϐ3 1fTI%c(9FX"0bЦ%+rم؟vM?1 Rh;x Pk];_}`֠a}g?e߿]?uE{%TZ^1O`잎vK+h J*2Y qK"7j\c{G# X+ٞY+}=[FޯДA=y Uπ~һQS! ㎗2yLB)JWH.Ve2 Zhj=~sϭ]8 *ZȚhm- ~ˏ #8;alQeΗ07&t! <0x屐\lǽ=3wk1i0(L9C'Q,Gp#D !:6ۧS iӖ֠A`wFt1nC%,{CW\ԉzi;ui{Ka! 8l䨇삑ꫯPChҩE!| aWEn'ӭGnְA}۴y5oƿ w& ,jX=˞ٽ!f 7;\n~F~a OqF gc8oA'=g͜ewv)׮EVcE 9ܽ#Btq #0ıdyZ$햙_2ըhyeZZ,ΑqHd,$(m()N9=atplіZLobͲ쯏?fkڕ]Z91CAm10h+m1+JLa m<%KOKz*ftec'RW82=EIA GCE*ޏāS&]|GYŹrJK-7d:v cقQH4"#=!x6.vh!f埯{2[h1.5[mt]p56hT5tF1ƏDl>7=* Q׹Ɗ_$0 0?&6mLJdmdvSN.ޥuûn9:QL8bJ?ސB&ezT_+[E~P`+C(_;,V$U(V8XAa]Sg̳oku:i6:wꢊ4.Xsn!Š,4u`Ǎr#0>JKbOz +,45&-Y}2mM~9$viְa⸠(^P2"KIvW.TDVXcLo~_z0#b>s6>^}؛{ȳkWt6Ü4nw2NcM'fPeP^GPHчL(+V|n33eX"k+`OW6dr[jM@p}x7;Xn5fNki%h5'H҅|+7wZ3vƖgsMXZqS23N0A)b it'.Uv:6p[jzﱯb1tұ J8+QOk}DJn0QE(S*/˗bE|/N d*_^$$qCa BB(*2q[l{.Ϛ^}s쏱>֫wokִ7ɅюptBShL[̙mg϶SAk 87C} SXQp=ڑ 0 y7?bwk٢ XO|}˚j!XG;1x8L>h Ĭֶ]K6gHuK :A:jxehHtL*?x=0U"ϙ3><8 vV73 ?TC 7[gam'OxX&Ĥ5b+q<ґψ|"۟Uٍ/7ƍelC{j~``UEwO_bwK{B=_`w)|[hB5k}ֽNs68m-GG^rw`=`|n3^8Tq\kCyt"Ox3Wl*ocjs327.,̂KVbeLHXR+?o}`ź֣goի72:6@!BsTAOKZ!,e|b{" XB\tM2mU4N<Nr:ڂ T #MEuG ]Ă0rPGo7' ֩s'to l@߂,gPG D۷U^]!?p@+ayQDžJ0zx*aJ#ch؝6UA?w9(Sx|>vgǂ7c2>DR[tܩl6m@gZIhj%|W$B$;oN k7&qdS4ILx.+6 /dd8Vı{Ey?{%edg L5{@ vi:h+b[iyQ ]UuR?ݧ72lPAc?:2UA%}c3gͲI}届:vg55)R.6Ə% 9*c$-*Ď\=Wm->jٙCO-[a)V5+WA ǼM8PiFZP@6m0j5{8Np %N|cPJbYfC"OO5.QJ< T.6w*(c 1Spf϶۠S10ŮWQ~0*#NqI֮Mp*J18a#Ǽ8i $h;G 8?w,Z?쬕8x2WltfVVIE|93E a(ȅ!AHX8xޙ8nc^/6u6ST9ĸVl8}grVۃX(`:~r(FeZ,#OZzM]jU˶U+ت96'x++RDM[qTHF64\;ڊdxg˄,履R1VB/IJkQ1 3 sx ꢾsmX7Dg8Oˉtp"Y ̞cЍʥXl2*v"O@[ٰun_ET9؉*'ëqL>mXKpPXVGZc9e qhU{zaM?[帽#mg`\mTE+N_g۵]9v4it$BŠF5ƧH_784\9~dq{ƥGcGw쵒r֥[wuk}U%eMܶ};iK͵ 6ݻNm vQS r)1 } %,T Ra@G t%( ;1'Mtͳqogs-l~֠10Y)B|07P%"΀,Y?,PZe#fEʼnO'"լJ>6hݤ*c P~sϞjnǬ䝨 )Vƶk5㯍K}=4ҍÆ*FE]wסw[苭ݬf<*5MRt~`d` 1A!24@,QW8ms=uvFնPd+z?bӌYJ>TЍ]k99U}Jػ~P; شy3Ze3g׵؛2*ukYMYe :`)OΞxgtHB<,O,"d-KߡSZa͘[뼠ejf#y1qm;1?(n\0+/`b!utQApwv'thnPj;vm;vn`dܴvD!.fߚ@VCaU>Zp͚uP8y FZ #!lRC]['~sk7 cB7-uZyCuSQq*iWQ*XP_Ux,E6o<,>>g]|5m ݆X/^ SKQ:)%5nGYQPؙp䃫cv 1Lw–8  Eg1[UK_:mf9hm墅_3k"W h*۵i5@:C2 W@k|lx5>E o0639o`s[kD~>xMph\mࣴ3 tXɌ甬\bQX%D(HR3aLE|̭$T@a eHPn5t-03n5/>k}ʬ?7T>JyQn \Y.*{ݥe?4'6cD?+TVP1c - !s[vϽp;{5?$ܺRb+n ] @.huUM{ڧg᠈sOoZlL’THٓ@ A!1Ld]B"`;uCYѡI*WZsn ?XQm[?oEX# ݶ 2Q V/?EnyUdHIq d*ci> W$珔Z>]~Oms]BsE^`a`T KEf&1lC9Qq)dVJ:ʢ"ji7.TM-]ntuT2;bi6imd9LKXhe$DqN6DaR$`Cx J_cDbȅb8NqZ62rhҘ^/ʤaJU[rb.u:l TQ}Dc{#Vmݺl8&q]tfUkGN*Aid)ԁz#&C*pEE^HX8~G vt<A_bg7FcEF=E 6?[9,:ΞFn{X ptJ p^L-rb\Ɠ/eqʆ$yzL'$e(F/"HT狯p<䎔Z ANt!?; @=~Y;{Xخ9ZX PjB)@; /XBmҏEyE?G=s0q?oY*Gŋ>A֬jLW^^E;u[ݶ2qV_zuvtڄD}ګ~MgaATFED}N /W\B-xut9t?͟ƚO*(_v'#x#&gԩgkټ[k `];*aȠ]>l1}n۶}n:cj f"]~d+%?Ȕy"&GjNt|[I@>yCPuK+.8b⇶鉗7SKqVN%S7IBVJNIq<8d)-\^蜟 E^)y-&^f@">vgP38|¸U`bnyZVz#/w-Wi*he8Wul IA)Q Gl `!bum3.l]z,/86J gy@gO Ad'9C]9&+V4[m5oUV{Y8!o ECe{GT9 X-*rQ nGiW7I t`/> :Txq9L};bדlu7[ *^߾J1S3㯽Z'zx9a Tg/S./QEOz{Z$)YF:L|Ig#g*]"P7 ~ū[<ޡ~& &=r7IH8x Aޒw:O.42u ,2F J$"P(>N d*chmf,\xf BFp7-*؟}Zb\KJ|˵c7U(y.ysUȀ  edq4񤺮: \#b~gauZg[%thgU|,E :y`4!Æs,7zˑ`33kMb&aab%l~϶t2*]V.>_:LaJ ;0IqK T pBE>! o0I iՈ1,HԦ: 3jLE|L͟GoWpx6铹 " <,@2",Kؓa*ORպ- kD*2F`Ȱ@ (H󂌅x8a9ыVǚg/Xtv\3it{éXGYvõW!snmd˳U[BOҒưNsFtit zI+Dn@pe)C.W>#_)ٰa} Ѹo:1.^'6~_`ͱe]9OՒ$幮Ξ!ӖӠ̸$5!ru]vF?ÀQ7/~0p˫>Z7-ܖn W"+\ ^)sG~?zᄅsA;p%))C D3D{ "dx2Y S (<r(D64C?iڋGe@cH "XxkgϷ'f? jʧ3q,sqy^ HM"8.8OeF=`#rzZJPM$[v$>,T!*`_k8{{gΚcS>~tbCp`,qu"k94Ӻ-}=0}z!Z2TX"P҃D+wH%iI|\8 A!yz#,cׇ+I+`7ȆL pš~m|bg2ղ+?G] m7$ ^Cpl? "1h>юGᤀt1 ʳ1@eHwq@">F3)w~QqCnk7?$H@1 9GtElY$9(JDiaq"K%KT4UO\tq܏il9V}j%}^H7 {wԉ{X'#B=Z MGt#C)+3" ษ@Dᄈǻ=6h,l-3K0hڎsujQ]pBWԿ>HxXD [5tQcr5fQ8zvmt>nJ/24›JxaEo`L@/܌ _ْ.>8"y8(5zC=6MBlYC%l.rpp Ek|S(L.c>]y9I ޔt0. FL܏21z(ACNFnPP`F'_Zîh poCd<=fft^"Wp<6:P[UlZR\# tNM۵XWNbiԠ h[ VVJxCF(oFQ^ EĀZcB=|K?_4,8}8ujm Sc'Mbݱ?uGLj;Ookղg9CDkK&',jXm5ޫ%b++h/U`ACbD&AA3$VšaQL+KH% $哜ʥE0wmnyxo[.>r(g!. (ۙ%n <1 W2.Hlr-`H^$׸@qr7Xb=ֶUcV-"2>fP ȔAϠ J9MHNMy88Gқ|?p R|6v×Guc;l㡵Ssm J/™,QE 6LBڈS%Y.Gړ9+;.[ĪSBB"R\ 25DŻt 썼 G2e-5>h۰ܨealtxEʡA pLR4wL+a['۴,rߩax@/PE☮Dd2i0ru3okb:K>$O)*`FRhlȊzx…l0.#3fǸ'Dwɔ P]oŃwL(</|3Z SC{232g>Ό斕N[`^guGxN99t%Cn­l7pPbfSfTCe㏨r#p!PdRP(m#5`@VsOCbx߾B.dg 뙁. G'B%\*a<]Іmt&LrSzzD:s5s4ې>F>a[\/LP<\CϤ 79Er1rJPz,㗺gfN1oM_zѷgvʗ9ie2 Bi6{.*g oԵm[c'~d*,Q&^! #! 䃄Ɵ!͗TLh "h 4pkcէ:{՜^`vbe a:|eڷz;ĢX$PtETZ%aH-`fs,xW~G48 ^wi`C<@P`3~5{j4&ODqD g@y8srE‚b#HOh?>z1M?3,$VaXxÌqpsWrdiӔ]l2p qbvL@">f~%ɜ%o{ ?墋ݐ9~8A[Xdgz"B *i)SF̐lN)!9rxe{fbp%DttMىut->:Obg9Cۖ`m9Br % Cv~vlo; lr#6C^BHV8CJ+ăY c]q͙΄IVvMd/nۢUs}1&ɝ%cK 9,XpD!xcZvLk7t(fcV ;ED>jLIuH(x 8`?:)𘒰,VNT TT. I bJ>AA2S0pR&Jw20'AދoL[ x#xw^vX8aD L`]]keM-9.I"pa{kE9)˻i[PeÉ*tb]ŠQ؁w@"T 5!~K?_m&}(?C͚7idPY/1U@rO rV A7ڵuUj,tM 5kzB[6JtIXѾt&r<2[QN1۪km!v-?&vnCtngSRT ;<q/D,t*|T*.l9@_+TlM Cc*fU {RvdpyTBE+#oDe$ :_1 t"Y /5i4ᷠg$~0%4Qr'B\g:1ƑOț.0Yu4 --̥D|㊎ 2Goزy \2Wm *c ­v?^h~ {Y--#֐rH!;ƼTW*g*E#ܙcnȰ2c,Н4zV[(Pq(X1b]w'ی_폿awl> `a*u v.T]Ph+Wي qٌL0&xx"ʍ~C)Yt]W8,۔8" t=wmi> 1a͚48ŧ<90&a3&Qx% PDxC@IExI#8QV*>`۷ ZY33EXq4.nitq [i GX~w*I)Nh|`90XerpW |r8 j{|mtSŏȄzR?OpdI@x_|r>Qҗ_"x[%sC*O+㎏2Wlw 読Pn{_^|Vk޸Kb *\qd3m@G:E'[;OtDȸ]$ rcˊmYa]tlCUW3KQfş:\XAxk̪YNYO>gI0'IS\A&蜚!FÈOٜ}Cvڛoo۶[eL dlê`Fr6_c3'icB?AyJ'yHmd;Wbw*mI##+Y1CSg/>o O8Ի&3r/v0tKa~u( F)KĊb&4^{ >^ھ, g5WNm< %i)>MtXK B .ƫ(aҗ<׾ EI4 G {!M_9 8H*n]ق}2s,B#|ڵ6n|J6 g C죓1CX"GƂ(HrwjQ\mw6:(5jF14hLM|g)jbO,IX5HQTT;9"m;333;[fg@6?J#ˎ#qq':O2֭mwXF]TF&ٺy=\vS*2HQw*H }q\&e1M>:sIc`3̚x"lƼq$&q$˞64ySoߒĂ<H3yNPB$>?"x֪#fCX#lIfc4gUF*LmiqT}S*dvH_PvBH̔U>#LCݏګWG É/>) @y (Sbڴiv?A{??m5\8kX PAB XzLK}'ؐLO|a{$i#&u4KY<Ξ=)d0> ކXa~`xx|wא6=`}A3 \o  ]x^+ecS ;5]SD Y8PfFx Wh+=}Lk3gͶv}Oᵫ}ia'ԩ*VeH%  Q` {^IǠR M.,-KP pQf Rg֖uњՔIZ"dg Dx pAaBV v{)gÝIf[Hذ_1 [Kz?,gBhA/]#'pS!-SuK LœKV|/팏x 8VqX"`MR>Z|GɆ,lrB %z<]|\kƛ gAq;a`*n]u$ס'# ;$D5v& |ccb6粒 ,>{lxЩsXz/bS6pS^=Kn`GLp(Sd2m([ͻZP)uQYNE$ʬP,:(E6_jk.8G)/9r{eDZRfj7N 0SjGF &($QVeBdhè"n~Pǚ'2L[G[>)W>$guF6pw0l22ۨQN8wAA\>{Og_9)|1fXMy މǀO'll +W%믹ܻ ڧӯmR>uRر. z0+C!iFp/y[ga:po[n߮,h+}g]v :7E̢,F6yJ<}G[b'zW$90c4vƬ7lcOhR'w :[V-p9A$ &~RKq_頉(*D[viڿ9g&Z-щvz;!/]ak).(W'e ORη5riD^fZo[IsUI>:gm>`<[t >-,{{\;6x֢y3[Dhp+.is{}$ɖR_)yQ9G9iUls >IL&qq'#O`6dֵ&wT^"N69%t A*V-\L#9 K<ط-l{BݐCJ`Ema< 6ᛃxZ`f(?t-,2٨AXݭ^_kEN?bV9ln."sO~!u9"iu-_n0[q*']~|$:-xϷaظ'w}ԣxeWa-WqzPNƲ!f,/{~;fvY֨c'Mފ3&0tR{뭷?>dW_ypA6mGX+>\Ɓ>y7`'̭լ.foZz5swm/w&"YUupQďZ-.uQ[v:,XZvmh6Wp /oEs-_J8˅@~F16\~=Cv[|N8K=tl|[?l< PNe':g,xb8q:ؿu퍵 2яһVs8 ì9Oo]o"d' pbܹk؇ ~ ?pj>uhY'w.D;ĝs-{yuYĴ9 *~p[߮[z5˷ȱ{_>Ѽtqr(_@=AWo5oXǎq2 > SUp D0O&Vy'5[3| WL5e;]Xoӕ~i[1dܸqvUWY_|w̘16oϞ=%v=XFɰ58tecQyޕS6p;z9c+Zsv?5QqwZRzbk[bgubNQ>}q>}O'1YMAT''~տxn?z o3?[<߿5ljDS>eټ\eG1)KjyJwܕZo|xuig+n06vf7c(ߚގ W]w&`JeK|m;J&nŕ"w}vGڕW^w[XC3~sf6ηihH,و0Hǫ]:/<^F؜'Mtb,w6W̙m,fCĉ[?\ ~(ۈ\ P[ps9 6DWq c³lZիW/ LeU-=>P͍Z!_Qs!@ zNc:OzjwJ)&VnÏ Kw涽5ujqs ʩ]!j)F|kۯz|2e|ͺWbC!5*'BՏ8AY6+/ L4djxA1Sy0{}C6wc̡YyGZ\z짓3XnfEqDb} «뮻Nt%9n3/]`|viv}I:Tl¶]h vwnk+6&ΐ&}=l/~&\fx}-֚ۋw: f q|`و+gͰGp?N6jmˆ#Pb@-]^Mrbg]kᰗ"Ά~ꫯðW\a] k T>0Dn㎳!C`]V;*~< lb]FP zlqvmY#;"dܖ^l3<n'atEVM)G`(ě%59Wc?j \h﫯}5p9a!mɮYfio~3B)MS~ބѯ ֏o6~mL8]}yy967D%Nzv%;-o wm%0y]˵1偸P+Ń=cߴbV[|+XhoV޾z)2qt?teBk]v"(ܸbsٮwy%6 !&pu8<ⴭlYhi? 5̶l>n?/}c5_HȖxʰrjKg5:8|}upqp}K/=>jV4]Aik5)<'_*NDHΝ3IC׏8^XACSzP[4cMJo[ܪx"`U['+YW) 1O:>OwamJ?)fm GsS٪ŋm=pX"PQI1Hvy93xmǰL{eK8_\2zb@ xϙO=x:pc{Dy{۠ߞ_gF \qlF¦Z-::b!oOjȪr;88| 7ozv ˅9x̙D^8 #>b,;J<ࠂx=wEy!+wxڦGOk {}Z Pؼ׬1auQԚ(k6t ͳWM_ٳ3Ъ9s4c9Ʈ }$6О؞ŏlk0[wTNWlU1֬}jV- [z-k;tZe^٘r'88quo۽]駟ֺ#GĬXЂ4; u{Ż-+'{+{N|_V1F|'%?A{?[#Nލ߻#0=zYN9ՖkZ̙X[u.j%Re;js޳q\I.\@[ 66$.LFR[2D,y$G}nVPޢmuqs|`wϷgMpê[O컧t u{kͻt6}یqsjQ}Ҡ6 LfnKzm\نr/g1(w}AHԤ81B?Y\䂉MMq& q\uՕ$dK]0@qW!k.:>p{/l3nms[9 ײڃNZĄk.նtR)!O6Uk[˞S%rj}Sq zg[GV#hJDxjhè~zϮGWwGR6c0}8?|%hY8}GU{/RCm7εo=p*ub#m3OY[:=wɌWY٫s5ҡk6ex3W1ju^Xĸ'_{gGkj B5yg~xFt`W  ow~dn>$WD:ܫ {3SLlw|z?])2V9ךժЬsם[@F=1Uۊ+5l8 _6n8n'OK8E6`&*@uډ4!"Ov'_Ѳ ָSg{ٳr H)_;qذC3yb ;= V\mM=r*G`W{t .|5hܹ:]YasMGnkϰ15k^U0<ҥB+Mzuq݆I'+gm})wmo׳:f͚g'oT<[XGu׮MUr3+uK/ϷlR1΃i t 7M] FuV|QWFؓO>igy'c&MM_m| #mӾj+#Rx3Pv6N;766jj_|!ţ,] Y=T~:\suQ#@=es@ljb^z}Ԃ/(u[k׮5:u9̟'`P{uT/Yۜ _텿a׭E<8ݦ~%cRu}z_F_Uu{_L[Y_9@laǎ-[]K hf4?ʨw#C17H|~o6LjھwSU6͚i\sGߋ%gmpڋrƪjިM;krv:@Sy[0ޖ&|~EiҤIٺi歄h/d_WCv[n㓸m5jۓ?-F~j|۠u'3| 7b0+u`cv;b[UΕ#P#[1۸?C8Qr[xvpW\ewooLYc9;zt :|m(fV u],U0_M?iW_}t6d"^b[])c=ˍZCߧ+Y[0cU돍V\9 ۊyGm\6._j 6u?g6~j񳧞j p[0L>>j,"+rDL)ۨl^qq]WW"'xQQck7b?;ᄿuW[&Ͱĵ%,e;1gn:[cG1RԻwo] Ż+kg–_~N>d~`Ї$6p;_]M>6߳3^g~}ƳyRTIR :b2ysl)Xc5٬qFߍM1uטN㔃TiZ $L"/rvqT|, _סγ>OrRS՟҆M-9j(я~dA'5cgehĝx=7NwG]mAZmNk';T~ bU=0d xU7ߗ' #t:x|m$I*-F̚[^Mrt qɊm]9#i„ xu5?7 rHfC(o?YuڸM?`?lQ}j/UZ2D5tZiz_ܴ#4eAPvˁxK:rVU#G?Qk,Su 1|E>` MG@K_W}'Q/|q٦pk4 +Y}{;(f{MhZmr*G`Wn9+enիWq5+؃>hCq[)E;*;&=|3vژ1c<Wv+G^qA_Ǜm]oy+Ejk,UOpսiZC\5]9,&#|~cX4$UU7"|O<;]ru~znܢ~_۪NJZPҚZmc~ҕET6{zLzJ7,wn?sЪZq;o<ӟdpwNb~뭷7{;`mtO)YִS嗄ælN"8Á[Sf?Zi#fۦ :!WQ&#1=} gyKzVj8 yg_Nhaszx ^>ٞ6ccGw%⊵u^i|rլ?ͥC9ש#NʶF`yL1{_m:3E+{sO}ۗ`RQEs38CFq,"8_Q66sgXg^| 뼶mu^s+vi8 =5]ۣRG`` <^IVvL. ẵUH^<5k_VZeWU,">x;s6+Շ@+ ƴ3`3N'nVW݌S!",n9";lҤIzfJt%_JQ|E wܹ<Di+e6o,1kmʕr`}ڊ_xiȠor*G`WnڊƍVbm;V3oƁTm^zN9ꪫA\l1A=mWi0Cɋlޜ8VUq&kײo -V"hn%ҢmҤfMؿoe`:Lva7!IRcFNSVLaW췄+¶̮͊oN!kљb^wBLwYWpڶni+,:  f:^o̜n}4hk2QVRkgϞese֬3>rSI!pX~ tq<ۀ]Lޒ(˰PȢ_7wWuEx[WP2@; `N-D"qN_ӗ¶D߲[,¶P [9/BZt6]V4g]t¼.bڜ:Qg뱞S۝}cFX=Ht`Sje9`*Prad*C,eo%^}O=Z-XJ\!D۬]쀡YӦzM}*ŀ{Gn FGn&k7@P'4vkм)N" eXcI$*BUmV|Ö8`5fQB%)g3wvQ:q%>gYDQVv*1`Ǟ^k'w5op 4l+IO@ڧzr&4q-8zc9?ѯ*VNBh0%ћﶈ 9$rbSh/³ftc]r$3z D!D+vmdA!M4IITȜLCuOz˖ۼqOX>?g߆  R`Bk)5lh?Y>ApCij9ogϞmkeNN=ڴtэJڀL,_/n]NGl\ƞzjm`8]QOeku164M٘1cpxh ͏¾ƏcĉDTa) z7u· Y+()d09=i jw-4ˀ('SpǏuyOY H|yD#\*^@+20PS%tx@!NBpGfoΛo7ruv%?gr/Rb8xvym)j|ֹC;ky/_ ^xBg3X6/m4Q$qqIT:z> 2(.zնl 0 )V5kPLlG6Wm5dR&A ThTax>/_~w,]]Ngd'B@HC|WBA}01^*٭\՗TdLq/qHv\FW'Bt AD dq"a"f@6/,dlO*qr# 2pث[G`19IrE&ҺbsA^}LК.;Ƶ|nm*Np&V"dg‹/_x܀3hsIGRP#3qBKD_ƟJv!<*'u,m3W[S9E :b*Bs;J q&52-3)Â'DA /s('٭}s `i0!Zy(H>)dжMZqzx3d*-_nux“H=7 %ion|4Y /2EpJ6B6Nhlܼޜy9e6'?Q$e6-:³O~% v Hƺщ 0x+"G1 N2IId_xIR?&ҧl҃Y7/K N~kk/\$++]yY:>3Dl)K!h?!GHu=Oq:f%^EnXv)ǛusWHX L2(bCN֯偨}A> Fd8za$I68K8;ch#Z$L䔢A -1x>KpO1y@&OBYɛWd/,P` qlcBGHRGn۵im{vlh?lJ 4r+̥/w )?9E-EQJ)H!&(""!ձ ,CY +p>pCI&WP}<[hXޭ3 MiYjd!t@I~:؁n]6qT>`MlXng-y@!#8%i>jD3*ZrAZ"H;PLhI@D8\H0q0=ѨɖL.OlBfTJ|uN}$dTʈH[ŕLI $zQۈ8A6y},۱Q=2t =6?nfδ{[1 hTѷ'{lc'/<<3%{ܢS{ifJXQ܅*hh K}iPw{%x0ۜ),k'e2 D,"Y =2ɤ?B"wa}{&o6Nuvc23ΗxRspU'U?኎# PK[_ڨPA*Yĥq"C[HI74GE8ByjG] k@IDAT۷G $sxV!Nn"?,͜$ q$#dD䪜^ P+yopV^IYJR/A%%`տ=/&3㜎Mvu:vx.|wmm۵xSiI$ bb,\~`fx4l%[z=tj#LB9mcX]#HD^3R.C@&2d ?C>jv~"< Z* Zsc"(=uqS8C5JA~Tj[s FiFGkخ^۹Kcvj#artEVѰ"TΛF?r$pڣdD$=cwneчM(rJ 2@'ˀ$lv6U.jVl%(Tm'.A[~K %K=L)l,k9C7e/~"Fٛ4LWxZHU]Bf"ˤ-YL$W4IcQ@d$P Kܺo$eO$WNa{v-[jƧQ/I=" 'mVYި+ghW\W??ܥ3&gq+~|2C6'CO2XG~%I I% y:6+I(CWZf~`(* -]aYGϔhO L#Tm%RmXm9%f4$u?!;Nj/&^j%\~“qKE6c^{}⋸t8;M2>%R12f*@_lݳb/;W !u ]Q(hdH+˓ 0eЯ<eAcMTMI/5 FXC723IC qjgޅRlԠJ>.Q|7bQ җo])I q`E7H8E;': …xQ HJ*IeJ:=ܚ4zӸ$$JZzp>q>wxA 38ȸ3ȓ6Θul&#ga=cf5EIa2| k?q~ hPPW anD:g`.IڤF,2\ d0't9Q)윎F' aA=~^)GM/xD?2(7/0&}Eȍ8ˍ1]G]&:$`e/k/#(}HY g9we%n8w<Ǡ18M5ҕDd, :B3i ɣ٨xƻF oGHr8.Dޠfz+IpF\7+O˖˯f3i/. ?rؐlzƝ)ыtt kG^jܨ1hRd(ĕ*0?75 W!]u?c'֩M/&{L4!yPH_Oqq_!P##3ٴ"W cv-X?U%)Mc٫tNp0HzY6{,Tlg wbƈI=T$\ NzEy.[)8?tiL'ڀͰ.` J܄[XyiE].;IfEۗKo {we3g%ˬn׹jz~. lx"ڸm4FMZ 4xAY;\ph3Ԟ( G"eqņb$B }AIvNb?f|t׉'t3E Yay|j!:$`Ö+ ]I$Y sX+sOe%\ŀB}~WxyZ 6i0:qLڹ.Ái1l8LIXBlDH2s'U9 &'L @B!gILW c1Qͅ$h %yGKDx*\iV"nS/b5}n 4]I7]f;t=!/cš[}kwUEڥaƕA#vgYPE`Ym"!K}"# a.2R$ZrlޯsE.ZM~KKZZ.eΑɗE0q I&~vKjVQ@䱄$)#+t`a ?U> <hḥ摼/f%Ɩfұ*BM0_HrS}&L¶S䐒 B*N҆;eK<60 TQ(A>ɤÐ](+]&\6pYx7ޝ1(7HJd5 vOcmkW&ISš>8O>?8:thop=.:+mb`ڟǑx)U̹0SƉ.) ;E٢.򉬤ǿsm.BVJSd|_RhR^"l#{& @krdFuĒL‚{0eۢ4 K@+;Of*S^u[Hooj$ ]Y)SBaMѷ j{ڊK2(}F E!ԖJye ­X=nJ<&-!8`E?! u-N ~̠LQ6S|/eQ?W|&dSJ:H+>eدsT~yDDNH'[. sT'9IR/rNIh;7TB2#G^$e$L HJh~MB$ڧQC,ɈKTcf,Udxy(\S&z&7Je`GRv{#2"/#!K) FCPjZt!v  @\`7m+3R<95{¸-* ))!>V{}{ <8Rq3m+>S1!_dg~sֿ_z*yS_.GrS6kЦʖ7OS IX _6 ۫=L V<BĜ5X겜Ӌ,߯4TZ@O᳷#Pdz QF*d)ex>4!O$1[SOXkF29XqIeBۘ Lƒ3j?|5&t8msmt?#hKWJ./y9o$p`݈~s9ЖWr3dط3W.^lџa2%:VAc2 u)a݅~Gv@FH'Я?%u [@5MueG%t4J|RStVtzԎ>/+1ݴ/|}֯3` <+^[pitP]PLtA~ d/KXQ?\DzSfmߚgʣd,_乧^jvȢNAD9'"DJcմ>cYrLE)qV0\9wЃGq5gh/-`dpdb,kڸ|W|x1ܯP/9L" dx%!Y&[)H\A1.I b/' y2y =i(e4f=fIOГ=KO UDy@&oZR%Hg^K&muB%߳TF2VAk7 Mڶkqa5?%>5{\;-QQxI/<>]o+Sÿ: C~"Ni&L.ӭ7+7IPmfivҫ*'ExmTEe.YV XI|q^`kWKWz捭~ g '_k^?`>F1Ql:fm:񊄖@)ѹHB^kE:7#>`2z@o} &=~p^ dS) h2I"] p2܄$"Ƞ tDdGƼ$ pogXV / NX}`L^5<(\Eu lR{ٸlܸMhTw&ּl̺ujc/D2O1s:R3DGl :Q(I:K[C3Ŏ<Q*i UJ6 %[HVGrQ,Ф!Y!Xbv IdK hPSegLЊIhH$IJOJـojCN9Φ5LJND̢}2NU6 Lilw_6 9*)I<7&z YYV*#N  xɉLAYXA*M@I`oGfql&5w<k /%W ܅K17oZ:X0%^+i5=> .k Hn:NqɲmqNR}O6I=!pa$_r'!ȃ)X^Q|.ebX8œhWh~ 0`XC̊h$˓V-Y"rp81D s T+ F_ $2e K^'r"SI`n}{۞}zj %N3V>z,]L.\^?'&l =p4~" (s)c/Z mnm^I&psdKV,io`^||vj܆f+ *p%*'U~Ȧ Ǽq` $z o:#X#\ 8@YM!O{IBp#kwq@<"ybz ` ,h^  'Wr2$Ly 6w눏 ͺvh~xǝux<0w2<_YMc=a}wvֈ 0&#϶ݠ`˲9gwu$|R^ ΁IY^%1uL0pdJ }r:T$ar.|GK&J (V*C"(/Bh`%*,IeGlF8?0`k^'C v(1CHO_ e@":=aI&B)svv$n?s-s_3^}}vFXMl}:ޚw6bPo8)1`z6a#]1_k m1c۬|ˢI wj8̏pQ.S%)LZr/22)$K{g̬_!Vd%Jpq6{XceX'FJ3Dtߩ(3i+r:lDp"im%)#+Mx914A>blX*S`O[$mxr蘑gtRm@g<^/q`L E fzuL2po'ު^r^WAA#XbF&1Uhӣ&15Ůi Jo*E:.𭵞sE~=iLyffϞ}t܎*\XksTn~3O=Ͻ*Y CsGF- }ưrvh.{_uj9nmy 7N +Wȷ::4uae\C1f,d>^: ٮ7FfY !I V!_:L9--&ʙlϹvTKRhfbBJE'SoP5]tj"Fx3tŊ #"lt +kK:Vɧyx DEKub_t-!gdmMcӡ z-b`U}8Vw=&\6䷪R\'a-Q?[9}סIHR !-\ujܹ7w5GyVhڭ SmJ/HSDm$8(/\ |3zDkigaD⛇YYv!*+giߵ~t؊oǴշC/ء]0bp7ά^U6 (tq!KX x|flԳTҞ̭#~V)<ճTd d5~!P>E4DFV!"tW9cHOEj`h\Tf![xN_:4Lt3j}8#b.0qL4DM1rLώUN˰+8OѺ)INk$5$of ,C&M}ד:}{ul8nLI+n1OҒg@z@,d  OދZy )74l)_-gcE^"y8zة4#(V~TpPyKfв'6i.0'9vp Wq,xGC xfsE#A@yR pkc&ȃYwb(Y:%/QS-5ikϒi2#2':nSMa&2 GLo=Oy'>:"R~550>W9a=\\us7F 檘@VU|ו,~"*`ҟYl)7[Bx 4#}ebfJ0~`buErCLq͑8 N9JH8 $@$M I+gCJ+ULTBM&sG~g_^]]1f>@r=Jy]DR^OypDzĉgkS[/MG$۵(~R'~%Krcth(:PȄWD_^RgN^5$.4gm:\},`/ĕb""2M[ ߄| *ܰ`)@Cā\ͪ$C" =ucBܩ{K)雎z~F^@& 0Ż DCvp3ܼY3B˾y:uhxhV E"hW#އΝ:УO{~{:{6Π^ NzbѠvS|gh[ >ַ%;\(90I;84-aO°#0eΫѿ0hݬ-#a>"\>LoiTZ^#fJWЇG{_{*vp4~e^[8qلw}P2>fyW(Qyߙn:T|!j[/և/4%t7(iŚD?c5CV:,;`֕>u-~l8N4 Gvt'JW/ry钒&gx7I82WRrQl3,dT c,a֥ף!#uXa[’p%b TyѮ(̓+R8 ,\o+[؞6{m,v7I6o&MwN]?Y_ʹZp+szń)-t Ĩ|̵Ӎ274f,_yG 5\7:2®Z0%A:őh~cJ' @$ bGeiv3 m{ Kkj!Wpϗ3ǰ{Ci0鐂H1H!!E9.e6lF0e8xd.j<&hd">{"gq)%gfb-—pj!2{ޘMPs>>\6lk9iqpB_OZ,TLtQOJV|];1p=\:d cclܸ_mUrUt֫Sv-^|_*ES~Ma6k޻8q ߌ^#zܡQ ZCjqj:\|$UH˵jG٩]ǢQ.,*g_\LD2zRx)C\f%/Qd3&X` MOWiaGƙLPΗIK.C@ &d8 犨G 4Lp6a hmO\w؆!aOu:՗S!1qlh$C)с ԐO'*6eǢNR.֖DK_bs а,>+^y uGv۩>Xrh3?CU\SّHVRrFWz54d`5XU9il> Pn|^rvV*mRk5l5YA5i#ҟ&~]F0XѮUSH:Iّd<_?s2yd"ڷi*.:q8gW=)W8h!z@sɋOl]l 'vUu נѳ#s9C驘_r>_l=ˎWNS~%Ust:PTD;M-B:_2df~ CW9N*vFuo$3k&>kxX~yW&C!) JIuIu`YYU$fcf8 TA^@B <5T9__ɑ'vfq7ƪhٺ=xMa@v| tkE4!苿yV+1,],dޣ`͚@טZaFhhk}g~"+< ?-y*L]k؛O`:9Oࣵ0iS1qіC#C}mꊌ(i2pGՌ 䧬r;diZl5,x!J2h O7kU Z63eͮEF?GO~~thtъf6z뙕<30u&l\Qd|:bw39kjmHL.go1yLWeNq2Zƒ4ʣ? ғ&T wo~~9jc8$ŨC)NrgoF(6S:CvHRZ # 9v(914zx.u j9 .YVfYg}vuC%Y⨞ԦLZ^GczjLy{:ޝ@} G}Ы}n) EDGI\s=uUXx ,\˗axsXS +1jsڐƹqbyPVkS*7N51g ~|0ѱCK\qhIj+ie:"΍rf X"y4.<-yp~R:ۻ3.Zgޘ' B.mHӠa:N^rbQe%l33$m tw̸f*~tw*>n`vȅD /ʎ_X+ ^^D?3~h $ù|Gyb)tHl.C8)S46ڹ+ D7 ^:\po?\νD]Y@ J𠭼]1-r#K.c $C,$i 9{F [()3`FzGN姫bxw{x mݻ7;DvѣG'q_%OvԈt{ʹlr̝;ciثsK4v4;]܍=!4$+Q_,fGLh6KдJ:-]у&^xl'ry8I]=vi`bV?ѳqOgb˜{om۶NʹJ_,ڧVʰqC%x-ܫ!_6{V\)Kc\եpd\-Ug{C'lΗѷ{>:Hj=~ק0apNs_IY+x7s6> *ZrΪĜ <;v6h 'yUw5:7AzY9{tlS5J+gȿS`f1f \/Md9Nl,8IXo l>pƦ߃_\M4[/z ,x$vQfPAN0V `s#(.d[jaC(MP\jhLO XsyƬ9xv+YƁc;?8Άu˖a4fI%^%wCNI&St`F@ Q%TѸUrydRLyoqؑ:t&4,QdA}'afx-g)mHepKe2̘F-V 1~Paцu0qvd]!; 0}Ur.k5́9KoƯUثAMܾ.;`A򲸖*Kye9M[NBe|W.nvX\9e.,><|g`7n蚅ny뉵g'fⅫkz<83F@3S۸yzA[w#WQmG} 47/@IDATb߽G|@<"_`,JB U0p2@2/Т+7ѫL95 Ƭ7ۧǫ>m{G/E]Ɵ21V? 'QrSm̕oCI2Hu fNJqVP*/-}h&,? FYʠ]0#㪑qf,+^pf<{ް#2GK䑕HPI掆 z'0|D_m1c?>Wx Pe1w>p?XmQރ%oZΈl&;9!Ҩul=`mX_x]L ؆cO8?;\ty* q0O< b|)>S%JR\X;2RܤŃ ~ea>/3ӫ}~F`rhǸ)⍘хM[F`.~zhס L9?A'a+&>x\Ih<65㴫½W𡽘7=B,~/G=uok㕍-ؒ/ی~kieVh LNyw{LM#=6R~=Mz۩LI;/ɠ:gjKjTP%PfHu@:] G jsEoq0/ڴlS*'aU'ض$n{p{0đi1WTa$~BtK'&)3(1@h~`1{yⳛǯNBmQ2ͻ6r 5QjyxN0s([sH-*AqpD}ƣO>&Gzl>+e8?F;Zt@>n@Yi̠,Ż5h)",Js I FJVY Hzזh“v@X)b| s jqv -F6C8kPa5UWџҴY2znƩ'3r8| ^ućR.l8n2ڊ eI5X~IĸGybpRxІ|#Dr䴀Rjd뎓\G1XKGKsy+(8$E!d#wfwuozu^ ܈cTK~J\qˏg '|qI6gzԤvxvg*#wi-KXFK<:J4&EI7ON+>?4ZbZH+L`җԢQfy:BIZ־#ZNmg^3;eCǟL*^EͶҦXYɉ"؂2FI,/1䣃WD.<6{īLT1Dw ~7ah8`>^O9\&y/LrY֙YKurwI~vSM"G9H“Оy}.V!Bs9V+^܈X Gk]c6,#L]ʰ`lTeHfΎcX;QWXғZ`P֬KmR[e Q4DwFmR"GK<&'vAߘ#h&cc%q&/+r_x D7 .O1@PًAD;OKvseJYHu9\f=}y7y6N>L4~_6ٌvھ]K` -?cرCG46芾>JUz2(N0k6.;i{ה(pͳ3"1,",|sԳMfxqw?.~vzȄ(cmCCXgdpDS.ĂϷkEʯ[R;c|J/ԑ'ssR<ڨԪYCrtGgTrGܰ -X;{7ēO=^={ծz\H^Y74nʧ:G'iWZ6L9oZ0)/r,':8@m2޴a$TPfOjI_75EEb ۵Ų7`ʴ8}Y?A\NI ̈IBD)!ç qTV)[ %!rR"LDkqqE?,rfީK~ M&uvaÿys^|zi.*vεk٣f|^YUۓs^3 I Wއκזri{E;W(E_u;/%P`sʨmGq :/A߾}w]iZU.t>G8>)N9~EG)}-z>M% reP۴hYgҩ ݰ-]3ƨ<ԀҢ\Vf5! ׳1aMi[qd%@VCIY;+<N~zxJ ɸLvNK=; c!H~r$a?pF=phs<}Ll<rV=8Eg p9PLVpCb_Va}*R|LEb,XS,5-pW/7zXq9XsÝ6n'_JJOOuklN0b6 b}`;gjs;6+$Nt.3s Y K޻_&y9צ$ZmUks5J8H6?K:Qf2<[׿q.Fnw|<g~tbfBgQkѨe .`1E5POCS p ;8* CtЁ3gUܼyPJc.WVns1c{c*6I8ςmp&ly'4%bJS$°ڵrLn[GFT_T&D 3*Vм|M!/b_ݞ +(NKsWGTiON}p5pYaU*F-T~}k/0]]ȭ%a߃F50ϗ-g\Y 7ڄ7t2\>¬cA=;7&?ca!HT3WnS8 }:uekfv#iyʣs|Pt/[spѶ}{|;ďy=9dc|4c~AnCzUWDs(*TLv2ww%RHqĺ'j^l`E&=t+_&?Cɣр_xa:>]u[tňI5xmT4k]HJUԷjmԬ3{ 2ZoOq5.U0ov2v4DGT](ޤ`#RƳCb\ mepڎP&-D,VM_a{7Д8oۂ_'"n~Pʈ3d\33-Uf0³aVZdtMG/z%uSR*[<*Zc |S/f`+e VaԎ]IICrIWbJkqw|= Zӹ-C?}{LeO'rWB[AIR51w"\;1tq' z5lvls5s??Ĥ+Cۛ mNo wh3 ѯ[S% Ajߏp,`Wۯ Om7>v&1"<{pa{ضEpؔt7/;޾ǟ`6s[:R%CҷUԫ;FX]FKy " uUp G? GycΙ6xC,A*-g^9mƋVvհԵhwhP!וTQz,?t2i8pQ9_m+ӕhKɫH)GWRSI(༫%䗧+E2QT3DJ7e5'̄ڰOeڃ~Sy~^~u4X >lӐ@A;KBaK"9csޔ6$lzuFĢDFi<$MYsҳ ^ d `un1g\{I(s33&8C9eJ.ı,cPЂ>;+D=; \.2ge W)Eɫ9jVːn G`3DdH-Hu"Q7_| O1`d3^KXX ~#6c֝hʯ5怫f%7kyV`|R+h<8s٧!5Zn2.ε]b%oC5r nz?sr]8|h܆Ƹ8O[ڶ%j3+iб\*5!u7ʟ|\.]nSZOꥫS0]?S2Ģ :M]`Q L u[Wa\d8֣7 fX݆i8)W=ȯ ɡ|OԂseJĀ 4Mt_UPrA&}xٲ"8j.9D1ORܻ7RQ" qmP5.{4Ăό2Q/O R1kOq7cđ(sUj3e*\YL_9gWq5y~#Q-뙍xvv|7l7834ż6{0o4ƆNWV!s -PT~x`n뀝sl\gJ*(:l+Mߢʍ Zw*Ͽƈ]]Oc&6 8³ݔWNOb?㈀r^d|.t \L,6u…Kyp !1Z.I MƒOhyF2ʊt5/$/rNFg5e?xt5F^Nf!j]yx.%'Pt ӷǧԵN,g%rX)N?$i2t"NS]&4k/1`@lg SvYo_ hqe}R›6mZ]Ѱb,(-C^w|W<÷mބ>YAˣ/1B,5;PSz_l`Ӓ9Nw<WƕF%y:LMPHm#ܼP0jhTqVs&Ƌ/G_IN>zsz3(_r>lAm KGtJje˨p8SS0ݾVV_,W6k 7m]q1>SKkt4쥃w`mФec~t!&\zxrƩh\!h ̵trj͚˝Pxи~+4޹puYPU4VmZH3P<,)΄j,wwy7Wwc'OabV39.o7 _eq2^;hx{G]U˦[']+NЃ$ųEPORݴWpԺEM9pQf3[ɬ=4T+'hC% Ǒ#qu ~xAڹ&N:7 fmS14cR1燀oV_Z{uK^*+#7Ҝd^)HrrHWl=gypt:,;-AU4Iz3.q_1inbI7i&_Y|{![i|ⵥ{;Sy?V?wl٩<٪qsq㌹GӇNwǼ#X.\) B˓n.Jsn=3↏w7\d" =0= RcU1ʐ-[ug(gTS34b5Ji k׮g;j‘J"pUm|U_҅`f;fp3>54~YFeI~g%͔QivJ?at٪AA1d& ~ "K4M4. D-Li%jrZ,,]= 95Q' ӅQM_%d ї,ʃc>#7ft&WpI~W7܄s/1_kVd gD Λk L<x?( ]yyػg+ rοY L˓*eݻxnWxhx~5 !ӿn< /猸=Z?Ͻz.)bч~%} m5[úoSux||/q_ؾKROϢ*ƕ L;_ol@U;MWbL5 ?tg|!.8 bK=RjmvDg?W#׺uzG;Rws+y"̰7qܢX%zX˼ɸ[zFێzc#n2^~zqF'ecQTǡ8`L8-L6b)i]בԵ*B tѕҵrd!k+^Uߴ:WG'ն'pނ.vҧtJ Ob$Q]6*#_WN)UK'AUoz䬶FE}}YxH,t-*wUYv3žc\5Ok{OjZ;zհ+λ5[ OguІf̳}.p==:^'u[v}AaJ3y2ᚷpwY̴'W>=;^ޘ%k{B%!)xF-C t-VfC`թK(MqnMG)f%|+oOyW ;$ g:RHC'zz o\[X&(⮋sQ.*/rw“F~=Jf%_v$m10J׾tN=pí_lނkʤOIeЫz h`"~ ̼iyKn2 j"/ź*4\/g5zN~f(:mFIZo ]Dvm+C۞Сg?H5ly;(FF_v؀N>:pפ*+*T)_m9d$9SGIrt5]G`UHT{r $9IwnT{5>qťOBKYf 0[+.ׄ"6))JIPq#??ԈGQمe[$n y )Fk0H8IQ!9M!A6S[Ti8FgHnYb, !C I&ݲp"REޮ4&g,S$gD?TQ?U(WqӔ&QfBM "_%`?@w6' Kjv<Sڰ1c+t~hɡWĎY1(`]UH%:۾()UE/Kٿ{~&[qmx'+C yL] ^u !>K[G:^2:Ј33Ř=ЇbvN..ˠIuj9]wT*d:) CNtza s7i0 F.H%{4ʼn),~AGxy`q+B6)+ ,|NJW>s؉xqG:c*OK.zLZGZs8.J¦hIZ1'Q\di.C2hI#dw*vt.$T`]nĊu0;s*q-lq)FR\64wTqTT/LFX xl ;c btXMsWK-_1^>icH)wėsqٸ0BYrݬ\]O@N@_񮬫m[)ZMZmv9w5v`k܀ íxiϭI<}-[CG%|W|1S>Z`NF6b~2\4bX^`v$eT (GM>SO=ck0 [“*1oW6S>icDSK_{r!?ɡSTޕ}nѓ_ܹX&? *QѬS{ݝ1g,|ؒƞu+95&BF)_a]$^:Mmϼ4mP/ )2djB!vٓY/.9r2Pd-)o,GN{Qak 6mj Ny|LyG-l}@ZWr6}!b5 絀jOΛqPO~]t)8x'bR SgSNs}\|q׳REKO}&-J3,=2r8J38/Xvs 2Y2Jʿz he챕ؿ$ <Äco~03l#snv_pA9"_KIL6#8Vb_(3DO0q[ oZ#Z0%f?'`!3pj9{&0V'l\gN: dԘÏGS7o߾i3P4<Ͻ8xPsxixw޸ntn{);"%'4UHb:7,1OfB0N* K0qbI'G2^9mVĭU 08],gڇijruzND\g.84.4󼵫0u/ƌ_ʬ!U-ۜR:Wo򆢔`uepTI6WA|INM?+)_ޙL䳱\GUJP&@ ƹn]>?sQ1Os|2!LY\gpP?Mfk=r"?f9} 1qtxypgsĩdMW5H,\3jw EXH${>XH',OE8\/~(DO8$ē-4oa'Q&cy5`pij16Me3گ2%X{ʰP%AD)t K fp t oR!j+v/È#\JB-kVܰqS=hL:xɏ2M8q/~ l̃hFESSL'PRZG)ݞ q_vH3Jf&4/=*^)Dx4nGkNS-X?<_‡CFx~|Ч}z7tֻ1͸FxO0cS}$\3tZq]kOFk[nz6i9:\~ hU~#cک'ScvƁ[oEyK=PITf&{t Y[@PuH^4%ESj֩)sps8ҸRmM%( ,?/o’qIazYUWi3,SHFO,/P.dF_d[K=K*/i媚d7ZiĕL}']t܉GEώ]QOʅD,eK< 04Wɳ'!''$Qd吠NrKѐG|'L ZMVc3)!`+9d[M+j=ʼTJpƥ54Zjx5O YkVCв~9v~tOXс+swo6܈۱ݎ~`vx:Z|z2xDT$sѹ0rXEʟ%zF~Gΐ.0hT𢡼˩țP*4:=^3SK.AW % ;HT3g݅ϱ4}RLf<ek9:5G}Acr`k+a,@IDAT-į܄_fƙ-Ɠ^oV O耇;+ko]~B?SQqЈqx}&VYXzq'rw+;~;ׅ:=dWZ<39O϶Zmj2|$P‘(Ĩ, .+ mԭ/H(^;|^iWyD 1TKbmIfnv@Ύjx)6~:vHk5> 6D7.'a=_\c&?znW<2wxhD|9.\<Բ[RR! CG\RHZSֽT&J8A9=GF`14/oY 4j5-Z%pC~˻g4VV2`Af^spbv+\{Oiy K=RnOxhҴdf;ag%/jPWˮ:e|Zz__j}XIC%RzyUTD(sF3$Șd*&$~O )2nPQ}p5gC MSZ 2b3ıuIތWReu%= 4j.}o/N lYPq7.g\wzy^QFԡTz. 6r>aDR[z,iĚ M2H(`+Ar89`8IDvn8*$OGyUI/7WI7A]\e *6tYtuWŮ+ &=$IH&}?g}o{sfy<̙CXv9򴪓&JW٤!:됓Tѷ5+#ZoN|>]} ~3.".;Wqѧ_w[3zjU|~?x_ct&U:|a1nޑ}DDQ&te$1,,bݭ` nx HFAۮWXjΧ c-6!֝|Rfϫ, W`Q<"?0NNXJ*&QioK|{3z'3]JpUvA3?PЁ|5x۷qF=:mkAx8t~s*_K S٪QikƵUl!>(6 v׮իu֫ٝ&?H?^'jV,DOƇw~o;⁇*?a|wzDL=i5gIJ]X3}?K_yIw*/C:2-t2mtm'=FEʭZJ2|P.SZm~R#v-"n, aWx0(`"Dv*3Sj8dY,W.ęuWwyfF Cbwfg^b#}F흣M$ЎxmUgisHfwꢴHՁ{[ɝ'^<4ɩHN\e| t"?:R2p&K~.\Ls5۫N%-t=g$"/q+yDcu賈x{|?A\)L!Cx*.^k;ilxMڠy=lSκR&v+!Q?(%C!BNQײŸebf&*q -[r|˝ 뻹pմOZ)?`$T#W3xKX`xggΫ)+Wn n/[>kk[3@nyXi;0_oyv[1E'@W.:^]!-銼ΈMfȀ}!E]P,T\CV{Jq}"DCxc19K 2%^z"u:Fch5EsBz[#>ރi;oB{kg69sY uTY*m] ^Ypa^Q #\. Web"$m Юh&3; Z+iůt1[pi_ڡ4T4zE^K&M3~ʝǁ{7!~2??w:= hEy懟O_w'nccb`tlzQv xއCg zvWbLZЙ _iz[B&1MǽBRR8m:?mH2J e0wΜg/)[LkLQH(A~!֐z zenU FגV~T_!Ñ5|'+C I%0j:D)JU~q2JKTNA3'98G2\R^`:3f,:БE_}bձuH\IknbMw wZp( ti om)_1 F(39ߕ1':F(髐ea!1.w6V\;w7C%[`VZco`ЌiZm=ٸnPh[RX\s>0M I-[Ա\XK|ݟ/C"{X:H٧NڼEgxpwea\~oűeJ|˲x2_8]o>1I1ud㉮XԇU()i¾HZ,a<꺵*iW|OrҵZ^_Fw1ͤ*̙l@L|:uvOp%ia  4-p (p+eO*I}K#UѾV+]=#f~k{q~=Ls*?vz|S$^yTR 2Ѝtuo&l:<MܹzmpReWD[]"%%6׬V̙3[G >Ov+2'H[gMlxMߤWc)^_bUabT%Ee;=GNA(~\ʈhŻ`eq&+ G/<'M r@:p1|D^)D"[~X`a5R E>בZlJ49*Gac`CU4E75 7{Ti?=@JԈN7}^&q8av͂b`‡[}}5%#0QPaBP^+t@|:IrX~h\mBj~~IVMZV.9_Rg*GY36 DhX"vᙍk ETE:쏿7p]7{kCO=&:=-1gK[{ֻN6aU|aNڀ N#5iR5IoԕfK-|O3CѣتRtqk{5㌭ҕd aČz$}}pAUҎy@A!˸k$j / eLǧRj{PmU!́f[p+:$iEuFsXǂ}vtIK)2*I_@~)-a-c6R4  8w {⤻Ϛ&^zrqB ,uO" FcE άN~f^=5i@* -XvU1(2*5_K|n4UhܷKR&UPHm10ʶȌT"B[BN2١:`(* ׮jgN>1Ro8Νq6kvܵwmC]5AsöMQ#*Z3{.y'}Z6-]gJ9{`vJ+5LbOHq KK@u\k޾rgNvO\?Ex%?jWqw={mS_Uc>I]/#Vѹ~†:+F_YG=b> !}gᒭUm]#=^Mv4I^!c>Gyv1+Q\t}j7<23:1fiosFKȱ4T.#F \?wdL6-ie2ZR ۦ!KvzNf(]>ԱrL-m4"f'NTx4 Y{MuV|.?5繘묎ʋM ? u7LFrZ"_`It|`Aq|) /Ū#)/^CeN.%R52Rݳdt6[l:h{5!:(q?q)1lP)es)H:OpQF.i0 'ctI8%U"1cFjP+9GESڢN8N+:Dq32琌%ݮv]`W#ٵ nvo}%NwSo&ٛ5|#-^_Ͼ+Q"*:+N-"mtՀڔ61>І׻F VRg/dK(ރ81)-yT ی5,FCZNhWtqMZ۩@ {ۤJXZRBm亁5k0*9¤Њ6+脫IڑpIlxMd:G8uzӴU2`KO#o(AQtqF2(j  !JY? _(4эcdyah#9A@P/S0^Ow r91Zr8/JMD!aщ=RG ]AƄDoJMb&9LqaMlRd5n U\M+ ~ &@ܔ)b慚ݣen9$<߼Ofܹ݊HcJ:dZ#rÕ1˕*?>74Ee:ԣݲ Wؤ6- N8z뮋?^R3wV5T(|>dq}eGxЙQpp`W=܁ ϑ-2{ R4 PQ]ҾP"gLvX"4\4Ns<|xd tSX 1b&ZppJ{ƽ* Im^^Wxև vzhWR8 &jjǑ64K;[뚲3Ҿ/uKK[UnZ1CƦK㠃f^ֺW:!IÒ&'H{8 i-D@V 屠p^@=i-@svt hN1xk!EtC2 Y.~ߪkhTUP;T2ɧI-|c2ZkӉcewZy`_a%~K'٤)<Ԛ + 62Sb]GsL>UEg,0SɫHvj@Cg?X-ep=zM~%ܑLKX z>wv`ymњQ,%^3N*GPv§鄁'uӥcUg$ 8>O`\vJOCVzzflcZOW7:XRwW+Q> awU-*boɕ?fTmE?|CsM^LU')~kNV,v:ݨq_Zy:I{zM}-ur_l(+ + No/mI8ntGI.^?Gq9oԆzlò/TxƲoӐ5Z& a~uޑÁ^%K܉#=ܩQ>..EBƯAhoxcwڄ= {n &28E4][ҁ t 5Q3͜MYrA]̕|qs79Vj734ig$qłĴqqʫoK!a'.[g˒-[/|G zpji.^a~3]˽|Tjjs3њJfbJyȀopu%ZԵ=9赴ͪBLUtt1 RFSW;De6ffYkBe+!L;3X@),=og紑.e^2ay,trBƮ)9wr6mF,eNpy Q4B">-: ԤC~mC⓬Тb-®BPZq,jA/F_׾tIL;)u`cò+֭%kY+uH2 /Hkþ-xKEkV),ɸ`dUY V<wvd h整s)nA Lk_ϟn:}3qGXYְ^ _z*3I'57G֭:ОxO5SvY 3x.ޤwLr)Y3'U?X6yK8=W'/<.8-1zTU:ahmsp^QD]L[ WYzP~QFTJ"ˠ؞"~s${xFPXUr̬ "dfZNmYgŌ֝g)'/tY#64ݺk @Ǐ>K?ZW܉Jэ[O)[ wC\5%O{隞FQthq?pVy)E٨Aϊ?'cs՘+l$M-^;6MAvS˿yvT=.;,5z^(V՛Fʕkt-'KYt–ujJaQy~Zh}R~>SSz/Wƾ?ǜg /QŖ&li 4r^ 4As%H$/m}饗dSBv8y%[b8뛍)=]祉h]5yiwxGGH;e.8-iDqvqB~Si!>yM' ׄ=tY&3`G\֬];iWG .qvxsȪTAr6pOxΈlgL̕O-=HžSyGFt##IGr(Sh=bcΎ]tj'{0zY[21#M|O3?8MKU}Wb5Ə~7}Jm\{8Oi8GWsZBٳ //}rw!d8i@72H^왦 6pPhPDUV00jҚou |ͲÔ#F {p^',LuGVOvj59꒑҉ezqJ>bW{h$кV1S,Y;Soˬ؍)E;huvOGK 36TBb RFZxmg!&erGkCsAkZD7 Y mf3MwvP|k_wjT?fi۴®:]0[-·( {qq1Sb>3:ڛ϶w͋oջ~(?tLoŧG/p߈?.[^_xbɛt$qG/5>:֝xQ{Dڕj(0\G}kU=u]w/.߾{Ew7d~0ɼFٶEQ[pEP%<2\cp *m²Nފo)/\Vӱ#FԮUpނXi`0pK^"چ # O~LtP 8fXkݨZ.ʤV)7,{1/gzzݥ/ċ/mcG3CmJZi'62Y|=4ӡɩ0zw› .&鄮Bg5$U=V oq5_ZT_ Yh Tg;N}[0nmc9!i@Ȥ9 BsJʒ x3O[wW߮ӵMk ?~|ڕqaS{oO_|_݃owſ }8v8o-5+?~gѩљ?"-ߺ ƽC:j\I/˗$~(}qʩ'F^;3=sB={KQǷv.G:[R~cGVq YK;ЋxFNRx|;yUҾ8C=O^[kxٟcɜ;,{f6oBkѯo=F=Gfۻ~<fҚD{M\/?..ѫղgg|_㒃xzY{8,9ծ$'gJgK\l&<k&Z5,v/mrox\^>??& ^<5l 4(ܚI:ioV=!P6l;M1>/#o8Ôa=)C\[yE1 QX[Fg{xeSG9#=WMtlɻ;~ɘ7 gAzǥxIű^םO{b7iu,رkl86Ns/>2}Kx%D*  G'ў;7{N{}2:2 NQU󠑩BqUffAdI< %]F%tRn)bG[_/Kt$Esփ&LL%wLg%D%(1P=c:?xVtvzVC㷔$B,N^"@au~f+rtve@N|0+3=_cBbÜɱ?Jw}WŤw})grGq[>F:hls ,??Q3 ,^S7/_{1scyu2 څjҁ UV#{a*q6 w%J?0t>{te=KG*Z, 6Jv&&MMC42ڜ0p|S'OO]|^=='z`d&S:4hQvNzW㓧ݻk1j̀xU11~XLϋU1y֟8ZuzEWĪĦ؉K>~aL uZ̚9T֕&h P12& 0!76q_+;8\`x~YʹIZ`Sbk)|qIR@+7Â`;dP Ɋ]3NXEH'de~džc4Z\JOM>/;Ӱ\tSԏA 9!#R@m>'G}gTxg%S:Xm_$[_҂Đ|,|:;1dPX`6d#ZlԀi3'{k,7KfӨ۵Yq_j]+uKv`F*2vi.Y|!yen9{|%fٴ TIP^}GJz`1VNpvs@#PngDF#Fg@< f_ zZ>Mc9.1w{[C\8#7Dy>8aӿhċ}zܰnwÌ>[%+8t:TM'2s-Iaiq ^F/EWdE,|`{ap:k@NG'MGcZX LH QT:j=KQN0jU3yU Ty6L0*EWuL}yk'>2OXnj?!wE}FSc1b I @.4f1P!U,vx{q2HYq@*i|: &T+o5GE/eA{3ǐ52wԢgşN/~Ko>0 T'z?<qӥƀqED}2P'u.jT˿oySkq:Zځ*J_5Y-b<VX}/͔n"LĜ1}&i#+"2 >y?W vû10H$~(J4Mjҡ:Lxg|:ʮƑ?&B ABH):uc9$56hZU}kT=Or>=&vh|7-9xzoYo~nX{1p$yi0DcBʹ:#+j8Z,Wzu}8̚jYʟN13l'q[ha̚8dp6c^FӥލZxqg>ǍE@vL8eD1p:(0WeDeո맦N !K#A"}Q묑:D2iV\knR}ZU!L g?2ifSLZ]#:cÙ>Ƌn㵽1aiFN@Cw廹[u9~v /~>8{߽|uP5d:V@<ŜCu)h׫q ВCN?-&u8bƟğ&W\m[8^O;uD'&$93b1Z`*r N%嗖mS7kwe`~Zć.$@uB4a^p fm5'e>B4n-ߑ|O@րS` 6oOw&ksXA5LTulշ1p)a5[#ͼ mG!G>qa%C]ߢM=%>) kf**X:uG~ F:Rqڿ|6NвFyy{'u)zn\}XX_H'qpyDݩY5<]UUeq6d_=Ƥɓ<"MnD`Oqs3SW  76̕pɍc;Y> Ϛ@E|ē p9lԮ' ÝGǘ f3q{>#qJQVu֑m`{I]^1 nFu%h]V,#-*DubE#Fr\\r76ύR^;%Qp6?!~iƆYP咴|xK{T}= =:nq6/41:3V\ESiZk/=j':gtgv츖wKpQ4H'V;5zb1ãJu+Zf"|U挸%"we>0Aqp"zefםiG꫿96:(u\*4,;dՇZ̻$-[f#Zm(9S,eF׉Q'vc| 22и7+. -r.wأǍ^4!.{b=ޤFQ ݬ23 g{eP+g}Sq?[_uF oٸ.yR`ͦ{ Gُ>ܣx ^;{}8 K;wDg{RFo{q=Mnf0`6ޮ_atJv:TJ]"h@IDATj:B|DT;Y?0.3wv#wힸ7=;Jπ&D=86<1QyΡ -FӐf^tmGՄjz vm|\ʬƅ0g0s:qgI6Ņ;W~u֜YkԆ;^b;S4%*kI䪆E΀m7ȥP.{u!U&6xڠ=CY3v?Tc1nD6~@[m' F(φAUQ1hKύZA?m8v~jg= K`:0d]~l-!pn@BX0c`-yY %xI&x}bK7 t<.^Gvڗ4Á+6I\Sۆo`zbJ}s>z^͚]Xmn9FM1&!eF#>qmz9O80}bpeoe-0PqI56;LiK.5L(\T|M-<1t=.FS db ,_%%6r:&K|1OO2Z~w@jl w:n;+PskSZ`ʞR-QQf 1s? Np@Qk(ԶH^_%C72>4vnhi{hzQ4(Ua7u,յ.:ZxK8t&%o)cbw3b1U: z974ٴut{8O ޴f:Cɱ詞 jK~1iw}~ScM`']QIL g= 3˘6cIL1\v,ƾښc3X0 N6( ;J,^PŒ9Н-g ك=UzQgpхJφ,7pl|S'``.^6~vO'>F lI {rzݪK֔*V!kaOy @I_0<.#fUG̋U/:bv;NWǟ>-n/Mߜ3ldL{eN7K=$CU B"ֈOtГ YҝC͝AsNyڢcq'~NAoѯ9/w-):7ƥ(eV K",0At!ܢQI;ą|4Eq:{OΉ;{$y^<b5=ݑv fc]8zyP3 ? =u:mm 65ߦn%KgEbݺw|L8>PV'bMo]{|@6se%3( Se 6ԝxt7c vU]t:ZwՑFŀ6u9K'qtLaҮP:aΑӝ ZgwjH"5sptPO)/̪iFa]0F Ll2&RqT`[ڈfiYa (2.I:"Wy,fn +&?SHӬ %!n#L}Mv:b 6U&XTXJ h%9+I266xU+3E9 8m:)S&ơs}.;?jGƧUX/Z/tq}uvt?\怍,YCmձig}ٺQ0?F͌SzBYA#JF?Ύ5"M2NoGY@*% #dI-~"k)Jcmr"eázioi{Qx|GYn=e:;r4<1@g9kMH-}C43Kvj-v,:9l+e(M g%/2FW%;c<\S\Ԟ(ͽ.:PWg{LƼ cbCs ^Xrܨ6>зt0ui>@~oX^fNVEosп_LU;鎋S&i5\/LAA>']'04bj[Wm|뜽ⴣvaCL~wکoxg'@0&~Š&230Ã%:mh\gng˵} qօceSM$-/.PyQ::DӉ@8R]H5tӤuReΕLTEAa p0r+Vm%Rn&IK,UzÃfIi-|!~yst\)}+%0*Yй5!v^|v[ ɔlfCT]Tb F)GʛdyX3WdCڝ93veVC._XtVjk3*W,;`3:~Pd i{v 4Pn1dT#5͗y7taJv2CrLt)ah_-QjE)MgvFͺd/,FhGg4u*^Sg_غ gwMO5*~$)C8)oV ރg9\~Ձa'}!IB-X⼆WE3s#/ZΩ%&dfj|>יԿ55\0-ד^\=׹NS9#4:k)Ye#M+WsVmK4yHtWKI"2rGu[wx%K»#S':F|oG#֒<{d* 9*D6*/|)̝r9m7Qg͒M:vNa0A8RT>'^m#LVJ&? Iy,ҹr"1`?gB*l䚰e\+%BFT%!Lqv"1eU#Ќ*tUR)jEaJXn/q6/P}j\o+3,pVQRS5Ԇܒa迃 4!  ՝7wӮz^|tkMkϸ5{2Y'Jԉg~DFEqfJ\d3]e&ԔZݜhn%ªK}epyGeIC,q~>,/3 a,x,4#m͍'/q13c K'·JdV<+%Y^kHցq%~탔1B@MT]PI-dHdՋYě5貾ZNPT ȱߺ!WFE)x^s˭:^ 6+= 'h1nPr8EW:~SY Ƣu؋kbSGcRwQxaxS=g;M7=]GoN;˗-Ȓҍ> 2)V VZ FG:5 YSY"*3Q1~'YP |.ʔ'*yW<')x{`Ѡ<8$q۟I꫊NGRa3rrş\jN=*<$VTE"` xn<+MncD#O)I~gTދ_7$Ex8y{J3ĥ@01i48yPGL,dMg3[VZ~GpYQ{T'ƎrCO%hlKbPUt)/:Tq/OO&(y˟i.Nn>AoRqJ5 #[(r[X$_Rǝ?'HBuNkh3xM%ѡ**4;nGkVTSV͒Xc3N'N׌B2 Z\uQ%ˬ$p#u#k=b~q cڏ\C=VBo)ܛ85ش^Qӌ+ƋKV&Vx~qa; ^L{DO lGצgKiף78nq`]bKZBeΏef GsoY9H4hc#GmlPSkR(*_wǿ蕲4-iaJ݇4qϗG+)DG˖/[8ēӦD@xĄYCE"mSk<Ӛ^eP2*-m#8SxUPDY 9a%[ 9x W*)L󪑩n.i/2asI㋏u($MV96%qf`'d+bK* QP M*]aNB3+i||24u/<˭Hx"oi=SIq(*Ɓg`WF'hp&3­/|L'.lj`=~QECLFSu ,S~qw ⚴) P&~q< 䑂TXu6ݴgِ|U^3^-J *FDZ9wzaL eF@QH!YRN[H$>Qy pSҧj8Gxn%I sޑP! >U> s?OӸ1elȼōa1iԀcMIɪbkbkA~o6jfǎĠ <ցu6Jt`Ûm'*qOb]Pwl!"訞v.̝ !_Bm&(Ȱ˃ +ngQO3așpNf̬,_ G.xl[sjڌ{V =L^RЎd\I#! BFap Yg\6I e鈉+*^3Rtmb!v| ʗP F~6%xS`6P#WyUq6\Y:u O\ m"\d: *PI omdhϰm*"I lJd{7B:QBW!@1`5pP?RVMiOiS3h|8xS0H%kDLr }d]I~jX AKhuI-~ZRBZ[0Bڵ$-2)?& t7 )@dd3*R, q~4ߥtYXnP[{^"2HifC'u 굒H2]Eʪaìplߚ=3cjQwjظD:mQ5Ӥr^jy:NEX>F(tP$t'͉JݑF1S›wʾ*H,p!p^gxq'Piy=m*==;.x.1PQsYZbŸd0Yu8ĥ+VTi  @[JM+mo :lTLMҤ%j#sFTَL̋*+sD|!&Bca0ThvLѪQe.}_{u]}~&JMҸ8}PEU@(HmB@E`ъ6VEHikȴ$m^v'$M}ǽq1\{}$EY|{5c>Z{q¹В9VLI3&bn_2PZYLb`!+u@ @o2k싓H8y8v\yΎtpm?;qp-}qTqXY(6zZ {s{_s\E<%KX$Koknk6c3;_YkEf&͐[lE.}6p2Ë1tb8oUeᄱxcu֩x#2SOY'{ ?eedѳXa93ɣCw$a].EO-$(+QǾq3w_!6LU>u%u7 rKW}}]>73#J.ۯ}^ttֽ0Yrֻ#rm.p^ g_2\88~x1K~Vc[JXwG-12:>f:[h3B(ݗG8v]FM9Y̦p`ٵ˒7_ (I,ā=s^UF&o <J:87&0SqsaM_z_`Bk>+%|78;?$+㱞cċ,&Dܹ _8 ozm=,,Y썤[vN2Pۊu[6ttp~gc.[p|Y\k/'0Df^!R7_WRŘ]`*ׁIG^/,>cmlrl=&8s=4:Ҹ3\(mc?UL _tv0&13W^l}ϭo{CK r;|5^&|ZO&Ij>Aڥ\Ͳ&:^7GOo3{݅8V9)77"jGM4%U9Z͈T5C#=S`,od`Zqd-){RH' iJZ UW;uZJH[ܒ0Q9=夠(ü h\.1;]Xh[T3[\pգ}b %y*z'噆<.GF3,ε̧J_l6x4-`qqYyoܬ˖U4e4sVƏ?MJ"k`g]Ա$Fg\׶S{j_wuk׎@Nb&fa~mV2{+eO Y ͗k j7?/"޵ kxi~]ӌۘƅ77p{q?b;L6nE P,!n+.NxNr{I~&Nz~Ħ9IϮϱ:`kWӿ#=q;~Qzp45wQ2;uQ}8)Ш8lKXμ*@;3_q_H׃S␒+gcN& ͍}}nBf{w9uuF.}e摁}Gq_|vMAkfn5|la#q5Ztއ"2 NvYāuXm6q(`ù9g&WX뵁'ݷ@O|i\Xpc#6b*źfCµ/mmac ċyYƿK~rqtYVWޗ2'qȽu㋟1#!nᥦHN(h&'sv6I9|+&vX7g>5WȜS)TpfxCL1+q[\4=+O_ux.ac&3,"r.  `ytWc.ƾ)cl[_/b}8u=B8_P:OZOsxʿʿӹos?l=Pu`HU=Ij3KKcLX kxtcldt51fAՎ<$E4E㺕긊Zl&} NLS'icX#[2C~cٞuMt{]3QOۃ.$dB}U|-}#G%˱BƗ@E?6\h v{+||-yۖb(7\H;~!~ zY0'~}#\dGlzjuA?$*HJBpZ {6+Umgtn)p'J\(Gerl̬,:'(Tn퇥{7`Q>,m=;) i˂O@o sA?'RJ&1Z_~)<6,.gC?:j"`V /f躇Ilc|o,>ϞdEns[{q!~f5\8U<ՏFAgmgaǚ^jRYDZ4MqMLRs7&n " 7~0ޙ[!K- Mk[pX "yy+cA7%_d\ox~W%?:o.j}!̾x"&SR!=B}?gY|ªgIJ .c'~s&|3} ^y|^4^W"sMIoȪΏ7r5vSz8 ;  H//neX@K@TIT;fHAcЎ(F0 Ҭƃk-Yl CM2_q|޼*"}>)}7_ߡ/q=򲽋c"P@Zᢩe Gl#ff51cMlǤwvrːI]_O~`i14JtGfTAhLY8>13,DF;'?~K< ࡏ,9mY圶C)79~vͭea'UeU;&Թ% :*6ԭ ycIrl 䅿K9Rģ(e夆2Ii\־̦?+#(\E֧HJL{kXJXmd볲Q(勮n|,ISMT)`kJOKj`s[do?5}{ P]փֶK~f7'8K;bkCVy'VrOl%s/.V}a`ہa _ʟ2/?6n{;iwoIBf=0[x |iHE]̷*3k=$z j/acFVKPS{_Le3f^xlv3oׇ;?[=ΟmԢ0"X`NKliVz-i,{ԞBV\IV J_03 e>} c f-%yQ;ij|޾ e0 w0őϲA im%)f$ $≠!n18?v㍜CG4ΔSu'ʋb6ۥ~ϾJslV* yCLz׸ .90'8!XpSBA8rl_d>mqV:aO,aɬl!Ԗر%*cU57Lp8n8Q׃pW[Dr-B_ck(lHZ{u7"dEtV$sۿ3OW]kw0P0=y2"dW,q"/Z攽<؞%/q!IÞĉ ʽe #T#2S ]U, |Lm{uK3Lm=@FEBeAh-kw ő|z4¤a(`ʏ @6E&U;mM )&ގq_i/h%]~l8NJ$e@@[<.MDSTq gQOg= F׷뎛1؜=!ZⰂXCyꧧW+j94$ȀY0A{16 9xqecidށonX5Gt`PrС I%5Ĕ=AҁԎ1rPGu]4|A̚i Ddz@/+W{?9sb_4^oW>_Yxd+\|{L@2A768#B}ը" 1"nʳ`!$W^R>>||䃿:>gM7^7V?1@ү_ƅA Fcwp8R׈Z]!4gbZǤFM랦_?}Ȧ KD%#ā*c`6~ zeGQ`,F sQc"Ɗ:ۊh*pUe1tK]&l*;W~8εccPsjļ:/T40k!ScK( d' l. 6bkD.mעi+A騏f LO4Ntf823/U첮aV?yH%}[P\5a)_RIZR&(G)'51&Z.%!ub16niM۱cbs!* zۼ]NwZ]pȸX|7~øW|z|O n]mb1#B'XY,VHstls&g4O37yt\0d2?3JxdIj[rc>e[p 7?t|w[c(|a{g7mIs C"CC$#T/_:6SsPxܭa!B~8C9ymݝ#,m/v'Xgwb?uJ߃}>K8c}GL-̼O=P+_YMr8o6^7ycRoHhlo]tCTwXO wV-aOET IA] kSr(QÖNW2(cல2NecN!u0056Amd bAw}ŌzЪYG# lu"I[mj=4}gEw]`/K;vl|w7d)ߊ{Ua:El-t9kbR_ܧӸ[C-6,%q]K cq8å>5Tյo/1uh f]:c\1c 7iU EK@19gs?y۰|71|L߾6}b]j"4nCfGo[[%#-ޣKAal]m(ĺDž'6g<=}q+0zd9O }xmp>ᗲ $I'jGlRu{l;;()~B^'@f7 QDP5n <2m͂oNђu^TwLks>_6)c]LĎg&"W?9ik-V]# nr,BWYeve3$qwWHW;O0nPJ;z6:&Ǐ>Q%$A+ףNP&=]_oW]uIK27 n[?Oޫ.[`Ț{=v^9vgp0sY ?~;G&- z ?61 n .Ip?ՂmO4YV7+}8f`|Āִo$!$oQD_3kumRuEdVe638 T ?8VC?EN;oYZWz9uHIR.uλ[w[.#ZuDz7'EõaNd6o{ "0zbr^0M~~k+9ng]y.pkJƴlU& d%q2O\c#;pwޯRr8y~vaOeVJEqzftVnԡd-zɈ$#٨('mpL_xoXznin6}kY^pd|^xʸ#?~b\gìv|8ƩByKRYO8>yxwoq׿d|5eX|.6рJ"ZLLI?-C0 wۅ(:7optI6'yp/}TߔFGpRhb'GPRi20?GNov`$;e`H<$Z}mhOQmvVGSc$ۇ֦(a8s nQ4Wٞ4LWϨyK?^{qק>7>~ϧ/}#?7+byz6/O?ヵ}w'l\“uz놯f\}{'~+&~54bO>Cn#iktY<קo6ƍmA\8 =?+6XE֡z5ؘA=PЊqO\&qӚEMnj[0g:r_˹Է3ȑ6尹YT/LF ÷rV_u8¡6ޯo8Sy_g[M e W'OnGƵ^;.5ψy~m.(yJͳb',n{|W]6.$j|Iѥ(qa_x['pm١Բ թx"FBNoTfEEL8$s҂Z)7̼V[<&HlD%+e%$.v 4 xg y^J=|G)[-0 q6n<"9ԚYg? [zxͯןHK}P z6i}+qr].Q:n5.wgաn@f- vH,Db:HX(Zb`#l2oڦٶwch[qz{[:fK&):6߈{Z/ʥ:G{m$LǏB78pj-Zs` 6&`5|/˞=2x!I'OSNj>x)=SoQYv&9;SʩQq388?Nr15>q4[R>/ڳ/]uet3fs`S- zu.Aa=% Y,/%F=8s@s2ߵrY,N^eh,sq:YӬ^OK3sgװ+|<>5kx!ũ:vkH R - _תf]ϳuXgS.` 8x59 curator-apache-curator-2.7.1/curator-x-rpc/src/test/000077500000000000000000000000001245521677600223675ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/000077500000000000000000000000001245521677600233105ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/000077500000000000000000000000001245521677600240775ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/000077500000000000000000000000001245521677600253205ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/000077500000000000000000000000001245521677600267775ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/000077500000000000000000000000001245521677600307355ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/Acl.java000066400000000000000000000335141245521677600323050ustar00rootroot00000000000000/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Acl implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("Acl"); private static final org.apache.thrift.protocol.TField PERMS_FIELD_DESC = new org.apache.thrift.protocol.TField("perms", org.apache.thrift.protocol.TType.I32, (short)1); private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new AclStandardSchemeFactory()); schemes.put(TupleScheme.class, new AclTupleSchemeFactory()); } public int perms; // required public Id id; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PERMS((short)1, "perms"), ID((short)2, "id"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PERMS return PERMS; case 2: // ID return ID; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __PERMS_ISSET_ID = 0; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PERMS, new org.apache.thrift.meta_data.FieldMetaData("perms", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, Id.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(Acl.class, metaDataMap); } public Acl() { } public Acl( int perms, Id id) { this(); this.perms = perms; setPermsIsSet(true); this.id = id; } /** * Performs a deep copy on other. */ public Acl(Acl other) { __isset_bitfield = other.__isset_bitfield; this.perms = other.perms; if (other.isSetId()) { this.id = new Id(other.id); } } public Acl deepCopy() { return new Acl(this); } @Override public void clear() { setPermsIsSet(false); this.perms = 0; this.id = null; } public int getPerms() { return this.perms; } public Acl setPerms(int perms) { this.perms = perms; setPermsIsSet(true); return this; } public void unsetPerms() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __PERMS_ISSET_ID); } /** Returns true if field perms is set (has been assigned a value) and false otherwise */ public boolean isSetPerms() { return EncodingUtils.testBit(__isset_bitfield, __PERMS_ISSET_ID); } public void setPermsIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __PERMS_ISSET_ID, value); } public Id getId() { return this.id; } public Acl setId(Id id) { this.id = id; return this; } public void unsetId() { this.id = null; } /** Returns true if field id is set (has been assigned a value) and false otherwise */ public boolean isSetId() { return this.id != null; } public void setIdIsSet(boolean value) { if (!value) { this.id = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PERMS: if (value == null) { unsetPerms(); } else { setPerms((Integer)value); } break; case ID: if (value == null) { unsetId(); } else { setId((Id)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PERMS: return Integer.valueOf(getPerms()); case ID: return getId(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PERMS: return isSetPerms(); case ID: return isSetId(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof Acl) return this.equals((Acl)that); return false; } public boolean equals(Acl that) { if (that == null) return false; boolean this_present_perms = true; boolean that_present_perms = true; if (this_present_perms || that_present_perms) { if (!(this_present_perms && that_present_perms)) return false; if (this.perms != that.perms) return false; } boolean this_present_id = true && this.isSetId(); boolean that_present_id = true && that.isSetId(); if (this_present_id || that_present_id) { if (!(this_present_id && that_present_id)) return false; if (!this.id.equals(that.id)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(Acl other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetPerms()).compareTo(other.isSetPerms()); if (lastComparison != 0) { return lastComparison; } if (isSetPerms()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.perms, other.perms); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); if (lastComparison != 0) { return lastComparison; } if (isSetId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("Acl("); boolean first = true; sb.append("perms:"); sb.append(this.perms); first = false; if (!first) sb.append(", "); sb.append("id:"); if (this.id == null) { sb.append("null"); } else { sb.append(this.id); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (id != null) { id.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class AclStandardSchemeFactory implements SchemeFactory { public AclStandardScheme getScheme() { return new AclStandardScheme(); } } private static class AclStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, Acl struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PERMS if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.perms = iprot.readI32(); struct.setPermsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // ID if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.id = new Id(); struct.id.read(iprot); struct.setIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, Acl struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldBegin(PERMS_FIELD_DESC); oprot.writeI32(struct.perms); oprot.writeFieldEnd(); if (struct.id != null) { oprot.writeFieldBegin(ID_FIELD_DESC); struct.id.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class AclTupleSchemeFactory implements SchemeFactory { public AclTupleScheme getScheme() { return new AclTupleScheme(); } } private static class AclTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, Acl struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetPerms()) { optionals.set(0); } if (struct.isSetId()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetPerms()) { oprot.writeI32(struct.perms); } if (struct.isSetId()) { struct.id.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, Acl struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.perms = iprot.readI32(); struct.setPermsIsSet(true); } if (incoming.get(1)) { struct.id = new Id(); struct.id.read(iprot); struct.setIdIsSet(true); } } } } curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/ChildData.java000066400000000000000000000420461245521677600334230ustar00rootroot00000000000000/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ChildData implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ChildData"); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField STAT_FIELD_DESC = new org.apache.thrift.protocol.TField("stat", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final org.apache.thrift.protocol.TField DATA_FIELD_DESC = new org.apache.thrift.protocol.TField("data", org.apache.thrift.protocol.TType.STRING, (short)3); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new ChildDataStandardSchemeFactory()); schemes.put(TupleScheme.class, new ChildDataTupleSchemeFactory()); } public String path; // required public Stat stat; // required public ByteBuffer data; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PATH((short)1, "path"), STAT((short)2, "stat"), DATA((short)3, "data"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PATH return PATH; case 2: // STAT return STAT; case 3: // DATA return DATA; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.STAT, new org.apache.thrift.meta_data.FieldMetaData("stat", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, Stat.class))); tmpMap.put(_Fields.DATA, new org.apache.thrift.meta_data.FieldMetaData("data", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ChildData.class, metaDataMap); } public ChildData() { } public ChildData( String path, Stat stat, ByteBuffer data) { this(); this.path = path; this.stat = stat; this.data = data; } /** * Performs a deep copy on other. */ public ChildData(ChildData other) { if (other.isSetPath()) { this.path = other.path; } if (other.isSetStat()) { this.stat = new Stat(other.stat); } if (other.isSetData()) { this.data = org.apache.thrift.TBaseHelper.copyBinary(other.data); ; } } public ChildData deepCopy() { return new ChildData(this); } @Override public void clear() { this.path = null; this.stat = null; this.data = null; } public String getPath() { return this.path; } public ChildData setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public Stat getStat() { return this.stat; } public ChildData setStat(Stat stat) { this.stat = stat; return this; } public void unsetStat() { this.stat = null; } /** Returns true if field stat is set (has been assigned a value) and false otherwise */ public boolean isSetStat() { return this.stat != null; } public void setStatIsSet(boolean value) { if (!value) { this.stat = null; } } public byte[] getData() { setData(org.apache.thrift.TBaseHelper.rightSize(data)); return data == null ? null : data.array(); } public ByteBuffer bufferForData() { return data; } public ChildData setData(byte[] data) { setData(data == null ? (ByteBuffer)null : ByteBuffer.wrap(data)); return this; } public ChildData setData(ByteBuffer data) { this.data = data; return this; } public void unsetData() { this.data = null; } /** Returns true if field data is set (has been assigned a value) and false otherwise */ public boolean isSetData() { return this.data != null; } public void setDataIsSet(boolean value) { if (!value) { this.data = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; case STAT: if (value == null) { unsetStat(); } else { setStat((Stat)value); } break; case DATA: if (value == null) { unsetData(); } else { setData((ByteBuffer)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PATH: return getPath(); case STAT: return getStat(); case DATA: return getData(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PATH: return isSetPath(); case STAT: return isSetStat(); case DATA: return isSetData(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof ChildData) return this.equals((ChildData)that); return false; } public boolean equals(ChildData that) { if (that == null) return false; boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } boolean this_present_stat = true && this.isSetStat(); boolean that_present_stat = true && that.isSetStat(); if (this_present_stat || that_present_stat) { if (!(this_present_stat && that_present_stat)) return false; if (!this.stat.equals(that.stat)) return false; } boolean this_present_data = true && this.isSetData(); boolean that_present_data = true && that.isSetData(); if (this_present_data || that_present_data) { if (!(this_present_data && that_present_data)) return false; if (!this.data.equals(that.data)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(ChildData other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetStat()).compareTo(other.isSetStat()); if (lastComparison != 0) { return lastComparison; } if (isSetStat()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.stat, other.stat); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetData()).compareTo(other.isSetData()); if (lastComparison != 0) { return lastComparison; } if (isSetData()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.data, other.data); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("ChildData("); boolean first = true; sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; if (!first) sb.append(", "); sb.append("stat:"); if (this.stat == null) { sb.append("null"); } else { sb.append(this.stat); } first = false; if (!first) sb.append(", "); sb.append("data:"); if (this.data == null) { sb.append("null"); } else { org.apache.thrift.TBaseHelper.toString(this.data, sb); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (stat != null) { stat.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class ChildDataStandardSchemeFactory implements SchemeFactory { public ChildDataStandardScheme getScheme() { return new ChildDataStandardScheme(); } } private static class ChildDataStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, ChildData struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // STAT if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.stat = new Stat(); struct.stat.read(iprot); struct.setStatIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // DATA if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.data = iprot.readBinary(); struct.setDataIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, ChildData struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } if (struct.stat != null) { oprot.writeFieldBegin(STAT_FIELD_DESC); struct.stat.write(oprot); oprot.writeFieldEnd(); } if (struct.data != null) { oprot.writeFieldBegin(DATA_FIELD_DESC); oprot.writeBinary(struct.data); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class ChildDataTupleSchemeFactory implements SchemeFactory { public ChildDataTupleScheme getScheme() { return new ChildDataTupleScheme(); } } private static class ChildDataTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, ChildData struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetPath()) { optionals.set(0); } if (struct.isSetStat()) { optionals.set(1); } if (struct.isSetData()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetPath()) { oprot.writeString(struct.path); } if (struct.isSetStat()) { struct.stat.write(oprot); } if (struct.isSetData()) { oprot.writeBinary(struct.data); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, ChildData struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } if (incoming.get(1)) { struct.stat = new Stat(); struct.stat.read(iprot); struct.setStatIsSet(true); } if (incoming.get(2)) { struct.data = iprot.readBinary(); struct.setDataIsSet(true); } } } } CreateMode.java000066400000000000000000000020661245521677600335350ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import java.util.Map; import java.util.HashMap; import org.apache.thrift.TEnum; public enum CreateMode implements org.apache.thrift.TEnum { PERSISTENT(0), PERSISTENT_SEQUENTIAL(1), EPHEMERAL(2), EPHEMERAL_SEQUENTIAL(3); private final int value; private CreateMode(int value) { this.value = value; } /** * Get the integer value of this enum value, as defined in the Thrift IDL. */ public int getValue() { return value; } /** * Find a the enum type by its integer value, as defined in the Thrift IDL. * @return null if the value is not found. */ public static CreateMode findByValue(int value) { switch (value) { case 0: return PERSISTENT; case 1: return PERSISTENT_SEQUENTIAL; case 2: return EPHEMERAL; case 3: return EPHEMERAL_SEQUENTIAL; default: return null; } } } CreateSpec.java000066400000000000000000000772161245521677600335540ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CreateSpec implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("CreateSpec"); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField DATA_FIELD_DESC = new org.apache.thrift.protocol.TField("data", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField MODE_FIELD_DESC = new org.apache.thrift.protocol.TField("mode", org.apache.thrift.protocol.TType.I32, (short)3); private static final org.apache.thrift.protocol.TField ASYNC_CONTEXT_FIELD_DESC = new org.apache.thrift.protocol.TField("asyncContext", org.apache.thrift.protocol.TType.STRING, (short)4); private static final org.apache.thrift.protocol.TField COMPRESSED_FIELD_DESC = new org.apache.thrift.protocol.TField("compressed", org.apache.thrift.protocol.TType.BOOL, (short)5); private static final org.apache.thrift.protocol.TField CREATING_PARENTS_IF_NEEDED_FIELD_DESC = new org.apache.thrift.protocol.TField("creatingParentsIfNeeded", org.apache.thrift.protocol.TType.BOOL, (short)6); private static final org.apache.thrift.protocol.TField WITH_PROTECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("withProtection", org.apache.thrift.protocol.TType.BOOL, (short)7); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new CreateSpecStandardSchemeFactory()); schemes.put(TupleScheme.class, new CreateSpecTupleSchemeFactory()); } public String path; // required public ByteBuffer data; // required /** * * @see CreateMode */ public CreateMode mode; // required public String asyncContext; // required public boolean compressed; // required public boolean creatingParentsIfNeeded; // required public boolean withProtection; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PATH((short)1, "path"), DATA((short)2, "data"), /** * * @see CreateMode */ MODE((short)3, "mode"), ASYNC_CONTEXT((short)4, "asyncContext"), COMPRESSED((short)5, "compressed"), CREATING_PARENTS_IF_NEEDED((short)6, "creatingParentsIfNeeded"), WITH_PROTECTION((short)7, "withProtection"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PATH return PATH; case 2: // DATA return DATA; case 3: // MODE return MODE; case 4: // ASYNC_CONTEXT return ASYNC_CONTEXT; case 5: // COMPRESSED return COMPRESSED; case 6: // CREATING_PARENTS_IF_NEEDED return CREATING_PARENTS_IF_NEEDED; case 7: // WITH_PROTECTION return WITH_PROTECTION; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __COMPRESSED_ISSET_ID = 0; private static final int __CREATINGPARENTSIFNEEDED_ISSET_ID = 1; private static final int __WITHPROTECTION_ISSET_ID = 2; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.DATA, new org.apache.thrift.meta_data.FieldMetaData("data", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true))); tmpMap.put(_Fields.MODE, new org.apache.thrift.meta_data.FieldMetaData("mode", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, CreateMode.class))); tmpMap.put(_Fields.ASYNC_CONTEXT, new org.apache.thrift.meta_data.FieldMetaData("asyncContext", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.COMPRESSED, new org.apache.thrift.meta_data.FieldMetaData("compressed", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.CREATING_PARENTS_IF_NEEDED, new org.apache.thrift.meta_data.FieldMetaData("creatingParentsIfNeeded", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.WITH_PROTECTION, new org.apache.thrift.meta_data.FieldMetaData("withProtection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(CreateSpec.class, metaDataMap); } public CreateSpec() { } public CreateSpec( String path, ByteBuffer data, CreateMode mode, String asyncContext, boolean compressed, boolean creatingParentsIfNeeded, boolean withProtection) { this(); this.path = path; this.data = data; this.mode = mode; this.asyncContext = asyncContext; this.compressed = compressed; setCompressedIsSet(true); this.creatingParentsIfNeeded = creatingParentsIfNeeded; setCreatingParentsIfNeededIsSet(true); this.withProtection = withProtection; setWithProtectionIsSet(true); } /** * Performs a deep copy on other. */ public CreateSpec(CreateSpec other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetPath()) { this.path = other.path; } if (other.isSetData()) { this.data = org.apache.thrift.TBaseHelper.copyBinary(other.data); ; } if (other.isSetMode()) { this.mode = other.mode; } if (other.isSetAsyncContext()) { this.asyncContext = other.asyncContext; } this.compressed = other.compressed; this.creatingParentsIfNeeded = other.creatingParentsIfNeeded; this.withProtection = other.withProtection; } public CreateSpec deepCopy() { return new CreateSpec(this); } @Override public void clear() { this.path = null; this.data = null; this.mode = null; this.asyncContext = null; setCompressedIsSet(false); this.compressed = false; setCreatingParentsIfNeededIsSet(false); this.creatingParentsIfNeeded = false; setWithProtectionIsSet(false); this.withProtection = false; } public String getPath() { return this.path; } public CreateSpec setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public byte[] getData() { setData(org.apache.thrift.TBaseHelper.rightSize(data)); return data == null ? null : data.array(); } public ByteBuffer bufferForData() { return data; } public CreateSpec setData(byte[] data) { setData(data == null ? (ByteBuffer)null : ByteBuffer.wrap(data)); return this; } public CreateSpec setData(ByteBuffer data) { this.data = data; return this; } public void unsetData() { this.data = null; } /** Returns true if field data is set (has been assigned a value) and false otherwise */ public boolean isSetData() { return this.data != null; } public void setDataIsSet(boolean value) { if (!value) { this.data = null; } } /** * * @see CreateMode */ public CreateMode getMode() { return this.mode; } /** * * @see CreateMode */ public CreateSpec setMode(CreateMode mode) { this.mode = mode; return this; } public void unsetMode() { this.mode = null; } /** Returns true if field mode is set (has been assigned a value) and false otherwise */ public boolean isSetMode() { return this.mode != null; } public void setModeIsSet(boolean value) { if (!value) { this.mode = null; } } public String getAsyncContext() { return this.asyncContext; } public CreateSpec setAsyncContext(String asyncContext) { this.asyncContext = asyncContext; return this; } public void unsetAsyncContext() { this.asyncContext = null; } /** Returns true if field asyncContext is set (has been assigned a value) and false otherwise */ public boolean isSetAsyncContext() { return this.asyncContext != null; } public void setAsyncContextIsSet(boolean value) { if (!value) { this.asyncContext = null; } } public boolean isCompressed() { return this.compressed; } public CreateSpec setCompressed(boolean compressed) { this.compressed = compressed; setCompressedIsSet(true); return this; } public void unsetCompressed() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __COMPRESSED_ISSET_ID); } /** Returns true if field compressed is set (has been assigned a value) and false otherwise */ public boolean isSetCompressed() { return EncodingUtils.testBit(__isset_bitfield, __COMPRESSED_ISSET_ID); } public void setCompressedIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __COMPRESSED_ISSET_ID, value); } public boolean isCreatingParentsIfNeeded() { return this.creatingParentsIfNeeded; } public CreateSpec setCreatingParentsIfNeeded(boolean creatingParentsIfNeeded) { this.creatingParentsIfNeeded = creatingParentsIfNeeded; setCreatingParentsIfNeededIsSet(true); return this; } public void unsetCreatingParentsIfNeeded() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __CREATINGPARENTSIFNEEDED_ISSET_ID); } /** Returns true if field creatingParentsIfNeeded is set (has been assigned a value) and false otherwise */ public boolean isSetCreatingParentsIfNeeded() { return EncodingUtils.testBit(__isset_bitfield, __CREATINGPARENTSIFNEEDED_ISSET_ID); } public void setCreatingParentsIfNeededIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __CREATINGPARENTSIFNEEDED_ISSET_ID, value); } public boolean isWithProtection() { return this.withProtection; } public CreateSpec setWithProtection(boolean withProtection) { this.withProtection = withProtection; setWithProtectionIsSet(true); return this; } public void unsetWithProtection() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __WITHPROTECTION_ISSET_ID); } /** Returns true if field withProtection is set (has been assigned a value) and false otherwise */ public boolean isSetWithProtection() { return EncodingUtils.testBit(__isset_bitfield, __WITHPROTECTION_ISSET_ID); } public void setWithProtectionIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __WITHPROTECTION_ISSET_ID, value); } public void setFieldValue(_Fields field, Object value) { switch (field) { case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; case DATA: if (value == null) { unsetData(); } else { setData((ByteBuffer)value); } break; case MODE: if (value == null) { unsetMode(); } else { setMode((CreateMode)value); } break; case ASYNC_CONTEXT: if (value == null) { unsetAsyncContext(); } else { setAsyncContext((String)value); } break; case COMPRESSED: if (value == null) { unsetCompressed(); } else { setCompressed((Boolean)value); } break; case CREATING_PARENTS_IF_NEEDED: if (value == null) { unsetCreatingParentsIfNeeded(); } else { setCreatingParentsIfNeeded((Boolean)value); } break; case WITH_PROTECTION: if (value == null) { unsetWithProtection(); } else { setWithProtection((Boolean)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PATH: return getPath(); case DATA: return getData(); case MODE: return getMode(); case ASYNC_CONTEXT: return getAsyncContext(); case COMPRESSED: return Boolean.valueOf(isCompressed()); case CREATING_PARENTS_IF_NEEDED: return Boolean.valueOf(isCreatingParentsIfNeeded()); case WITH_PROTECTION: return Boolean.valueOf(isWithProtection()); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PATH: return isSetPath(); case DATA: return isSetData(); case MODE: return isSetMode(); case ASYNC_CONTEXT: return isSetAsyncContext(); case COMPRESSED: return isSetCompressed(); case CREATING_PARENTS_IF_NEEDED: return isSetCreatingParentsIfNeeded(); case WITH_PROTECTION: return isSetWithProtection(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof CreateSpec) return this.equals((CreateSpec)that); return false; } public boolean equals(CreateSpec that) { if (that == null) return false; boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } boolean this_present_data = true && this.isSetData(); boolean that_present_data = true && that.isSetData(); if (this_present_data || that_present_data) { if (!(this_present_data && that_present_data)) return false; if (!this.data.equals(that.data)) return false; } boolean this_present_mode = true && this.isSetMode(); boolean that_present_mode = true && that.isSetMode(); if (this_present_mode || that_present_mode) { if (!(this_present_mode && that_present_mode)) return false; if (!this.mode.equals(that.mode)) return false; } boolean this_present_asyncContext = true && this.isSetAsyncContext(); boolean that_present_asyncContext = true && that.isSetAsyncContext(); if (this_present_asyncContext || that_present_asyncContext) { if (!(this_present_asyncContext && that_present_asyncContext)) return false; if (!this.asyncContext.equals(that.asyncContext)) return false; } boolean this_present_compressed = true; boolean that_present_compressed = true; if (this_present_compressed || that_present_compressed) { if (!(this_present_compressed && that_present_compressed)) return false; if (this.compressed != that.compressed) return false; } boolean this_present_creatingParentsIfNeeded = true; boolean that_present_creatingParentsIfNeeded = true; if (this_present_creatingParentsIfNeeded || that_present_creatingParentsIfNeeded) { if (!(this_present_creatingParentsIfNeeded && that_present_creatingParentsIfNeeded)) return false; if (this.creatingParentsIfNeeded != that.creatingParentsIfNeeded) return false; } boolean this_present_withProtection = true; boolean that_present_withProtection = true; if (this_present_withProtection || that_present_withProtection) { if (!(this_present_withProtection && that_present_withProtection)) return false; if (this.withProtection != that.withProtection) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(CreateSpec other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetData()).compareTo(other.isSetData()); if (lastComparison != 0) { return lastComparison; } if (isSetData()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.data, other.data); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetMode()).compareTo(other.isSetMode()); if (lastComparison != 0) { return lastComparison; } if (isSetMode()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.mode, other.mode); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetAsyncContext()).compareTo(other.isSetAsyncContext()); if (lastComparison != 0) { return lastComparison; } if (isSetAsyncContext()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.asyncContext, other.asyncContext); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetCompressed()).compareTo(other.isSetCompressed()); if (lastComparison != 0) { return lastComparison; } if (isSetCompressed()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.compressed, other.compressed); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetCreatingParentsIfNeeded()).compareTo(other.isSetCreatingParentsIfNeeded()); if (lastComparison != 0) { return lastComparison; } if (isSetCreatingParentsIfNeeded()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.creatingParentsIfNeeded, other.creatingParentsIfNeeded); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetWithProtection()).compareTo(other.isSetWithProtection()); if (lastComparison != 0) { return lastComparison; } if (isSetWithProtection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.withProtection, other.withProtection); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("CreateSpec("); boolean first = true; sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; if (!first) sb.append(", "); sb.append("data:"); if (this.data == null) { sb.append("null"); } else { org.apache.thrift.TBaseHelper.toString(this.data, sb); } first = false; if (!first) sb.append(", "); sb.append("mode:"); if (this.mode == null) { sb.append("null"); } else { sb.append(this.mode); } first = false; if (!first) sb.append(", "); sb.append("asyncContext:"); if (this.asyncContext == null) { sb.append("null"); } else { sb.append(this.asyncContext); } first = false; if (!first) sb.append(", "); sb.append("compressed:"); sb.append(this.compressed); first = false; if (!first) sb.append(", "); sb.append("creatingParentsIfNeeded:"); sb.append(this.creatingParentsIfNeeded); first = false; if (!first) sb.append(", "); sb.append("withProtection:"); sb.append(this.withProtection); first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class CreateSpecStandardSchemeFactory implements SchemeFactory { public CreateSpecStandardScheme getScheme() { return new CreateSpecStandardScheme(); } } private static class CreateSpecStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, CreateSpec struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // DATA if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.data = iprot.readBinary(); struct.setDataIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // MODE if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.mode = CreateMode.findByValue(iprot.readI32()); struct.setModeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ASYNC_CONTEXT if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.asyncContext = iprot.readString(); struct.setAsyncContextIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // COMPRESSED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.compressed = iprot.readBool(); struct.setCompressedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // CREATING_PARENTS_IF_NEEDED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.creatingParentsIfNeeded = iprot.readBool(); struct.setCreatingParentsIfNeededIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 7: // WITH_PROTECTION if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.withProtection = iprot.readBool(); struct.setWithProtectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, CreateSpec struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } if (struct.data != null) { oprot.writeFieldBegin(DATA_FIELD_DESC); oprot.writeBinary(struct.data); oprot.writeFieldEnd(); } if (struct.mode != null) { oprot.writeFieldBegin(MODE_FIELD_DESC); oprot.writeI32(struct.mode.getValue()); oprot.writeFieldEnd(); } if (struct.asyncContext != null) { oprot.writeFieldBegin(ASYNC_CONTEXT_FIELD_DESC); oprot.writeString(struct.asyncContext); oprot.writeFieldEnd(); } oprot.writeFieldBegin(COMPRESSED_FIELD_DESC); oprot.writeBool(struct.compressed); oprot.writeFieldEnd(); oprot.writeFieldBegin(CREATING_PARENTS_IF_NEEDED_FIELD_DESC); oprot.writeBool(struct.creatingParentsIfNeeded); oprot.writeFieldEnd(); oprot.writeFieldBegin(WITH_PROTECTION_FIELD_DESC); oprot.writeBool(struct.withProtection); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class CreateSpecTupleSchemeFactory implements SchemeFactory { public CreateSpecTupleScheme getScheme() { return new CreateSpecTupleScheme(); } } private static class CreateSpecTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, CreateSpec struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetPath()) { optionals.set(0); } if (struct.isSetData()) { optionals.set(1); } if (struct.isSetMode()) { optionals.set(2); } if (struct.isSetAsyncContext()) { optionals.set(3); } if (struct.isSetCompressed()) { optionals.set(4); } if (struct.isSetCreatingParentsIfNeeded()) { optionals.set(5); } if (struct.isSetWithProtection()) { optionals.set(6); } oprot.writeBitSet(optionals, 7); if (struct.isSetPath()) { oprot.writeString(struct.path); } if (struct.isSetData()) { oprot.writeBinary(struct.data); } if (struct.isSetMode()) { oprot.writeI32(struct.mode.getValue()); } if (struct.isSetAsyncContext()) { oprot.writeString(struct.asyncContext); } if (struct.isSetCompressed()) { oprot.writeBool(struct.compressed); } if (struct.isSetCreatingParentsIfNeeded()) { oprot.writeBool(struct.creatingParentsIfNeeded); } if (struct.isSetWithProtection()) { oprot.writeBool(struct.withProtection); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, CreateSpec struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(7); if (incoming.get(0)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } if (incoming.get(1)) { struct.data = iprot.readBinary(); struct.setDataIsSet(true); } if (incoming.get(2)) { struct.mode = CreateMode.findByValue(iprot.readI32()); struct.setModeIsSet(true); } if (incoming.get(3)) { struct.asyncContext = iprot.readString(); struct.setAsyncContextIsSet(true); } if (incoming.get(4)) { struct.compressed = iprot.readBool(); struct.setCompressedIsSet(true); } if (incoming.get(5)) { struct.creatingParentsIfNeeded = iprot.readBool(); struct.setCreatingParentsIfNeededIsSet(true); } if (incoming.get(6)) { struct.withProtection = iprot.readBool(); struct.setWithProtectionIsSet(true); } } } } CuratorEvent.java000066400000000000000000001444701245521677600341540ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CuratorEvent implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("CuratorEvent"); private static final org.apache.thrift.protocol.TField TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("type", org.apache.thrift.protocol.TType.I32, (short)2); private static final org.apache.thrift.protocol.TField RESULT_CODE_FIELD_DESC = new org.apache.thrift.protocol.TField("resultCode", org.apache.thrift.protocol.TType.I32, (short)3); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)4); private static final org.apache.thrift.protocol.TField CONTEXT_FIELD_DESC = new org.apache.thrift.protocol.TField("context", org.apache.thrift.protocol.TType.STRING, (short)5); private static final org.apache.thrift.protocol.TField STAT_FIELD_DESC = new org.apache.thrift.protocol.TField("stat", org.apache.thrift.protocol.TType.STRUCT, (short)6); private static final org.apache.thrift.protocol.TField DATA_FIELD_DESC = new org.apache.thrift.protocol.TField("data", org.apache.thrift.protocol.TType.STRING, (short)7); private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)8); private static final org.apache.thrift.protocol.TField CHILDREN_FIELD_DESC = new org.apache.thrift.protocol.TField("children", org.apache.thrift.protocol.TType.LIST, (short)9); private static final org.apache.thrift.protocol.TField ACL_LIST_FIELD_DESC = new org.apache.thrift.protocol.TField("aclList", org.apache.thrift.protocol.TType.LIST, (short)10); private static final org.apache.thrift.protocol.TField WATCHED_EVENT_FIELD_DESC = new org.apache.thrift.protocol.TField("watchedEvent", org.apache.thrift.protocol.TType.STRUCT, (short)11); private static final org.apache.thrift.protocol.TField LEADER_EVENT_FIELD_DESC = new org.apache.thrift.protocol.TField("leaderEvent", org.apache.thrift.protocol.TType.STRUCT, (short)12); private static final org.apache.thrift.protocol.TField CHILDREN_CACHE_EVENT_FIELD_DESC = new org.apache.thrift.protocol.TField("childrenCacheEvent", org.apache.thrift.protocol.TType.STRUCT, (short)13); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new CuratorEventStandardSchemeFactory()); schemes.put(TupleScheme.class, new CuratorEventTupleSchemeFactory()); } /** * * @see CuratorEventType */ public CuratorEventType type; // required public int resultCode; // required public String path; // required public String context; // required public Stat stat; // required public ByteBuffer data; // required public String name; // required public List children; // required public List aclList; // required public WatchedEvent watchedEvent; // required public LeaderEvent leaderEvent; // required public PathChildrenCacheEvent childrenCacheEvent; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { /** * * @see CuratorEventType */ TYPE((short)2, "type"), RESULT_CODE((short)3, "resultCode"), PATH((short)4, "path"), CONTEXT((short)5, "context"), STAT((short)6, "stat"), DATA((short)7, "data"), NAME((short)8, "name"), CHILDREN((short)9, "children"), ACL_LIST((short)10, "aclList"), WATCHED_EVENT((short)11, "watchedEvent"), LEADER_EVENT((short)12, "leaderEvent"), CHILDREN_CACHE_EVENT((short)13, "childrenCacheEvent"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 2: // TYPE return TYPE; case 3: // RESULT_CODE return RESULT_CODE; case 4: // PATH return PATH; case 5: // CONTEXT return CONTEXT; case 6: // STAT return STAT; case 7: // DATA return DATA; case 8: // NAME return NAME; case 9: // CHILDREN return CHILDREN; case 10: // ACL_LIST return ACL_LIST; case 11: // WATCHED_EVENT return WATCHED_EVENT; case 12: // LEADER_EVENT return LEADER_EVENT; case 13: // CHILDREN_CACHE_EVENT return CHILDREN_CACHE_EVENT; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __RESULTCODE_ISSET_ID = 0; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.TYPE, new org.apache.thrift.meta_data.FieldMetaData("type", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, CuratorEventType.class))); tmpMap.put(_Fields.RESULT_CODE, new org.apache.thrift.meta_data.FieldMetaData("resultCode", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.CONTEXT, new org.apache.thrift.meta_data.FieldMetaData("context", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.STAT, new org.apache.thrift.meta_data.FieldMetaData("stat", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, Stat.class))); tmpMap.put(_Fields.DATA, new org.apache.thrift.meta_data.FieldMetaData("data", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true))); tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.CHILDREN, new org.apache.thrift.meta_data.FieldMetaData("children", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)))); tmpMap.put(_Fields.ACL_LIST, new org.apache.thrift.meta_data.FieldMetaData("aclList", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, Acl.class)))); tmpMap.put(_Fields.WATCHED_EVENT, new org.apache.thrift.meta_data.FieldMetaData("watchedEvent", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, WatchedEvent.class))); tmpMap.put(_Fields.LEADER_EVENT, new org.apache.thrift.meta_data.FieldMetaData("leaderEvent", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, LeaderEvent.class))); tmpMap.put(_Fields.CHILDREN_CACHE_EVENT, new org.apache.thrift.meta_data.FieldMetaData("childrenCacheEvent", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, PathChildrenCacheEvent.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(CuratorEvent.class, metaDataMap); } public CuratorEvent() { } public CuratorEvent( CuratorEventType type, int resultCode, String path, String context, Stat stat, ByteBuffer data, String name, List children, List aclList, WatchedEvent watchedEvent, LeaderEvent leaderEvent, PathChildrenCacheEvent childrenCacheEvent) { this(); this.type = type; this.resultCode = resultCode; setResultCodeIsSet(true); this.path = path; this.context = context; this.stat = stat; this.data = data; this.name = name; this.children = children; this.aclList = aclList; this.watchedEvent = watchedEvent; this.leaderEvent = leaderEvent; this.childrenCacheEvent = childrenCacheEvent; } /** * Performs a deep copy on other. */ public CuratorEvent(CuratorEvent other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetType()) { this.type = other.type; } this.resultCode = other.resultCode; if (other.isSetPath()) { this.path = other.path; } if (other.isSetContext()) { this.context = other.context; } if (other.isSetStat()) { this.stat = new Stat(other.stat); } if (other.isSetData()) { this.data = org.apache.thrift.TBaseHelper.copyBinary(other.data); ; } if (other.isSetName()) { this.name = other.name; } if (other.isSetChildren()) { List __this__children = new ArrayList(other.children); this.children = __this__children; } if (other.isSetAclList()) { List __this__aclList = new ArrayList(other.aclList.size()); for (Acl other_element : other.aclList) { __this__aclList.add(new Acl(other_element)); } this.aclList = __this__aclList; } if (other.isSetWatchedEvent()) { this.watchedEvent = new WatchedEvent(other.watchedEvent); } if (other.isSetLeaderEvent()) { this.leaderEvent = new LeaderEvent(other.leaderEvent); } if (other.isSetChildrenCacheEvent()) { this.childrenCacheEvent = new PathChildrenCacheEvent(other.childrenCacheEvent); } } public CuratorEvent deepCopy() { return new CuratorEvent(this); } @Override public void clear() { this.type = null; setResultCodeIsSet(false); this.resultCode = 0; this.path = null; this.context = null; this.stat = null; this.data = null; this.name = null; this.children = null; this.aclList = null; this.watchedEvent = null; this.leaderEvent = null; this.childrenCacheEvent = null; } /** * * @see CuratorEventType */ public CuratorEventType getType() { return this.type; } /** * * @see CuratorEventType */ public CuratorEvent setType(CuratorEventType type) { this.type = type; return this; } public void unsetType() { this.type = null; } /** Returns true if field type is set (has been assigned a value) and false otherwise */ public boolean isSetType() { return this.type != null; } public void setTypeIsSet(boolean value) { if (!value) { this.type = null; } } public int getResultCode() { return this.resultCode; } public CuratorEvent setResultCode(int resultCode) { this.resultCode = resultCode; setResultCodeIsSet(true); return this; } public void unsetResultCode() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __RESULTCODE_ISSET_ID); } /** Returns true if field resultCode is set (has been assigned a value) and false otherwise */ public boolean isSetResultCode() { return EncodingUtils.testBit(__isset_bitfield, __RESULTCODE_ISSET_ID); } public void setResultCodeIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __RESULTCODE_ISSET_ID, value); } public String getPath() { return this.path; } public CuratorEvent setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public String getContext() { return this.context; } public CuratorEvent setContext(String context) { this.context = context; return this; } public void unsetContext() { this.context = null; } /** Returns true if field context is set (has been assigned a value) and false otherwise */ public boolean isSetContext() { return this.context != null; } public void setContextIsSet(boolean value) { if (!value) { this.context = null; } } public Stat getStat() { return this.stat; } public CuratorEvent setStat(Stat stat) { this.stat = stat; return this; } public void unsetStat() { this.stat = null; } /** Returns true if field stat is set (has been assigned a value) and false otherwise */ public boolean isSetStat() { return this.stat != null; } public void setStatIsSet(boolean value) { if (!value) { this.stat = null; } } public byte[] getData() { setData(org.apache.thrift.TBaseHelper.rightSize(data)); return data == null ? null : data.array(); } public ByteBuffer bufferForData() { return data; } public CuratorEvent setData(byte[] data) { setData(data == null ? (ByteBuffer)null : ByteBuffer.wrap(data)); return this; } public CuratorEvent setData(ByteBuffer data) { this.data = data; return this; } public void unsetData() { this.data = null; } /** Returns true if field data is set (has been assigned a value) and false otherwise */ public boolean isSetData() { return this.data != null; } public void setDataIsSet(boolean value) { if (!value) { this.data = null; } } public String getName() { return this.name; } public CuratorEvent setName(String name) { this.name = name; return this; } public void unsetName() { this.name = null; } /** Returns true if field name is set (has been assigned a value) and false otherwise */ public boolean isSetName() { return this.name != null; } public void setNameIsSet(boolean value) { if (!value) { this.name = null; } } public int getChildrenSize() { return (this.children == null) ? 0 : this.children.size(); } public java.util.Iterator getChildrenIterator() { return (this.children == null) ? null : this.children.iterator(); } public void addToChildren(String elem) { if (this.children == null) { this.children = new ArrayList(); } this.children.add(elem); } public List getChildren() { return this.children; } public CuratorEvent setChildren(List children) { this.children = children; return this; } public void unsetChildren() { this.children = null; } /** Returns true if field children is set (has been assigned a value) and false otherwise */ public boolean isSetChildren() { return this.children != null; } public void setChildrenIsSet(boolean value) { if (!value) { this.children = null; } } public int getAclListSize() { return (this.aclList == null) ? 0 : this.aclList.size(); } public java.util.Iterator getAclListIterator() { return (this.aclList == null) ? null : this.aclList.iterator(); } public void addToAclList(Acl elem) { if (this.aclList == null) { this.aclList = new ArrayList(); } this.aclList.add(elem); } public List getAclList() { return this.aclList; } public CuratorEvent setAclList(List aclList) { this.aclList = aclList; return this; } public void unsetAclList() { this.aclList = null; } /** Returns true if field aclList is set (has been assigned a value) and false otherwise */ public boolean isSetAclList() { return this.aclList != null; } public void setAclListIsSet(boolean value) { if (!value) { this.aclList = null; } } public WatchedEvent getWatchedEvent() { return this.watchedEvent; } public CuratorEvent setWatchedEvent(WatchedEvent watchedEvent) { this.watchedEvent = watchedEvent; return this; } public void unsetWatchedEvent() { this.watchedEvent = null; } /** Returns true if field watchedEvent is set (has been assigned a value) and false otherwise */ public boolean isSetWatchedEvent() { return this.watchedEvent != null; } public void setWatchedEventIsSet(boolean value) { if (!value) { this.watchedEvent = null; } } public LeaderEvent getLeaderEvent() { return this.leaderEvent; } public CuratorEvent setLeaderEvent(LeaderEvent leaderEvent) { this.leaderEvent = leaderEvent; return this; } public void unsetLeaderEvent() { this.leaderEvent = null; } /** Returns true if field leaderEvent is set (has been assigned a value) and false otherwise */ public boolean isSetLeaderEvent() { return this.leaderEvent != null; } public void setLeaderEventIsSet(boolean value) { if (!value) { this.leaderEvent = null; } } public PathChildrenCacheEvent getChildrenCacheEvent() { return this.childrenCacheEvent; } public CuratorEvent setChildrenCacheEvent(PathChildrenCacheEvent childrenCacheEvent) { this.childrenCacheEvent = childrenCacheEvent; return this; } public void unsetChildrenCacheEvent() { this.childrenCacheEvent = null; } /** Returns true if field childrenCacheEvent is set (has been assigned a value) and false otherwise */ public boolean isSetChildrenCacheEvent() { return this.childrenCacheEvent != null; } public void setChildrenCacheEventIsSet(boolean value) { if (!value) { this.childrenCacheEvent = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case TYPE: if (value == null) { unsetType(); } else { setType((CuratorEventType)value); } break; case RESULT_CODE: if (value == null) { unsetResultCode(); } else { setResultCode((Integer)value); } break; case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; case CONTEXT: if (value == null) { unsetContext(); } else { setContext((String)value); } break; case STAT: if (value == null) { unsetStat(); } else { setStat((Stat)value); } break; case DATA: if (value == null) { unsetData(); } else { setData((ByteBuffer)value); } break; case NAME: if (value == null) { unsetName(); } else { setName((String)value); } break; case CHILDREN: if (value == null) { unsetChildren(); } else { setChildren((List)value); } break; case ACL_LIST: if (value == null) { unsetAclList(); } else { setAclList((List)value); } break; case WATCHED_EVENT: if (value == null) { unsetWatchedEvent(); } else { setWatchedEvent((WatchedEvent)value); } break; case LEADER_EVENT: if (value == null) { unsetLeaderEvent(); } else { setLeaderEvent((LeaderEvent)value); } break; case CHILDREN_CACHE_EVENT: if (value == null) { unsetChildrenCacheEvent(); } else { setChildrenCacheEvent((PathChildrenCacheEvent)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case TYPE: return getType(); case RESULT_CODE: return Integer.valueOf(getResultCode()); case PATH: return getPath(); case CONTEXT: return getContext(); case STAT: return getStat(); case DATA: return getData(); case NAME: return getName(); case CHILDREN: return getChildren(); case ACL_LIST: return getAclList(); case WATCHED_EVENT: return getWatchedEvent(); case LEADER_EVENT: return getLeaderEvent(); case CHILDREN_CACHE_EVENT: return getChildrenCacheEvent(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case TYPE: return isSetType(); case RESULT_CODE: return isSetResultCode(); case PATH: return isSetPath(); case CONTEXT: return isSetContext(); case STAT: return isSetStat(); case DATA: return isSetData(); case NAME: return isSetName(); case CHILDREN: return isSetChildren(); case ACL_LIST: return isSetAclList(); case WATCHED_EVENT: return isSetWatchedEvent(); case LEADER_EVENT: return isSetLeaderEvent(); case CHILDREN_CACHE_EVENT: return isSetChildrenCacheEvent(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof CuratorEvent) return this.equals((CuratorEvent)that); return false; } public boolean equals(CuratorEvent that) { if (that == null) return false; boolean this_present_type = true && this.isSetType(); boolean that_present_type = true && that.isSetType(); if (this_present_type || that_present_type) { if (!(this_present_type && that_present_type)) return false; if (!this.type.equals(that.type)) return false; } boolean this_present_resultCode = true; boolean that_present_resultCode = true; if (this_present_resultCode || that_present_resultCode) { if (!(this_present_resultCode && that_present_resultCode)) return false; if (this.resultCode != that.resultCode) return false; } boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } boolean this_present_context = true && this.isSetContext(); boolean that_present_context = true && that.isSetContext(); if (this_present_context || that_present_context) { if (!(this_present_context && that_present_context)) return false; if (!this.context.equals(that.context)) return false; } boolean this_present_stat = true && this.isSetStat(); boolean that_present_stat = true && that.isSetStat(); if (this_present_stat || that_present_stat) { if (!(this_present_stat && that_present_stat)) return false; if (!this.stat.equals(that.stat)) return false; } boolean this_present_data = true && this.isSetData(); boolean that_present_data = true && that.isSetData(); if (this_present_data || that_present_data) { if (!(this_present_data && that_present_data)) return false; if (!this.data.equals(that.data)) return false; } boolean this_present_name = true && this.isSetName(); boolean that_present_name = true && that.isSetName(); if (this_present_name || that_present_name) { if (!(this_present_name && that_present_name)) return false; if (!this.name.equals(that.name)) return false; } boolean this_present_children = true && this.isSetChildren(); boolean that_present_children = true && that.isSetChildren(); if (this_present_children || that_present_children) { if (!(this_present_children && that_present_children)) return false; if (!this.children.equals(that.children)) return false; } boolean this_present_aclList = true && this.isSetAclList(); boolean that_present_aclList = true && that.isSetAclList(); if (this_present_aclList || that_present_aclList) { if (!(this_present_aclList && that_present_aclList)) return false; if (!this.aclList.equals(that.aclList)) return false; } boolean this_present_watchedEvent = true && this.isSetWatchedEvent(); boolean that_present_watchedEvent = true && that.isSetWatchedEvent(); if (this_present_watchedEvent || that_present_watchedEvent) { if (!(this_present_watchedEvent && that_present_watchedEvent)) return false; if (!this.watchedEvent.equals(that.watchedEvent)) return false; } boolean this_present_leaderEvent = true && this.isSetLeaderEvent(); boolean that_present_leaderEvent = true && that.isSetLeaderEvent(); if (this_present_leaderEvent || that_present_leaderEvent) { if (!(this_present_leaderEvent && that_present_leaderEvent)) return false; if (!this.leaderEvent.equals(that.leaderEvent)) return false; } boolean this_present_childrenCacheEvent = true && this.isSetChildrenCacheEvent(); boolean that_present_childrenCacheEvent = true && that.isSetChildrenCacheEvent(); if (this_present_childrenCacheEvent || that_present_childrenCacheEvent) { if (!(this_present_childrenCacheEvent && that_present_childrenCacheEvent)) return false; if (!this.childrenCacheEvent.equals(that.childrenCacheEvent)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(CuratorEvent other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetType()).compareTo(other.isSetType()); if (lastComparison != 0) { return lastComparison; } if (isSetType()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.type, other.type); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetResultCode()).compareTo(other.isSetResultCode()); if (lastComparison != 0) { return lastComparison; } if (isSetResultCode()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.resultCode, other.resultCode); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetContext()).compareTo(other.isSetContext()); if (lastComparison != 0) { return lastComparison; } if (isSetContext()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.context, other.context); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetStat()).compareTo(other.isSetStat()); if (lastComparison != 0) { return lastComparison; } if (isSetStat()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.stat, other.stat); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetData()).compareTo(other.isSetData()); if (lastComparison != 0) { return lastComparison; } if (isSetData()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.data, other.data); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetName()).compareTo(other.isSetName()); if (lastComparison != 0) { return lastComparison; } if (isSetName()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetChildren()).compareTo(other.isSetChildren()); if (lastComparison != 0) { return lastComparison; } if (isSetChildren()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.children, other.children); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetAclList()).compareTo(other.isSetAclList()); if (lastComparison != 0) { return lastComparison; } if (isSetAclList()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.aclList, other.aclList); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetWatchedEvent()).compareTo(other.isSetWatchedEvent()); if (lastComparison != 0) { return lastComparison; } if (isSetWatchedEvent()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.watchedEvent, other.watchedEvent); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetLeaderEvent()).compareTo(other.isSetLeaderEvent()); if (lastComparison != 0) { return lastComparison; } if (isSetLeaderEvent()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.leaderEvent, other.leaderEvent); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetChildrenCacheEvent()).compareTo(other.isSetChildrenCacheEvent()); if (lastComparison != 0) { return lastComparison; } if (isSetChildrenCacheEvent()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.childrenCacheEvent, other.childrenCacheEvent); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("CuratorEvent("); boolean first = true; sb.append("type:"); if (this.type == null) { sb.append("null"); } else { sb.append(this.type); } first = false; if (!first) sb.append(", "); sb.append("resultCode:"); sb.append(this.resultCode); first = false; if (!first) sb.append(", "); sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; if (!first) sb.append(", "); sb.append("context:"); if (this.context == null) { sb.append("null"); } else { sb.append(this.context); } first = false; if (!first) sb.append(", "); sb.append("stat:"); if (this.stat == null) { sb.append("null"); } else { sb.append(this.stat); } first = false; if (!first) sb.append(", "); sb.append("data:"); if (this.data == null) { sb.append("null"); } else { org.apache.thrift.TBaseHelper.toString(this.data, sb); } first = false; if (!first) sb.append(", "); sb.append("name:"); if (this.name == null) { sb.append("null"); } else { sb.append(this.name); } first = false; if (!first) sb.append(", "); sb.append("children:"); if (this.children == null) { sb.append("null"); } else { sb.append(this.children); } first = false; if (!first) sb.append(", "); sb.append("aclList:"); if (this.aclList == null) { sb.append("null"); } else { sb.append(this.aclList); } first = false; if (!first) sb.append(", "); sb.append("watchedEvent:"); if (this.watchedEvent == null) { sb.append("null"); } else { sb.append(this.watchedEvent); } first = false; if (!first) sb.append(", "); sb.append("leaderEvent:"); if (this.leaderEvent == null) { sb.append("null"); } else { sb.append(this.leaderEvent); } first = false; if (!first) sb.append(", "); sb.append("childrenCacheEvent:"); if (this.childrenCacheEvent == null) { sb.append("null"); } else { sb.append(this.childrenCacheEvent); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (stat != null) { stat.validate(); } if (watchedEvent != null) { watchedEvent.validate(); } if (leaderEvent != null) { leaderEvent.validate(); } if (childrenCacheEvent != null) { childrenCacheEvent.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class CuratorEventStandardSchemeFactory implements SchemeFactory { public CuratorEventStandardScheme getScheme() { return new CuratorEventStandardScheme(); } } private static class CuratorEventStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, CuratorEvent struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 2: // TYPE if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.type = CuratorEventType.findByValue(iprot.readI32()); struct.setTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // RESULT_CODE if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.resultCode = iprot.readI32(); struct.setResultCodeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // CONTEXT if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.context = iprot.readString(); struct.setContextIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // STAT if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.stat = new Stat(); struct.stat.read(iprot); struct.setStatIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 7: // DATA if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.data = iprot.readBinary(); struct.setDataIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 8: // NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.name = iprot.readString(); struct.setNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 9: // CHILDREN if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list8 = iprot.readListBegin(); struct.children = new ArrayList(_list8.size); for (int _i9 = 0; _i9 < _list8.size; ++_i9) { String _elem10; _elem10 = iprot.readString(); struct.children.add(_elem10); } iprot.readListEnd(); } struct.setChildrenIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 10: // ACL_LIST if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list11 = iprot.readListBegin(); struct.aclList = new ArrayList(_list11.size); for (int _i12 = 0; _i12 < _list11.size; ++_i12) { Acl _elem13; _elem13 = new Acl(); _elem13.read(iprot); struct.aclList.add(_elem13); } iprot.readListEnd(); } struct.setAclListIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 11: // WATCHED_EVENT if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.watchedEvent = new WatchedEvent(); struct.watchedEvent.read(iprot); struct.setWatchedEventIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 12: // LEADER_EVENT if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.leaderEvent = new LeaderEvent(); struct.leaderEvent.read(iprot); struct.setLeaderEventIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 13: // CHILDREN_CACHE_EVENT if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.childrenCacheEvent = new PathChildrenCacheEvent(); struct.childrenCacheEvent.read(iprot); struct.setChildrenCacheEventIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, CuratorEvent struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.type != null) { oprot.writeFieldBegin(TYPE_FIELD_DESC); oprot.writeI32(struct.type.getValue()); oprot.writeFieldEnd(); } oprot.writeFieldBegin(RESULT_CODE_FIELD_DESC); oprot.writeI32(struct.resultCode); oprot.writeFieldEnd(); if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } if (struct.context != null) { oprot.writeFieldBegin(CONTEXT_FIELD_DESC); oprot.writeString(struct.context); oprot.writeFieldEnd(); } if (struct.stat != null) { oprot.writeFieldBegin(STAT_FIELD_DESC); struct.stat.write(oprot); oprot.writeFieldEnd(); } if (struct.data != null) { oprot.writeFieldBegin(DATA_FIELD_DESC); oprot.writeBinary(struct.data); oprot.writeFieldEnd(); } if (struct.name != null) { oprot.writeFieldBegin(NAME_FIELD_DESC); oprot.writeString(struct.name); oprot.writeFieldEnd(); } if (struct.children != null) { oprot.writeFieldBegin(CHILDREN_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, struct.children.size())); for (String _iter14 : struct.children) { oprot.writeString(_iter14); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } if (struct.aclList != null) { oprot.writeFieldBegin(ACL_LIST_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.aclList.size())); for (Acl _iter15 : struct.aclList) { _iter15.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } if (struct.watchedEvent != null) { oprot.writeFieldBegin(WATCHED_EVENT_FIELD_DESC); struct.watchedEvent.write(oprot); oprot.writeFieldEnd(); } if (struct.leaderEvent != null) { oprot.writeFieldBegin(LEADER_EVENT_FIELD_DESC); struct.leaderEvent.write(oprot); oprot.writeFieldEnd(); } if (struct.childrenCacheEvent != null) { oprot.writeFieldBegin(CHILDREN_CACHE_EVENT_FIELD_DESC); struct.childrenCacheEvent.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class CuratorEventTupleSchemeFactory implements SchemeFactory { public CuratorEventTupleScheme getScheme() { return new CuratorEventTupleScheme(); } } private static class CuratorEventTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, CuratorEvent struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetType()) { optionals.set(0); } if (struct.isSetResultCode()) { optionals.set(1); } if (struct.isSetPath()) { optionals.set(2); } if (struct.isSetContext()) { optionals.set(3); } if (struct.isSetStat()) { optionals.set(4); } if (struct.isSetData()) { optionals.set(5); } if (struct.isSetName()) { optionals.set(6); } if (struct.isSetChildren()) { optionals.set(7); } if (struct.isSetAclList()) { optionals.set(8); } if (struct.isSetWatchedEvent()) { optionals.set(9); } if (struct.isSetLeaderEvent()) { optionals.set(10); } if (struct.isSetChildrenCacheEvent()) { optionals.set(11); } oprot.writeBitSet(optionals, 12); if (struct.isSetType()) { oprot.writeI32(struct.type.getValue()); } if (struct.isSetResultCode()) { oprot.writeI32(struct.resultCode); } if (struct.isSetPath()) { oprot.writeString(struct.path); } if (struct.isSetContext()) { oprot.writeString(struct.context); } if (struct.isSetStat()) { struct.stat.write(oprot); } if (struct.isSetData()) { oprot.writeBinary(struct.data); } if (struct.isSetName()) { oprot.writeString(struct.name); } if (struct.isSetChildren()) { { oprot.writeI32(struct.children.size()); for (String _iter16 : struct.children) { oprot.writeString(_iter16); } } } if (struct.isSetAclList()) { { oprot.writeI32(struct.aclList.size()); for (Acl _iter17 : struct.aclList) { _iter17.write(oprot); } } } if (struct.isSetWatchedEvent()) { struct.watchedEvent.write(oprot); } if (struct.isSetLeaderEvent()) { struct.leaderEvent.write(oprot); } if (struct.isSetChildrenCacheEvent()) { struct.childrenCacheEvent.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, CuratorEvent struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(12); if (incoming.get(0)) { struct.type = CuratorEventType.findByValue(iprot.readI32()); struct.setTypeIsSet(true); } if (incoming.get(1)) { struct.resultCode = iprot.readI32(); struct.setResultCodeIsSet(true); } if (incoming.get(2)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } if (incoming.get(3)) { struct.context = iprot.readString(); struct.setContextIsSet(true); } if (incoming.get(4)) { struct.stat = new Stat(); struct.stat.read(iprot); struct.setStatIsSet(true); } if (incoming.get(5)) { struct.data = iprot.readBinary(); struct.setDataIsSet(true); } if (incoming.get(6)) { struct.name = iprot.readString(); struct.setNameIsSet(true); } if (incoming.get(7)) { { org.apache.thrift.protocol.TList _list18 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, iprot.readI32()); struct.children = new ArrayList(_list18.size); for (int _i19 = 0; _i19 < _list18.size; ++_i19) { String _elem20; _elem20 = iprot.readString(); struct.children.add(_elem20); } } struct.setChildrenIsSet(true); } if (incoming.get(8)) { { org.apache.thrift.protocol.TList _list21 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.aclList = new ArrayList(_list21.size); for (int _i22 = 0; _i22 < _list21.size; ++_i22) { Acl _elem23; _elem23 = new Acl(); _elem23.read(iprot); struct.aclList.add(_elem23); } } struct.setAclListIsSet(true); } if (incoming.get(9)) { struct.watchedEvent = new WatchedEvent(); struct.watchedEvent.read(iprot); struct.setWatchedEventIsSet(true); } if (incoming.get(10)) { struct.leaderEvent = new LeaderEvent(); struct.leaderEvent.read(iprot); struct.setLeaderEventIsSet(true); } if (incoming.get(11)) { struct.childrenCacheEvent = new PathChildrenCacheEvent(); struct.childrenCacheEvent.read(iprot); struct.setChildrenCacheEventIsSet(true); } } } } CuratorEventType.java000066400000000000000000000037501245521677600350110ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import java.util.Map; import java.util.HashMap; import org.apache.thrift.TEnum; public enum CuratorEventType implements org.apache.thrift.TEnum { PING(0), CREATE(1), DELETE(2), EXISTS(3), GET_DATA(4), SET_DATA(5), CHILDREN(6), SYNC(7), GET_ACL(8), SET_ACL(9), WATCHED(10), CLOSING(11), CONNECTION_CONNECTED(12), CONNECTION_SUSPENDED(13), CONNECTION_RECONNECTED(14), CONNECTION_LOST(15), CONNECTION_READ_ONLY(16), LEADER(17), PATH_CHILDREN_CACHE(18), NODE_CACHE(19); private final int value; private CuratorEventType(int value) { this.value = value; } /** * Get the integer value of this enum value, as defined in the Thrift IDL. */ public int getValue() { return value; } /** * Find a the enum type by its integer value, as defined in the Thrift IDL. * @return null if the value is not found. */ public static CuratorEventType findByValue(int value) { switch (value) { case 0: return PING; case 1: return CREATE; case 2: return DELETE; case 3: return EXISTS; case 4: return GET_DATA; case 5: return SET_DATA; case 6: return CHILDREN; case 7: return SYNC; case 8: return GET_ACL; case 9: return SET_ACL; case 10: return WATCHED; case 11: return CLOSING; case 12: return CONNECTION_CONNECTED; case 13: return CONNECTION_SUSPENDED; case 14: return CONNECTION_RECONNECTED; case 15: return CONNECTION_LOST; case 16: return CONNECTION_READ_ONLY; case 17: return LEADER; case 18: return PATH_CHILDREN_CACHE; case 19: return NODE_CACHE; default: return null; } } } CuratorException.java000066400000000000000000000544661245521677600350360ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CuratorException extends TException implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("CuratorException"); private static final org.apache.thrift.protocol.TField TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("type", org.apache.thrift.protocol.TType.I32, (short)1); private static final org.apache.thrift.protocol.TField ZOO_KEEPER_EXCEPTION_FIELD_DESC = new org.apache.thrift.protocol.TField("zooKeeperException", org.apache.thrift.protocol.TType.I32, (short)2); private static final org.apache.thrift.protocol.TField NODE_EXCEPTION_FIELD_DESC = new org.apache.thrift.protocol.TField("nodeException", org.apache.thrift.protocol.TType.I32, (short)3); private static final org.apache.thrift.protocol.TField MESSAGE_FIELD_DESC = new org.apache.thrift.protocol.TField("message", org.apache.thrift.protocol.TType.STRING, (short)4); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new CuratorExceptionStandardSchemeFactory()); schemes.put(TupleScheme.class, new CuratorExceptionTupleSchemeFactory()); } /** * * @see ExceptionType */ public ExceptionType type; // required /** * * @see ZooKeeperExceptionType */ public ZooKeeperExceptionType zooKeeperException; // required /** * * @see NodeExceptionType */ public NodeExceptionType nodeException; // required public String message; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { /** * * @see ExceptionType */ TYPE((short)1, "type"), /** * * @see ZooKeeperExceptionType */ ZOO_KEEPER_EXCEPTION((short)2, "zooKeeperException"), /** * * @see NodeExceptionType */ NODE_EXCEPTION((short)3, "nodeException"), MESSAGE((short)4, "message"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // TYPE return TYPE; case 2: // ZOO_KEEPER_EXCEPTION return ZOO_KEEPER_EXCEPTION; case 3: // NODE_EXCEPTION return NODE_EXCEPTION; case 4: // MESSAGE return MESSAGE; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.TYPE, new org.apache.thrift.meta_data.FieldMetaData("type", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, ExceptionType.class))); tmpMap.put(_Fields.ZOO_KEEPER_EXCEPTION, new org.apache.thrift.meta_data.FieldMetaData("zooKeeperException", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, ZooKeeperExceptionType.class))); tmpMap.put(_Fields.NODE_EXCEPTION, new org.apache.thrift.meta_data.FieldMetaData("nodeException", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, NodeExceptionType.class))); tmpMap.put(_Fields.MESSAGE, new org.apache.thrift.meta_data.FieldMetaData("message", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(CuratorException.class, metaDataMap); } public CuratorException() { } public CuratorException( ExceptionType type, ZooKeeperExceptionType zooKeeperException, NodeExceptionType nodeException, String message) { this(); this.type = type; this.zooKeeperException = zooKeeperException; this.nodeException = nodeException; this.message = message; } /** * Performs a deep copy on other. */ public CuratorException(CuratorException other) { if (other.isSetType()) { this.type = other.type; } if (other.isSetZooKeeperException()) { this.zooKeeperException = other.zooKeeperException; } if (other.isSetNodeException()) { this.nodeException = other.nodeException; } if (other.isSetMessage()) { this.message = other.message; } } public CuratorException deepCopy() { return new CuratorException(this); } @Override public void clear() { this.type = null; this.zooKeeperException = null; this.nodeException = null; this.message = null; } /** * * @see ExceptionType */ public ExceptionType getType() { return this.type; } /** * * @see ExceptionType */ public CuratorException setType(ExceptionType type) { this.type = type; return this; } public void unsetType() { this.type = null; } /** Returns true if field type is set (has been assigned a value) and false otherwise */ public boolean isSetType() { return this.type != null; } public void setTypeIsSet(boolean value) { if (!value) { this.type = null; } } /** * * @see ZooKeeperExceptionType */ public ZooKeeperExceptionType getZooKeeperException() { return this.zooKeeperException; } /** * * @see ZooKeeperExceptionType */ public CuratorException setZooKeeperException(ZooKeeperExceptionType zooKeeperException) { this.zooKeeperException = zooKeeperException; return this; } public void unsetZooKeeperException() { this.zooKeeperException = null; } /** Returns true if field zooKeeperException is set (has been assigned a value) and false otherwise */ public boolean isSetZooKeeperException() { return this.zooKeeperException != null; } public void setZooKeeperExceptionIsSet(boolean value) { if (!value) { this.zooKeeperException = null; } } /** * * @see NodeExceptionType */ public NodeExceptionType getNodeException() { return this.nodeException; } /** * * @see NodeExceptionType */ public CuratorException setNodeException(NodeExceptionType nodeException) { this.nodeException = nodeException; return this; } public void unsetNodeException() { this.nodeException = null; } /** Returns true if field nodeException is set (has been assigned a value) and false otherwise */ public boolean isSetNodeException() { return this.nodeException != null; } public void setNodeExceptionIsSet(boolean value) { if (!value) { this.nodeException = null; } } public String getMessage() { return this.message; } public CuratorException setMessage(String message) { this.message = message; return this; } public void unsetMessage() { this.message = null; } /** Returns true if field message is set (has been assigned a value) and false otherwise */ public boolean isSetMessage() { return this.message != null; } public void setMessageIsSet(boolean value) { if (!value) { this.message = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case TYPE: if (value == null) { unsetType(); } else { setType((ExceptionType)value); } break; case ZOO_KEEPER_EXCEPTION: if (value == null) { unsetZooKeeperException(); } else { setZooKeeperException((ZooKeeperExceptionType)value); } break; case NODE_EXCEPTION: if (value == null) { unsetNodeException(); } else { setNodeException((NodeExceptionType)value); } break; case MESSAGE: if (value == null) { unsetMessage(); } else { setMessage((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case TYPE: return getType(); case ZOO_KEEPER_EXCEPTION: return getZooKeeperException(); case NODE_EXCEPTION: return getNodeException(); case MESSAGE: return getMessage(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case TYPE: return isSetType(); case ZOO_KEEPER_EXCEPTION: return isSetZooKeeperException(); case NODE_EXCEPTION: return isSetNodeException(); case MESSAGE: return isSetMessage(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof CuratorException) return this.equals((CuratorException)that); return false; } public boolean equals(CuratorException that) { if (that == null) return false; boolean this_present_type = true && this.isSetType(); boolean that_present_type = true && that.isSetType(); if (this_present_type || that_present_type) { if (!(this_present_type && that_present_type)) return false; if (!this.type.equals(that.type)) return false; } boolean this_present_zooKeeperException = true && this.isSetZooKeeperException(); boolean that_present_zooKeeperException = true && that.isSetZooKeeperException(); if (this_present_zooKeeperException || that_present_zooKeeperException) { if (!(this_present_zooKeeperException && that_present_zooKeeperException)) return false; if (!this.zooKeeperException.equals(that.zooKeeperException)) return false; } boolean this_present_nodeException = true && this.isSetNodeException(); boolean that_present_nodeException = true && that.isSetNodeException(); if (this_present_nodeException || that_present_nodeException) { if (!(this_present_nodeException && that_present_nodeException)) return false; if (!this.nodeException.equals(that.nodeException)) return false; } boolean this_present_message = true && this.isSetMessage(); boolean that_present_message = true && that.isSetMessage(); if (this_present_message || that_present_message) { if (!(this_present_message && that_present_message)) return false; if (!this.message.equals(that.message)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(CuratorException other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetType()).compareTo(other.isSetType()); if (lastComparison != 0) { return lastComparison; } if (isSetType()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.type, other.type); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetZooKeeperException()).compareTo(other.isSetZooKeeperException()); if (lastComparison != 0) { return lastComparison; } if (isSetZooKeeperException()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.zooKeeperException, other.zooKeeperException); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetNodeException()).compareTo(other.isSetNodeException()); if (lastComparison != 0) { return lastComparison; } if (isSetNodeException()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.nodeException, other.nodeException); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetMessage()).compareTo(other.isSetMessage()); if (lastComparison != 0) { return lastComparison; } if (isSetMessage()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.message, other.message); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("CuratorException("); boolean first = true; sb.append("type:"); if (this.type == null) { sb.append("null"); } else { sb.append(this.type); } first = false; if (!first) sb.append(", "); sb.append("zooKeeperException:"); if (this.zooKeeperException == null) { sb.append("null"); } else { sb.append(this.zooKeeperException); } first = false; if (!first) sb.append(", "); sb.append("nodeException:"); if (this.nodeException == null) { sb.append("null"); } else { sb.append(this.nodeException); } first = false; if (!first) sb.append(", "); sb.append("message:"); if (this.message == null) { sb.append("null"); } else { sb.append(this.message); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class CuratorExceptionStandardSchemeFactory implements SchemeFactory { public CuratorExceptionStandardScheme getScheme() { return new CuratorExceptionStandardScheme(); } } private static class CuratorExceptionStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, CuratorException struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // TYPE if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.type = ExceptionType.findByValue(iprot.readI32()); struct.setTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // ZOO_KEEPER_EXCEPTION if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.zooKeeperException = ZooKeeperExceptionType.findByValue(iprot.readI32()); struct.setZooKeeperExceptionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // NODE_EXCEPTION if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.nodeException = NodeExceptionType.findByValue(iprot.readI32()); struct.setNodeExceptionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // MESSAGE if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.message = iprot.readString(); struct.setMessageIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, CuratorException struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.type != null) { oprot.writeFieldBegin(TYPE_FIELD_DESC); oprot.writeI32(struct.type.getValue()); oprot.writeFieldEnd(); } if (struct.zooKeeperException != null) { oprot.writeFieldBegin(ZOO_KEEPER_EXCEPTION_FIELD_DESC); oprot.writeI32(struct.zooKeeperException.getValue()); oprot.writeFieldEnd(); } if (struct.nodeException != null) { oprot.writeFieldBegin(NODE_EXCEPTION_FIELD_DESC); oprot.writeI32(struct.nodeException.getValue()); oprot.writeFieldEnd(); } if (struct.message != null) { oprot.writeFieldBegin(MESSAGE_FIELD_DESC); oprot.writeString(struct.message); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class CuratorExceptionTupleSchemeFactory implements SchemeFactory { public CuratorExceptionTupleScheme getScheme() { return new CuratorExceptionTupleScheme(); } } private static class CuratorExceptionTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, CuratorException struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetType()) { optionals.set(0); } if (struct.isSetZooKeeperException()) { optionals.set(1); } if (struct.isSetNodeException()) { optionals.set(2); } if (struct.isSetMessage()) { optionals.set(3); } oprot.writeBitSet(optionals, 4); if (struct.isSetType()) { oprot.writeI32(struct.type.getValue()); } if (struct.isSetZooKeeperException()) { oprot.writeI32(struct.zooKeeperException.getValue()); } if (struct.isSetNodeException()) { oprot.writeI32(struct.nodeException.getValue()); } if (struct.isSetMessage()) { oprot.writeString(struct.message); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, CuratorException struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(4); if (incoming.get(0)) { struct.type = ExceptionType.findByValue(iprot.readI32()); struct.setTypeIsSet(true); } if (incoming.get(1)) { struct.zooKeeperException = ZooKeeperExceptionType.findByValue(iprot.readI32()); struct.setZooKeeperExceptionIsSet(true); } if (incoming.get(2)) { struct.nodeException = NodeExceptionType.findByValue(iprot.readI32()); struct.setNodeExceptionIsSet(true); } if (incoming.get(3)) { struct.message = iprot.readString(); struct.setMessageIsSet(true); } } } } CuratorProjection.java000066400000000000000000000261031245521677600351770ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CuratorProjection implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("CuratorProjection"); private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.STRING, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new CuratorProjectionStandardSchemeFactory()); schemes.put(TupleScheme.class, new CuratorProjectionTupleSchemeFactory()); } public String id; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ID((short)1, "id"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // ID return ID; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(CuratorProjection.class, metaDataMap); } public CuratorProjection() { } public CuratorProjection( String id) { this(); this.id = id; } /** * Performs a deep copy on other. */ public CuratorProjection(CuratorProjection other) { if (other.isSetId()) { this.id = other.id; } } public CuratorProjection deepCopy() { return new CuratorProjection(this); } @Override public void clear() { this.id = null; } public String getId() { return this.id; } public CuratorProjection setId(String id) { this.id = id; return this; } public void unsetId() { this.id = null; } /** Returns true if field id is set (has been assigned a value) and false otherwise */ public boolean isSetId() { return this.id != null; } public void setIdIsSet(boolean value) { if (!value) { this.id = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case ID: if (value == null) { unsetId(); } else { setId((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case ID: return getId(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case ID: return isSetId(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof CuratorProjection) return this.equals((CuratorProjection)that); return false; } public boolean equals(CuratorProjection that) { if (that == null) return false; boolean this_present_id = true && this.isSetId(); boolean that_present_id = true && that.isSetId(); if (this_present_id || that_present_id) { if (!(this_present_id && that_present_id)) return false; if (!this.id.equals(that.id)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(CuratorProjection other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); if (lastComparison != 0) { return lastComparison; } if (isSetId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("CuratorProjection("); boolean first = true; sb.append("id:"); if (this.id == null) { sb.append("null"); } else { sb.append(this.id); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class CuratorProjectionStandardSchemeFactory implements SchemeFactory { public CuratorProjectionStandardScheme getScheme() { return new CuratorProjectionStandardScheme(); } } private static class CuratorProjectionStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, CuratorProjection struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.id = iprot.readString(); struct.setIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, CuratorProjection struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.id != null) { oprot.writeFieldBegin(ID_FIELD_DESC); oprot.writeString(struct.id); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class CuratorProjectionTupleSchemeFactory implements SchemeFactory { public CuratorProjectionTupleScheme getScheme() { return new CuratorProjectionTupleScheme(); } } private static class CuratorProjectionTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, CuratorProjection struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetId()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetId()) { oprot.writeString(struct.id); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, CuratorProjection struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.id = iprot.readString(); struct.setIdIsSet(true); } } } } CuratorService.java000066400000000000000000031524751245521677600345020ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CuratorService { public interface Iface { public OptionalLockProjection acquireLock(CuratorProjection projection, String path, int maxWaitMs) throws CuratorException, org.apache.thrift.TException; public List acquireSemaphore(CuratorProjection projection, String path, int acquireQty, int maxWaitMs, int maxLeases) throws CuratorException, org.apache.thrift.TException; public void closeCuratorProjection(CuratorProjection projection) throws org.apache.thrift.TException; public boolean closeGenericProjection(CuratorProjection projection, String id) throws CuratorException, org.apache.thrift.TException; public OptionalPath createNode(CuratorProjection projection, CreateSpec spec) throws CuratorException, org.apache.thrift.TException; public void deleteNode(CuratorProjection projection, DeleteSpec spec) throws CuratorException, org.apache.thrift.TException; public OptionalStat exists(CuratorProjection projection, ExistsSpec spec) throws CuratorException, org.apache.thrift.TException; public OptionalChildrenList getChildren(CuratorProjection projection, GetChildrenSpec spec) throws CuratorException, org.apache.thrift.TException; public OptionalData getData(CuratorProjection projection, GetDataSpec spec) throws CuratorException, org.apache.thrift.TException; public List getLeaderParticipants(CuratorProjection projection, LeaderProjection leaderProjection) throws CuratorException, org.apache.thrift.TException; public ChildData getNodeCacheData(CuratorProjection projection, NodeCacheProjection cacheProjection) throws CuratorException, org.apache.thrift.TException; public List getPathChildrenCacheData(CuratorProjection projection, PathChildrenCacheProjection cacheProjection) throws CuratorException, org.apache.thrift.TException; public ChildData getPathChildrenCacheDataForPath(CuratorProjection projection, PathChildrenCacheProjection cacheProjection, String path) throws CuratorException, org.apache.thrift.TException; public boolean isLeader(CuratorProjection projection, LeaderProjection leaderProjection) throws CuratorException, org.apache.thrift.TException; public CuratorProjection newCuratorProjection(String connectionName) throws CuratorException, org.apache.thrift.TException; public void pingCuratorProjection(CuratorProjection projection) throws org.apache.thrift.TException; public OptionalStat setData(CuratorProjection projection, SetDataSpec spec) throws CuratorException, org.apache.thrift.TException; public LeaderResult startLeaderSelector(CuratorProjection projection, String path, String participantId, int waitForLeadershipMs) throws CuratorException, org.apache.thrift.TException; public NodeCacheProjection startNodeCache(CuratorProjection projection, String path, boolean dataIsCompressed, boolean buildInitial) throws CuratorException, org.apache.thrift.TException; public PathChildrenCacheProjection startPathChildrenCache(CuratorProjection projection, String path, boolean cacheData, boolean dataIsCompressed, PathChildrenCacheStartMode startMode) throws CuratorException, org.apache.thrift.TException; public PersistentEphemeralNodeProjection startPersistentEphemeralNode(CuratorProjection projection, String path, ByteBuffer data, PersistentEphemeralNodeMode mode) throws CuratorException, org.apache.thrift.TException; public void sync(CuratorProjection projection, String path, String asyncContext) throws CuratorException, org.apache.thrift.TException; } public interface AsyncIface { public void acquireLock(CuratorProjection projection, String path, int maxWaitMs, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void acquireSemaphore(CuratorProjection projection, String path, int acquireQty, int maxWaitMs, int maxLeases, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void closeCuratorProjection(CuratorProjection projection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void closeGenericProjection(CuratorProjection projection, String id, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void createNode(CuratorProjection projection, CreateSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void deleteNode(CuratorProjection projection, DeleteSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void exists(CuratorProjection projection, ExistsSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void getChildren(CuratorProjection projection, GetChildrenSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void getData(CuratorProjection projection, GetDataSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void getLeaderParticipants(CuratorProjection projection, LeaderProjection leaderProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void getNodeCacheData(CuratorProjection projection, NodeCacheProjection cacheProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void getPathChildrenCacheData(CuratorProjection projection, PathChildrenCacheProjection cacheProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void getPathChildrenCacheDataForPath(CuratorProjection projection, PathChildrenCacheProjection cacheProjection, String path, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void isLeader(CuratorProjection projection, LeaderProjection leaderProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void newCuratorProjection(String connectionName, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void pingCuratorProjection(CuratorProjection projection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void setData(CuratorProjection projection, SetDataSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void startLeaderSelector(CuratorProjection projection, String path, String participantId, int waitForLeadershipMs, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void startNodeCache(CuratorProjection projection, String path, boolean dataIsCompressed, boolean buildInitial, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void startPathChildrenCache(CuratorProjection projection, String path, boolean cacheData, boolean dataIsCompressed, PathChildrenCacheStartMode startMode, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void startPersistentEphemeralNode(CuratorProjection projection, String path, ByteBuffer data, PersistentEphemeralNodeMode mode, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void sync(CuratorProjection projection, String path, String asyncContext, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; } public static class Client extends org.apache.thrift.TServiceClient implements Iface { public static class Factory implements org.apache.thrift.TServiceClientFactory { public Factory() {} public Client getClient(org.apache.thrift.protocol.TProtocol prot) { return new Client(prot); } public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { return new Client(iprot, oprot); } } public Client(org.apache.thrift.protocol.TProtocol prot) { super(prot, prot); } public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { super(iprot, oprot); } public OptionalLockProjection acquireLock(CuratorProjection projection, String path, int maxWaitMs) throws CuratorException, org.apache.thrift.TException { send_acquireLock(projection, path, maxWaitMs); return recv_acquireLock(); } public void send_acquireLock(CuratorProjection projection, String path, int maxWaitMs) throws org.apache.thrift.TException { acquireLock_args args = new acquireLock_args(); args.setProjection(projection); args.setPath(path); args.setMaxWaitMs(maxWaitMs); sendBase("acquireLock", args); } public OptionalLockProjection recv_acquireLock() throws CuratorException, org.apache.thrift.TException { acquireLock_result result = new acquireLock_result(); receiveBase(result, "acquireLock"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "acquireLock failed: unknown result"); } public List acquireSemaphore(CuratorProjection projection, String path, int acquireQty, int maxWaitMs, int maxLeases) throws CuratorException, org.apache.thrift.TException { send_acquireSemaphore(projection, path, acquireQty, maxWaitMs, maxLeases); return recv_acquireSemaphore(); } public void send_acquireSemaphore(CuratorProjection projection, String path, int acquireQty, int maxWaitMs, int maxLeases) throws org.apache.thrift.TException { acquireSemaphore_args args = new acquireSemaphore_args(); args.setProjection(projection); args.setPath(path); args.setAcquireQty(acquireQty); args.setMaxWaitMs(maxWaitMs); args.setMaxLeases(maxLeases); sendBase("acquireSemaphore", args); } public List recv_acquireSemaphore() throws CuratorException, org.apache.thrift.TException { acquireSemaphore_result result = new acquireSemaphore_result(); receiveBase(result, "acquireSemaphore"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "acquireSemaphore failed: unknown result"); } public void closeCuratorProjection(CuratorProjection projection) throws org.apache.thrift.TException { send_closeCuratorProjection(projection); recv_closeCuratorProjection(); } public void send_closeCuratorProjection(CuratorProjection projection) throws org.apache.thrift.TException { closeCuratorProjection_args args = new closeCuratorProjection_args(); args.setProjection(projection); sendBase("closeCuratorProjection", args); } public void recv_closeCuratorProjection() throws org.apache.thrift.TException { closeCuratorProjection_result result = new closeCuratorProjection_result(); receiveBase(result, "closeCuratorProjection"); return; } public boolean closeGenericProjection(CuratorProjection projection, String id) throws CuratorException, org.apache.thrift.TException { send_closeGenericProjection(projection, id); return recv_closeGenericProjection(); } public void send_closeGenericProjection(CuratorProjection projection, String id) throws org.apache.thrift.TException { closeGenericProjection_args args = new closeGenericProjection_args(); args.setProjection(projection); args.setId(id); sendBase("closeGenericProjection", args); } public boolean recv_closeGenericProjection() throws CuratorException, org.apache.thrift.TException { closeGenericProjection_result result = new closeGenericProjection_result(); receiveBase(result, "closeGenericProjection"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "closeGenericProjection failed: unknown result"); } public OptionalPath createNode(CuratorProjection projection, CreateSpec spec) throws CuratorException, org.apache.thrift.TException { send_createNode(projection, spec); return recv_createNode(); } public void send_createNode(CuratorProjection projection, CreateSpec spec) throws org.apache.thrift.TException { createNode_args args = new createNode_args(); args.setProjection(projection); args.setSpec(spec); sendBase("createNode", args); } public OptionalPath recv_createNode() throws CuratorException, org.apache.thrift.TException { createNode_result result = new createNode_result(); receiveBase(result, "createNode"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "createNode failed: unknown result"); } public void deleteNode(CuratorProjection projection, DeleteSpec spec) throws CuratorException, org.apache.thrift.TException { send_deleteNode(projection, spec); recv_deleteNode(); } public void send_deleteNode(CuratorProjection projection, DeleteSpec spec) throws org.apache.thrift.TException { deleteNode_args args = new deleteNode_args(); args.setProjection(projection); args.setSpec(spec); sendBase("deleteNode", args); } public void recv_deleteNode() throws CuratorException, org.apache.thrift.TException { deleteNode_result result = new deleteNode_result(); receiveBase(result, "deleteNode"); if (result.ex1 != null) { throw result.ex1; } return; } public OptionalStat exists(CuratorProjection projection, ExistsSpec spec) throws CuratorException, org.apache.thrift.TException { send_exists(projection, spec); return recv_exists(); } public void send_exists(CuratorProjection projection, ExistsSpec spec) throws org.apache.thrift.TException { exists_args args = new exists_args(); args.setProjection(projection); args.setSpec(spec); sendBase("exists", args); } public OptionalStat recv_exists() throws CuratorException, org.apache.thrift.TException { exists_result result = new exists_result(); receiveBase(result, "exists"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "exists failed: unknown result"); } public OptionalChildrenList getChildren(CuratorProjection projection, GetChildrenSpec spec) throws CuratorException, org.apache.thrift.TException { send_getChildren(projection, spec); return recv_getChildren(); } public void send_getChildren(CuratorProjection projection, GetChildrenSpec spec) throws org.apache.thrift.TException { getChildren_args args = new getChildren_args(); args.setProjection(projection); args.setSpec(spec); sendBase("getChildren", args); } public OptionalChildrenList recv_getChildren() throws CuratorException, org.apache.thrift.TException { getChildren_result result = new getChildren_result(); receiveBase(result, "getChildren"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getChildren failed: unknown result"); } public OptionalData getData(CuratorProjection projection, GetDataSpec spec) throws CuratorException, org.apache.thrift.TException { send_getData(projection, spec); return recv_getData(); } public void send_getData(CuratorProjection projection, GetDataSpec spec) throws org.apache.thrift.TException { getData_args args = new getData_args(); args.setProjection(projection); args.setSpec(spec); sendBase("getData", args); } public OptionalData recv_getData() throws CuratorException, org.apache.thrift.TException { getData_result result = new getData_result(); receiveBase(result, "getData"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getData failed: unknown result"); } public List getLeaderParticipants(CuratorProjection projection, LeaderProjection leaderProjection) throws CuratorException, org.apache.thrift.TException { send_getLeaderParticipants(projection, leaderProjection); return recv_getLeaderParticipants(); } public void send_getLeaderParticipants(CuratorProjection projection, LeaderProjection leaderProjection) throws org.apache.thrift.TException { getLeaderParticipants_args args = new getLeaderParticipants_args(); args.setProjection(projection); args.setLeaderProjection(leaderProjection); sendBase("getLeaderParticipants", args); } public List recv_getLeaderParticipants() throws CuratorException, org.apache.thrift.TException { getLeaderParticipants_result result = new getLeaderParticipants_result(); receiveBase(result, "getLeaderParticipants"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getLeaderParticipants failed: unknown result"); } public ChildData getNodeCacheData(CuratorProjection projection, NodeCacheProjection cacheProjection) throws CuratorException, org.apache.thrift.TException { send_getNodeCacheData(projection, cacheProjection); return recv_getNodeCacheData(); } public void send_getNodeCacheData(CuratorProjection projection, NodeCacheProjection cacheProjection) throws org.apache.thrift.TException { getNodeCacheData_args args = new getNodeCacheData_args(); args.setProjection(projection); args.setCacheProjection(cacheProjection); sendBase("getNodeCacheData", args); } public ChildData recv_getNodeCacheData() throws CuratorException, org.apache.thrift.TException { getNodeCacheData_result result = new getNodeCacheData_result(); receiveBase(result, "getNodeCacheData"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getNodeCacheData failed: unknown result"); } public List getPathChildrenCacheData(CuratorProjection projection, PathChildrenCacheProjection cacheProjection) throws CuratorException, org.apache.thrift.TException { send_getPathChildrenCacheData(projection, cacheProjection); return recv_getPathChildrenCacheData(); } public void send_getPathChildrenCacheData(CuratorProjection projection, PathChildrenCacheProjection cacheProjection) throws org.apache.thrift.TException { getPathChildrenCacheData_args args = new getPathChildrenCacheData_args(); args.setProjection(projection); args.setCacheProjection(cacheProjection); sendBase("getPathChildrenCacheData", args); } public List recv_getPathChildrenCacheData() throws CuratorException, org.apache.thrift.TException { getPathChildrenCacheData_result result = new getPathChildrenCacheData_result(); receiveBase(result, "getPathChildrenCacheData"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getPathChildrenCacheData failed: unknown result"); } public ChildData getPathChildrenCacheDataForPath(CuratorProjection projection, PathChildrenCacheProjection cacheProjection, String path) throws CuratorException, org.apache.thrift.TException { send_getPathChildrenCacheDataForPath(projection, cacheProjection, path); return recv_getPathChildrenCacheDataForPath(); } public void send_getPathChildrenCacheDataForPath(CuratorProjection projection, PathChildrenCacheProjection cacheProjection, String path) throws org.apache.thrift.TException { getPathChildrenCacheDataForPath_args args = new getPathChildrenCacheDataForPath_args(); args.setProjection(projection); args.setCacheProjection(cacheProjection); args.setPath(path); sendBase("getPathChildrenCacheDataForPath", args); } public ChildData recv_getPathChildrenCacheDataForPath() throws CuratorException, org.apache.thrift.TException { getPathChildrenCacheDataForPath_result result = new getPathChildrenCacheDataForPath_result(); receiveBase(result, "getPathChildrenCacheDataForPath"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getPathChildrenCacheDataForPath failed: unknown result"); } public boolean isLeader(CuratorProjection projection, LeaderProjection leaderProjection) throws CuratorException, org.apache.thrift.TException { send_isLeader(projection, leaderProjection); return recv_isLeader(); } public void send_isLeader(CuratorProjection projection, LeaderProjection leaderProjection) throws org.apache.thrift.TException { isLeader_args args = new isLeader_args(); args.setProjection(projection); args.setLeaderProjection(leaderProjection); sendBase("isLeader", args); } public boolean recv_isLeader() throws CuratorException, org.apache.thrift.TException { isLeader_result result = new isLeader_result(); receiveBase(result, "isLeader"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "isLeader failed: unknown result"); } public CuratorProjection newCuratorProjection(String connectionName) throws CuratorException, org.apache.thrift.TException { send_newCuratorProjection(connectionName); return recv_newCuratorProjection(); } public void send_newCuratorProjection(String connectionName) throws org.apache.thrift.TException { newCuratorProjection_args args = new newCuratorProjection_args(); args.setConnectionName(connectionName); sendBase("newCuratorProjection", args); } public CuratorProjection recv_newCuratorProjection() throws CuratorException, org.apache.thrift.TException { newCuratorProjection_result result = new newCuratorProjection_result(); receiveBase(result, "newCuratorProjection"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "newCuratorProjection failed: unknown result"); } public void pingCuratorProjection(CuratorProjection projection) throws org.apache.thrift.TException { send_pingCuratorProjection(projection); } public void send_pingCuratorProjection(CuratorProjection projection) throws org.apache.thrift.TException { pingCuratorProjection_args args = new pingCuratorProjection_args(); args.setProjection(projection); sendBase("pingCuratorProjection", args); } public OptionalStat setData(CuratorProjection projection, SetDataSpec spec) throws CuratorException, org.apache.thrift.TException { send_setData(projection, spec); return recv_setData(); } public void send_setData(CuratorProjection projection, SetDataSpec spec) throws org.apache.thrift.TException { setData_args args = new setData_args(); args.setProjection(projection); args.setSpec(spec); sendBase("setData", args); } public OptionalStat recv_setData() throws CuratorException, org.apache.thrift.TException { setData_result result = new setData_result(); receiveBase(result, "setData"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "setData failed: unknown result"); } public LeaderResult startLeaderSelector(CuratorProjection projection, String path, String participantId, int waitForLeadershipMs) throws CuratorException, org.apache.thrift.TException { send_startLeaderSelector(projection, path, participantId, waitForLeadershipMs); return recv_startLeaderSelector(); } public void send_startLeaderSelector(CuratorProjection projection, String path, String participantId, int waitForLeadershipMs) throws org.apache.thrift.TException { startLeaderSelector_args args = new startLeaderSelector_args(); args.setProjection(projection); args.setPath(path); args.setParticipantId(participantId); args.setWaitForLeadershipMs(waitForLeadershipMs); sendBase("startLeaderSelector", args); } public LeaderResult recv_startLeaderSelector() throws CuratorException, org.apache.thrift.TException { startLeaderSelector_result result = new startLeaderSelector_result(); receiveBase(result, "startLeaderSelector"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "startLeaderSelector failed: unknown result"); } public NodeCacheProjection startNodeCache(CuratorProjection projection, String path, boolean dataIsCompressed, boolean buildInitial) throws CuratorException, org.apache.thrift.TException { send_startNodeCache(projection, path, dataIsCompressed, buildInitial); return recv_startNodeCache(); } public void send_startNodeCache(CuratorProjection projection, String path, boolean dataIsCompressed, boolean buildInitial) throws org.apache.thrift.TException { startNodeCache_args args = new startNodeCache_args(); args.setProjection(projection); args.setPath(path); args.setDataIsCompressed(dataIsCompressed); args.setBuildInitial(buildInitial); sendBase("startNodeCache", args); } public NodeCacheProjection recv_startNodeCache() throws CuratorException, org.apache.thrift.TException { startNodeCache_result result = new startNodeCache_result(); receiveBase(result, "startNodeCache"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "startNodeCache failed: unknown result"); } public PathChildrenCacheProjection startPathChildrenCache(CuratorProjection projection, String path, boolean cacheData, boolean dataIsCompressed, PathChildrenCacheStartMode startMode) throws CuratorException, org.apache.thrift.TException { send_startPathChildrenCache(projection, path, cacheData, dataIsCompressed, startMode); return recv_startPathChildrenCache(); } public void send_startPathChildrenCache(CuratorProjection projection, String path, boolean cacheData, boolean dataIsCompressed, PathChildrenCacheStartMode startMode) throws org.apache.thrift.TException { startPathChildrenCache_args args = new startPathChildrenCache_args(); args.setProjection(projection); args.setPath(path); args.setCacheData(cacheData); args.setDataIsCompressed(dataIsCompressed); args.setStartMode(startMode); sendBase("startPathChildrenCache", args); } public PathChildrenCacheProjection recv_startPathChildrenCache() throws CuratorException, org.apache.thrift.TException { startPathChildrenCache_result result = new startPathChildrenCache_result(); receiveBase(result, "startPathChildrenCache"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "startPathChildrenCache failed: unknown result"); } public PersistentEphemeralNodeProjection startPersistentEphemeralNode(CuratorProjection projection, String path, ByteBuffer data, PersistentEphemeralNodeMode mode) throws CuratorException, org.apache.thrift.TException { send_startPersistentEphemeralNode(projection, path, data, mode); return recv_startPersistentEphemeralNode(); } public void send_startPersistentEphemeralNode(CuratorProjection projection, String path, ByteBuffer data, PersistentEphemeralNodeMode mode) throws org.apache.thrift.TException { startPersistentEphemeralNode_args args = new startPersistentEphemeralNode_args(); args.setProjection(projection); args.setPath(path); args.setData(data); args.setMode(mode); sendBase("startPersistentEphemeralNode", args); } public PersistentEphemeralNodeProjection recv_startPersistentEphemeralNode() throws CuratorException, org.apache.thrift.TException { startPersistentEphemeralNode_result result = new startPersistentEphemeralNode_result(); receiveBase(result, "startPersistentEphemeralNode"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "startPersistentEphemeralNode failed: unknown result"); } public void sync(CuratorProjection projection, String path, String asyncContext) throws CuratorException, org.apache.thrift.TException { send_sync(projection, path, asyncContext); recv_sync(); } public void send_sync(CuratorProjection projection, String path, String asyncContext) throws org.apache.thrift.TException { sync_args args = new sync_args(); args.setProjection(projection); args.setPath(path); args.setAsyncContext(asyncContext); sendBase("sync", args); } public void recv_sync() throws CuratorException, org.apache.thrift.TException { sync_result result = new sync_result(); receiveBase(result, "sync"); if (result.ex1 != null) { throw result.ex1; } return; } } public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface { public static class Factory implements org.apache.thrift.async.TAsyncClientFactory { private org.apache.thrift.async.TAsyncClientManager clientManager; private org.apache.thrift.protocol.TProtocolFactory protocolFactory; public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) { this.clientManager = clientManager; this.protocolFactory = protocolFactory; } public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) { return new AsyncClient(protocolFactory, clientManager, transport); } } public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) { super(protocolFactory, clientManager, transport); } public void acquireLock(CuratorProjection projection, String path, int maxWaitMs, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); acquireLock_call method_call = new acquireLock_call(projection, path, maxWaitMs, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class acquireLock_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private String path; private int maxWaitMs; public acquireLock_call(CuratorProjection projection, String path, int maxWaitMs, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.path = path; this.maxWaitMs = maxWaitMs; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("acquireLock", org.apache.thrift.protocol.TMessageType.CALL, 0)); acquireLock_args args = new acquireLock_args(); args.setProjection(projection); args.setPath(path); args.setMaxWaitMs(maxWaitMs); args.write(prot); prot.writeMessageEnd(); } public OptionalLockProjection getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_acquireLock(); } } public void acquireSemaphore(CuratorProjection projection, String path, int acquireQty, int maxWaitMs, int maxLeases, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); acquireSemaphore_call method_call = new acquireSemaphore_call(projection, path, acquireQty, maxWaitMs, maxLeases, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class acquireSemaphore_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private String path; private int acquireQty; private int maxWaitMs; private int maxLeases; public acquireSemaphore_call(CuratorProjection projection, String path, int acquireQty, int maxWaitMs, int maxLeases, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.path = path; this.acquireQty = acquireQty; this.maxWaitMs = maxWaitMs; this.maxLeases = maxLeases; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("acquireSemaphore", org.apache.thrift.protocol.TMessageType.CALL, 0)); acquireSemaphore_args args = new acquireSemaphore_args(); args.setProjection(projection); args.setPath(path); args.setAcquireQty(acquireQty); args.setMaxWaitMs(maxWaitMs); args.setMaxLeases(maxLeases); args.write(prot); prot.writeMessageEnd(); } public List getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_acquireSemaphore(); } } public void closeCuratorProjection(CuratorProjection projection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); closeCuratorProjection_call method_call = new closeCuratorProjection_call(projection, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class closeCuratorProjection_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; public closeCuratorProjection_call(CuratorProjection projection, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("closeCuratorProjection", org.apache.thrift.protocol.TMessageType.CALL, 0)); closeCuratorProjection_args args = new closeCuratorProjection_args(); args.setProjection(projection); args.write(prot); prot.writeMessageEnd(); } public void getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); (new Client(prot)).recv_closeCuratorProjection(); } } public void closeGenericProjection(CuratorProjection projection, String id, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); closeGenericProjection_call method_call = new closeGenericProjection_call(projection, id, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class closeGenericProjection_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private String id; public closeGenericProjection_call(CuratorProjection projection, String id, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.id = id; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("closeGenericProjection", org.apache.thrift.protocol.TMessageType.CALL, 0)); closeGenericProjection_args args = new closeGenericProjection_args(); args.setProjection(projection); args.setId(id); args.write(prot); prot.writeMessageEnd(); } public boolean getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_closeGenericProjection(); } } public void createNode(CuratorProjection projection, CreateSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); createNode_call method_call = new createNode_call(projection, spec, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class createNode_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private CreateSpec spec; public createNode_call(CuratorProjection projection, CreateSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.spec = spec; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("createNode", org.apache.thrift.protocol.TMessageType.CALL, 0)); createNode_args args = new createNode_args(); args.setProjection(projection); args.setSpec(spec); args.write(prot); prot.writeMessageEnd(); } public OptionalPath getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_createNode(); } } public void deleteNode(CuratorProjection projection, DeleteSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); deleteNode_call method_call = new deleteNode_call(projection, spec, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class deleteNode_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private DeleteSpec spec; public deleteNode_call(CuratorProjection projection, DeleteSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.spec = spec; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("deleteNode", org.apache.thrift.protocol.TMessageType.CALL, 0)); deleteNode_args args = new deleteNode_args(); args.setProjection(projection); args.setSpec(spec); args.write(prot); prot.writeMessageEnd(); } public void getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); (new Client(prot)).recv_deleteNode(); } } public void exists(CuratorProjection projection, ExistsSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); exists_call method_call = new exists_call(projection, spec, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class exists_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private ExistsSpec spec; public exists_call(CuratorProjection projection, ExistsSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.spec = spec; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("exists", org.apache.thrift.protocol.TMessageType.CALL, 0)); exists_args args = new exists_args(); args.setProjection(projection); args.setSpec(spec); args.write(prot); prot.writeMessageEnd(); } public OptionalStat getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_exists(); } } public void getChildren(CuratorProjection projection, GetChildrenSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); getChildren_call method_call = new getChildren_call(projection, spec, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class getChildren_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private GetChildrenSpec spec; public getChildren_call(CuratorProjection projection, GetChildrenSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.spec = spec; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getChildren", org.apache.thrift.protocol.TMessageType.CALL, 0)); getChildren_args args = new getChildren_args(); args.setProjection(projection); args.setSpec(spec); args.write(prot); prot.writeMessageEnd(); } public OptionalChildrenList getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_getChildren(); } } public void getData(CuratorProjection projection, GetDataSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); getData_call method_call = new getData_call(projection, spec, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class getData_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private GetDataSpec spec; public getData_call(CuratorProjection projection, GetDataSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.spec = spec; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getData", org.apache.thrift.protocol.TMessageType.CALL, 0)); getData_args args = new getData_args(); args.setProjection(projection); args.setSpec(spec); args.write(prot); prot.writeMessageEnd(); } public OptionalData getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_getData(); } } public void getLeaderParticipants(CuratorProjection projection, LeaderProjection leaderProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); getLeaderParticipants_call method_call = new getLeaderParticipants_call(projection, leaderProjection, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class getLeaderParticipants_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private LeaderProjection leaderProjection; public getLeaderParticipants_call(CuratorProjection projection, LeaderProjection leaderProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.leaderProjection = leaderProjection; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getLeaderParticipants", org.apache.thrift.protocol.TMessageType.CALL, 0)); getLeaderParticipants_args args = new getLeaderParticipants_args(); args.setProjection(projection); args.setLeaderProjection(leaderProjection); args.write(prot); prot.writeMessageEnd(); } public List getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_getLeaderParticipants(); } } public void getNodeCacheData(CuratorProjection projection, NodeCacheProjection cacheProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); getNodeCacheData_call method_call = new getNodeCacheData_call(projection, cacheProjection, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class getNodeCacheData_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private NodeCacheProjection cacheProjection; public getNodeCacheData_call(CuratorProjection projection, NodeCacheProjection cacheProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.cacheProjection = cacheProjection; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getNodeCacheData", org.apache.thrift.protocol.TMessageType.CALL, 0)); getNodeCacheData_args args = new getNodeCacheData_args(); args.setProjection(projection); args.setCacheProjection(cacheProjection); args.write(prot); prot.writeMessageEnd(); } public ChildData getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_getNodeCacheData(); } } public void getPathChildrenCacheData(CuratorProjection projection, PathChildrenCacheProjection cacheProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); getPathChildrenCacheData_call method_call = new getPathChildrenCacheData_call(projection, cacheProjection, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class getPathChildrenCacheData_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private PathChildrenCacheProjection cacheProjection; public getPathChildrenCacheData_call(CuratorProjection projection, PathChildrenCacheProjection cacheProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.cacheProjection = cacheProjection; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getPathChildrenCacheData", org.apache.thrift.protocol.TMessageType.CALL, 0)); getPathChildrenCacheData_args args = new getPathChildrenCacheData_args(); args.setProjection(projection); args.setCacheProjection(cacheProjection); args.write(prot); prot.writeMessageEnd(); } public List getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_getPathChildrenCacheData(); } } public void getPathChildrenCacheDataForPath(CuratorProjection projection, PathChildrenCacheProjection cacheProjection, String path, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); getPathChildrenCacheDataForPath_call method_call = new getPathChildrenCacheDataForPath_call(projection, cacheProjection, path, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class getPathChildrenCacheDataForPath_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private PathChildrenCacheProjection cacheProjection; private String path; public getPathChildrenCacheDataForPath_call(CuratorProjection projection, PathChildrenCacheProjection cacheProjection, String path, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.cacheProjection = cacheProjection; this.path = path; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getPathChildrenCacheDataForPath", org.apache.thrift.protocol.TMessageType.CALL, 0)); getPathChildrenCacheDataForPath_args args = new getPathChildrenCacheDataForPath_args(); args.setProjection(projection); args.setCacheProjection(cacheProjection); args.setPath(path); args.write(prot); prot.writeMessageEnd(); } public ChildData getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_getPathChildrenCacheDataForPath(); } } public void isLeader(CuratorProjection projection, LeaderProjection leaderProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); isLeader_call method_call = new isLeader_call(projection, leaderProjection, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class isLeader_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private LeaderProjection leaderProjection; public isLeader_call(CuratorProjection projection, LeaderProjection leaderProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.leaderProjection = leaderProjection; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("isLeader", org.apache.thrift.protocol.TMessageType.CALL, 0)); isLeader_args args = new isLeader_args(); args.setProjection(projection); args.setLeaderProjection(leaderProjection); args.write(prot); prot.writeMessageEnd(); } public boolean getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_isLeader(); } } public void newCuratorProjection(String connectionName, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); newCuratorProjection_call method_call = new newCuratorProjection_call(connectionName, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class newCuratorProjection_call extends org.apache.thrift.async.TAsyncMethodCall { private String connectionName; public newCuratorProjection_call(String connectionName, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.connectionName = connectionName; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("newCuratorProjection", org.apache.thrift.protocol.TMessageType.CALL, 0)); newCuratorProjection_args args = new newCuratorProjection_args(); args.setConnectionName(connectionName); args.write(prot); prot.writeMessageEnd(); } public CuratorProjection getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_newCuratorProjection(); } } public void pingCuratorProjection(CuratorProjection projection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); pingCuratorProjection_call method_call = new pingCuratorProjection_call(projection, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class pingCuratorProjection_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; public pingCuratorProjection_call(CuratorProjection projection, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, true); this.projection = projection; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("pingCuratorProjection", org.apache.thrift.protocol.TMessageType.CALL, 0)); pingCuratorProjection_args args = new pingCuratorProjection_args(); args.setProjection(projection); args.write(prot); prot.writeMessageEnd(); } public void getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); } } public void setData(CuratorProjection projection, SetDataSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); setData_call method_call = new setData_call(projection, spec, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class setData_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private SetDataSpec spec; public setData_call(CuratorProjection projection, SetDataSpec spec, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.spec = spec; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("setData", org.apache.thrift.protocol.TMessageType.CALL, 0)); setData_args args = new setData_args(); args.setProjection(projection); args.setSpec(spec); args.write(prot); prot.writeMessageEnd(); } public OptionalStat getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_setData(); } } public void startLeaderSelector(CuratorProjection projection, String path, String participantId, int waitForLeadershipMs, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); startLeaderSelector_call method_call = new startLeaderSelector_call(projection, path, participantId, waitForLeadershipMs, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class startLeaderSelector_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private String path; private String participantId; private int waitForLeadershipMs; public startLeaderSelector_call(CuratorProjection projection, String path, String participantId, int waitForLeadershipMs, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.path = path; this.participantId = participantId; this.waitForLeadershipMs = waitForLeadershipMs; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("startLeaderSelector", org.apache.thrift.protocol.TMessageType.CALL, 0)); startLeaderSelector_args args = new startLeaderSelector_args(); args.setProjection(projection); args.setPath(path); args.setParticipantId(participantId); args.setWaitForLeadershipMs(waitForLeadershipMs); args.write(prot); prot.writeMessageEnd(); } public LeaderResult getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_startLeaderSelector(); } } public void startNodeCache(CuratorProjection projection, String path, boolean dataIsCompressed, boolean buildInitial, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); startNodeCache_call method_call = new startNodeCache_call(projection, path, dataIsCompressed, buildInitial, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class startNodeCache_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private String path; private boolean dataIsCompressed; private boolean buildInitial; public startNodeCache_call(CuratorProjection projection, String path, boolean dataIsCompressed, boolean buildInitial, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.path = path; this.dataIsCompressed = dataIsCompressed; this.buildInitial = buildInitial; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("startNodeCache", org.apache.thrift.protocol.TMessageType.CALL, 0)); startNodeCache_args args = new startNodeCache_args(); args.setProjection(projection); args.setPath(path); args.setDataIsCompressed(dataIsCompressed); args.setBuildInitial(buildInitial); args.write(prot); prot.writeMessageEnd(); } public NodeCacheProjection getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_startNodeCache(); } } public void startPathChildrenCache(CuratorProjection projection, String path, boolean cacheData, boolean dataIsCompressed, PathChildrenCacheStartMode startMode, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); startPathChildrenCache_call method_call = new startPathChildrenCache_call(projection, path, cacheData, dataIsCompressed, startMode, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class startPathChildrenCache_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private String path; private boolean cacheData; private boolean dataIsCompressed; private PathChildrenCacheStartMode startMode; public startPathChildrenCache_call(CuratorProjection projection, String path, boolean cacheData, boolean dataIsCompressed, PathChildrenCacheStartMode startMode, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.path = path; this.cacheData = cacheData; this.dataIsCompressed = dataIsCompressed; this.startMode = startMode; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("startPathChildrenCache", org.apache.thrift.protocol.TMessageType.CALL, 0)); startPathChildrenCache_args args = new startPathChildrenCache_args(); args.setProjection(projection); args.setPath(path); args.setCacheData(cacheData); args.setDataIsCompressed(dataIsCompressed); args.setStartMode(startMode); args.write(prot); prot.writeMessageEnd(); } public PathChildrenCacheProjection getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_startPathChildrenCache(); } } public void startPersistentEphemeralNode(CuratorProjection projection, String path, ByteBuffer data, PersistentEphemeralNodeMode mode, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); startPersistentEphemeralNode_call method_call = new startPersistentEphemeralNode_call(projection, path, data, mode, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class startPersistentEphemeralNode_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private String path; private ByteBuffer data; private PersistentEphemeralNodeMode mode; public startPersistentEphemeralNode_call(CuratorProjection projection, String path, ByteBuffer data, PersistentEphemeralNodeMode mode, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.path = path; this.data = data; this.mode = mode; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("startPersistentEphemeralNode", org.apache.thrift.protocol.TMessageType.CALL, 0)); startPersistentEphemeralNode_args args = new startPersistentEphemeralNode_args(); args.setProjection(projection); args.setPath(path); args.setData(data); args.setMode(mode); args.write(prot); prot.writeMessageEnd(); } public PersistentEphemeralNodeProjection getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_startPersistentEphemeralNode(); } } public void sync(CuratorProjection projection, String path, String asyncContext, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); sync_call method_call = new sync_call(projection, path, asyncContext, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class sync_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private String path; private String asyncContext; public sync_call(CuratorProjection projection, String path, String asyncContext, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.path = path; this.asyncContext = asyncContext; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("sync", org.apache.thrift.protocol.TMessageType.CALL, 0)); sync_args args = new sync_args(); args.setProjection(projection); args.setPath(path); args.setAsyncContext(asyncContext); args.write(prot); prot.writeMessageEnd(); } public void getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); (new Client(prot)).recv_sync(); } } } public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName()); public Processor(I iface) { super(iface, getProcessMap(new HashMap>())); } protected Processor(I iface, Map> processMap) { super(iface, getProcessMap(processMap)); } private static Map> getProcessMap(Map> processMap) { processMap.put("acquireLock", new acquireLock()); processMap.put("acquireSemaphore", new acquireSemaphore()); processMap.put("closeCuratorProjection", new closeCuratorProjection()); processMap.put("closeGenericProjection", new closeGenericProjection()); processMap.put("createNode", new createNode()); processMap.put("deleteNode", new deleteNode()); processMap.put("exists", new exists()); processMap.put("getChildren", new getChildren()); processMap.put("getData", new getData()); processMap.put("getLeaderParticipants", new getLeaderParticipants()); processMap.put("getNodeCacheData", new getNodeCacheData()); processMap.put("getPathChildrenCacheData", new getPathChildrenCacheData()); processMap.put("getPathChildrenCacheDataForPath", new getPathChildrenCacheDataForPath()); processMap.put("isLeader", new isLeader()); processMap.put("newCuratorProjection", new newCuratorProjection()); processMap.put("pingCuratorProjection", new pingCuratorProjection()); processMap.put("setData", new setData()); processMap.put("startLeaderSelector", new startLeaderSelector()); processMap.put("startNodeCache", new startNodeCache()); processMap.put("startPathChildrenCache", new startPathChildrenCache()); processMap.put("startPersistentEphemeralNode", new startPersistentEphemeralNode()); processMap.put("sync", new sync()); return processMap; } public static class acquireLock extends org.apache.thrift.ProcessFunction { public acquireLock() { super("acquireLock"); } public acquireLock_args getEmptyArgsInstance() { return new acquireLock_args(); } protected boolean isOneway() { return false; } public acquireLock_result getResult(I iface, acquireLock_args args) throws org.apache.thrift.TException { acquireLock_result result = new acquireLock_result(); try { result.success = iface.acquireLock(args.projection, args.path, args.maxWaitMs); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class acquireSemaphore extends org.apache.thrift.ProcessFunction { public acquireSemaphore() { super("acquireSemaphore"); } public acquireSemaphore_args getEmptyArgsInstance() { return new acquireSemaphore_args(); } protected boolean isOneway() { return false; } public acquireSemaphore_result getResult(I iface, acquireSemaphore_args args) throws org.apache.thrift.TException { acquireSemaphore_result result = new acquireSemaphore_result(); try { result.success = iface.acquireSemaphore(args.projection, args.path, args.acquireQty, args.maxWaitMs, args.maxLeases); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class closeCuratorProjection extends org.apache.thrift.ProcessFunction { public closeCuratorProjection() { super("closeCuratorProjection"); } public closeCuratorProjection_args getEmptyArgsInstance() { return new closeCuratorProjection_args(); } protected boolean isOneway() { return false; } public closeCuratorProjection_result getResult(I iface, closeCuratorProjection_args args) throws org.apache.thrift.TException { closeCuratorProjection_result result = new closeCuratorProjection_result(); iface.closeCuratorProjection(args.projection); return result; } } public static class closeGenericProjection extends org.apache.thrift.ProcessFunction { public closeGenericProjection() { super("closeGenericProjection"); } public closeGenericProjection_args getEmptyArgsInstance() { return new closeGenericProjection_args(); } protected boolean isOneway() { return false; } public closeGenericProjection_result getResult(I iface, closeGenericProjection_args args) throws org.apache.thrift.TException { closeGenericProjection_result result = new closeGenericProjection_result(); try { result.success = iface.closeGenericProjection(args.projection, args.id); result.setSuccessIsSet(true); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class createNode extends org.apache.thrift.ProcessFunction { public createNode() { super("createNode"); } public createNode_args getEmptyArgsInstance() { return new createNode_args(); } protected boolean isOneway() { return false; } public createNode_result getResult(I iface, createNode_args args) throws org.apache.thrift.TException { createNode_result result = new createNode_result(); try { result.success = iface.createNode(args.projection, args.spec); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class deleteNode extends org.apache.thrift.ProcessFunction { public deleteNode() { super("deleteNode"); } public deleteNode_args getEmptyArgsInstance() { return new deleteNode_args(); } protected boolean isOneway() { return false; } public deleteNode_result getResult(I iface, deleteNode_args args) throws org.apache.thrift.TException { deleteNode_result result = new deleteNode_result(); try { iface.deleteNode(args.projection, args.spec); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class exists extends org.apache.thrift.ProcessFunction { public exists() { super("exists"); } public exists_args getEmptyArgsInstance() { return new exists_args(); } protected boolean isOneway() { return false; } public exists_result getResult(I iface, exists_args args) throws org.apache.thrift.TException { exists_result result = new exists_result(); try { result.success = iface.exists(args.projection, args.spec); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class getChildren extends org.apache.thrift.ProcessFunction { public getChildren() { super("getChildren"); } public getChildren_args getEmptyArgsInstance() { return new getChildren_args(); } protected boolean isOneway() { return false; } public getChildren_result getResult(I iface, getChildren_args args) throws org.apache.thrift.TException { getChildren_result result = new getChildren_result(); try { result.success = iface.getChildren(args.projection, args.spec); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class getData extends org.apache.thrift.ProcessFunction { public getData() { super("getData"); } public getData_args getEmptyArgsInstance() { return new getData_args(); } protected boolean isOneway() { return false; } public getData_result getResult(I iface, getData_args args) throws org.apache.thrift.TException { getData_result result = new getData_result(); try { result.success = iface.getData(args.projection, args.spec); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class getLeaderParticipants extends org.apache.thrift.ProcessFunction { public getLeaderParticipants() { super("getLeaderParticipants"); } public getLeaderParticipants_args getEmptyArgsInstance() { return new getLeaderParticipants_args(); } protected boolean isOneway() { return false; } public getLeaderParticipants_result getResult(I iface, getLeaderParticipants_args args) throws org.apache.thrift.TException { getLeaderParticipants_result result = new getLeaderParticipants_result(); try { result.success = iface.getLeaderParticipants(args.projection, args.leaderProjection); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class getNodeCacheData extends org.apache.thrift.ProcessFunction { public getNodeCacheData() { super("getNodeCacheData"); } public getNodeCacheData_args getEmptyArgsInstance() { return new getNodeCacheData_args(); } protected boolean isOneway() { return false; } public getNodeCacheData_result getResult(I iface, getNodeCacheData_args args) throws org.apache.thrift.TException { getNodeCacheData_result result = new getNodeCacheData_result(); try { result.success = iface.getNodeCacheData(args.projection, args.cacheProjection); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class getPathChildrenCacheData extends org.apache.thrift.ProcessFunction { public getPathChildrenCacheData() { super("getPathChildrenCacheData"); } public getPathChildrenCacheData_args getEmptyArgsInstance() { return new getPathChildrenCacheData_args(); } protected boolean isOneway() { return false; } public getPathChildrenCacheData_result getResult(I iface, getPathChildrenCacheData_args args) throws org.apache.thrift.TException { getPathChildrenCacheData_result result = new getPathChildrenCacheData_result(); try { result.success = iface.getPathChildrenCacheData(args.projection, args.cacheProjection); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class getPathChildrenCacheDataForPath extends org.apache.thrift.ProcessFunction { public getPathChildrenCacheDataForPath() { super("getPathChildrenCacheDataForPath"); } public getPathChildrenCacheDataForPath_args getEmptyArgsInstance() { return new getPathChildrenCacheDataForPath_args(); } protected boolean isOneway() { return false; } public getPathChildrenCacheDataForPath_result getResult(I iface, getPathChildrenCacheDataForPath_args args) throws org.apache.thrift.TException { getPathChildrenCacheDataForPath_result result = new getPathChildrenCacheDataForPath_result(); try { result.success = iface.getPathChildrenCacheDataForPath(args.projection, args.cacheProjection, args.path); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class isLeader extends org.apache.thrift.ProcessFunction { public isLeader() { super("isLeader"); } public isLeader_args getEmptyArgsInstance() { return new isLeader_args(); } protected boolean isOneway() { return false; } public isLeader_result getResult(I iface, isLeader_args args) throws org.apache.thrift.TException { isLeader_result result = new isLeader_result(); try { result.success = iface.isLeader(args.projection, args.leaderProjection); result.setSuccessIsSet(true); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class newCuratorProjection extends org.apache.thrift.ProcessFunction { public newCuratorProjection() { super("newCuratorProjection"); } public newCuratorProjection_args getEmptyArgsInstance() { return new newCuratorProjection_args(); } protected boolean isOneway() { return false; } public newCuratorProjection_result getResult(I iface, newCuratorProjection_args args) throws org.apache.thrift.TException { newCuratorProjection_result result = new newCuratorProjection_result(); try { result.success = iface.newCuratorProjection(args.connectionName); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class pingCuratorProjection extends org.apache.thrift.ProcessFunction { public pingCuratorProjection() { super("pingCuratorProjection"); } public pingCuratorProjection_args getEmptyArgsInstance() { return new pingCuratorProjection_args(); } protected boolean isOneway() { return true; } public org.apache.thrift.TBase getResult(I iface, pingCuratorProjection_args args) throws org.apache.thrift.TException { iface.pingCuratorProjection(args.projection); return null; } } public static class setData extends org.apache.thrift.ProcessFunction { public setData() { super("setData"); } public setData_args getEmptyArgsInstance() { return new setData_args(); } protected boolean isOneway() { return false; } public setData_result getResult(I iface, setData_args args) throws org.apache.thrift.TException { setData_result result = new setData_result(); try { result.success = iface.setData(args.projection, args.spec); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class startLeaderSelector extends org.apache.thrift.ProcessFunction { public startLeaderSelector() { super("startLeaderSelector"); } public startLeaderSelector_args getEmptyArgsInstance() { return new startLeaderSelector_args(); } protected boolean isOneway() { return false; } public startLeaderSelector_result getResult(I iface, startLeaderSelector_args args) throws org.apache.thrift.TException { startLeaderSelector_result result = new startLeaderSelector_result(); try { result.success = iface.startLeaderSelector(args.projection, args.path, args.participantId, args.waitForLeadershipMs); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class startNodeCache extends org.apache.thrift.ProcessFunction { public startNodeCache() { super("startNodeCache"); } public startNodeCache_args getEmptyArgsInstance() { return new startNodeCache_args(); } protected boolean isOneway() { return false; } public startNodeCache_result getResult(I iface, startNodeCache_args args) throws org.apache.thrift.TException { startNodeCache_result result = new startNodeCache_result(); try { result.success = iface.startNodeCache(args.projection, args.path, args.dataIsCompressed, args.buildInitial); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class startPathChildrenCache extends org.apache.thrift.ProcessFunction { public startPathChildrenCache() { super("startPathChildrenCache"); } public startPathChildrenCache_args getEmptyArgsInstance() { return new startPathChildrenCache_args(); } protected boolean isOneway() { return false; } public startPathChildrenCache_result getResult(I iface, startPathChildrenCache_args args) throws org.apache.thrift.TException { startPathChildrenCache_result result = new startPathChildrenCache_result(); try { result.success = iface.startPathChildrenCache(args.projection, args.path, args.cacheData, args.dataIsCompressed, args.startMode); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class startPersistentEphemeralNode extends org.apache.thrift.ProcessFunction { public startPersistentEphemeralNode() { super("startPersistentEphemeralNode"); } public startPersistentEphemeralNode_args getEmptyArgsInstance() { return new startPersistentEphemeralNode_args(); } protected boolean isOneway() { return false; } public startPersistentEphemeralNode_result getResult(I iface, startPersistentEphemeralNode_args args) throws org.apache.thrift.TException { startPersistentEphemeralNode_result result = new startPersistentEphemeralNode_result(); try { result.success = iface.startPersistentEphemeralNode(args.projection, args.path, args.data, args.mode); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class sync extends org.apache.thrift.ProcessFunction { public sync() { super("sync"); } public sync_args getEmptyArgsInstance() { return new sync_args(); } protected boolean isOneway() { return false; } public sync_result getResult(I iface, sync_args args) throws org.apache.thrift.TException { sync_result result = new sync_result(); try { iface.sync(args.projection, args.path, args.asyncContext); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } } public static class AsyncProcessor extends org.apache.thrift.TBaseAsyncProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName()); public AsyncProcessor(I iface) { super(iface, getProcessMap(new HashMap>())); } protected AsyncProcessor(I iface, Map> processMap) { super(iface, getProcessMap(processMap)); } private static Map> getProcessMap(Map> processMap) { processMap.put("acquireLock", new acquireLock()); processMap.put("acquireSemaphore", new acquireSemaphore()); processMap.put("closeCuratorProjection", new closeCuratorProjection()); processMap.put("closeGenericProjection", new closeGenericProjection()); processMap.put("createNode", new createNode()); processMap.put("deleteNode", new deleteNode()); processMap.put("exists", new exists()); processMap.put("getChildren", new getChildren()); processMap.put("getData", new getData()); processMap.put("getLeaderParticipants", new getLeaderParticipants()); processMap.put("getNodeCacheData", new getNodeCacheData()); processMap.put("getPathChildrenCacheData", new getPathChildrenCacheData()); processMap.put("getPathChildrenCacheDataForPath", new getPathChildrenCacheDataForPath()); processMap.put("isLeader", new isLeader()); processMap.put("newCuratorProjection", new newCuratorProjection()); processMap.put("pingCuratorProjection", new pingCuratorProjection()); processMap.put("setData", new setData()); processMap.put("startLeaderSelector", new startLeaderSelector()); processMap.put("startNodeCache", new startNodeCache()); processMap.put("startPathChildrenCache", new startPathChildrenCache()); processMap.put("startPersistentEphemeralNode", new startPersistentEphemeralNode()); processMap.put("sync", new sync()); return processMap; } public static class acquireLock extends org.apache.thrift.AsyncProcessFunction { public acquireLock() { super("acquireLock"); } public acquireLock_args getEmptyArgsInstance() { return new acquireLock_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(OptionalLockProjection o) { acquireLock_result result = new acquireLock_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; acquireLock_result result = new acquireLock_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, acquireLock_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.acquireLock(args.projection, args.path, args.maxWaitMs,resultHandler); } } public static class acquireSemaphore extends org.apache.thrift.AsyncProcessFunction> { public acquireSemaphore() { super("acquireSemaphore"); } public acquireSemaphore_args getEmptyArgsInstance() { return new acquireSemaphore_args(); } public AsyncMethodCallback> getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback>() { public void onComplete(List o) { acquireSemaphore_result result = new acquireSemaphore_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; acquireSemaphore_result result = new acquireSemaphore_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, acquireSemaphore_args args, org.apache.thrift.async.AsyncMethodCallback> resultHandler) throws TException { iface.acquireSemaphore(args.projection, args.path, args.acquireQty, args.maxWaitMs, args.maxLeases,resultHandler); } } public static class closeCuratorProjection extends org.apache.thrift.AsyncProcessFunction { public closeCuratorProjection() { super("closeCuratorProjection"); } public closeCuratorProjection_args getEmptyArgsInstance() { return new closeCuratorProjection_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(Void o) { closeCuratorProjection_result result = new closeCuratorProjection_result(); try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; closeCuratorProjection_result result = new closeCuratorProjection_result(); { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, closeCuratorProjection_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.closeCuratorProjection(args.projection,resultHandler); } } public static class closeGenericProjection extends org.apache.thrift.AsyncProcessFunction { public closeGenericProjection() { super("closeGenericProjection"); } public closeGenericProjection_args getEmptyArgsInstance() { return new closeGenericProjection_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(Boolean o) { closeGenericProjection_result result = new closeGenericProjection_result(); result.success = o; result.setSuccessIsSet(true); try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; closeGenericProjection_result result = new closeGenericProjection_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, closeGenericProjection_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.closeGenericProjection(args.projection, args.id,resultHandler); } } public static class createNode extends org.apache.thrift.AsyncProcessFunction { public createNode() { super("createNode"); } public createNode_args getEmptyArgsInstance() { return new createNode_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(OptionalPath o) { createNode_result result = new createNode_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; createNode_result result = new createNode_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, createNode_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.createNode(args.projection, args.spec,resultHandler); } } public static class deleteNode extends org.apache.thrift.AsyncProcessFunction { public deleteNode() { super("deleteNode"); } public deleteNode_args getEmptyArgsInstance() { return new deleteNode_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(Void o) { deleteNode_result result = new deleteNode_result(); try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; deleteNode_result result = new deleteNode_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, deleteNode_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.deleteNode(args.projection, args.spec,resultHandler); } } public static class exists extends org.apache.thrift.AsyncProcessFunction { public exists() { super("exists"); } public exists_args getEmptyArgsInstance() { return new exists_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(OptionalStat o) { exists_result result = new exists_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; exists_result result = new exists_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, exists_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.exists(args.projection, args.spec,resultHandler); } } public static class getChildren extends org.apache.thrift.AsyncProcessFunction { public getChildren() { super("getChildren"); } public getChildren_args getEmptyArgsInstance() { return new getChildren_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(OptionalChildrenList o) { getChildren_result result = new getChildren_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; getChildren_result result = new getChildren_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, getChildren_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.getChildren(args.projection, args.spec,resultHandler); } } public static class getData extends org.apache.thrift.AsyncProcessFunction { public getData() { super("getData"); } public getData_args getEmptyArgsInstance() { return new getData_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(OptionalData o) { getData_result result = new getData_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; getData_result result = new getData_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, getData_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.getData(args.projection, args.spec,resultHandler); } } public static class getLeaderParticipants extends org.apache.thrift.AsyncProcessFunction> { public getLeaderParticipants() { super("getLeaderParticipants"); } public getLeaderParticipants_args getEmptyArgsInstance() { return new getLeaderParticipants_args(); } public AsyncMethodCallback> getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback>() { public void onComplete(List o) { getLeaderParticipants_result result = new getLeaderParticipants_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; getLeaderParticipants_result result = new getLeaderParticipants_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, getLeaderParticipants_args args, org.apache.thrift.async.AsyncMethodCallback> resultHandler) throws TException { iface.getLeaderParticipants(args.projection, args.leaderProjection,resultHandler); } } public static class getNodeCacheData extends org.apache.thrift.AsyncProcessFunction { public getNodeCacheData() { super("getNodeCacheData"); } public getNodeCacheData_args getEmptyArgsInstance() { return new getNodeCacheData_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(ChildData o) { getNodeCacheData_result result = new getNodeCacheData_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; getNodeCacheData_result result = new getNodeCacheData_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, getNodeCacheData_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.getNodeCacheData(args.projection, args.cacheProjection,resultHandler); } } public static class getPathChildrenCacheData extends org.apache.thrift.AsyncProcessFunction> { public getPathChildrenCacheData() { super("getPathChildrenCacheData"); } public getPathChildrenCacheData_args getEmptyArgsInstance() { return new getPathChildrenCacheData_args(); } public AsyncMethodCallback> getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback>() { public void onComplete(List o) { getPathChildrenCacheData_result result = new getPathChildrenCacheData_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; getPathChildrenCacheData_result result = new getPathChildrenCacheData_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, getPathChildrenCacheData_args args, org.apache.thrift.async.AsyncMethodCallback> resultHandler) throws TException { iface.getPathChildrenCacheData(args.projection, args.cacheProjection,resultHandler); } } public static class getPathChildrenCacheDataForPath extends org.apache.thrift.AsyncProcessFunction { public getPathChildrenCacheDataForPath() { super("getPathChildrenCacheDataForPath"); } public getPathChildrenCacheDataForPath_args getEmptyArgsInstance() { return new getPathChildrenCacheDataForPath_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(ChildData o) { getPathChildrenCacheDataForPath_result result = new getPathChildrenCacheDataForPath_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; getPathChildrenCacheDataForPath_result result = new getPathChildrenCacheDataForPath_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, getPathChildrenCacheDataForPath_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.getPathChildrenCacheDataForPath(args.projection, args.cacheProjection, args.path,resultHandler); } } public static class isLeader extends org.apache.thrift.AsyncProcessFunction { public isLeader() { super("isLeader"); } public isLeader_args getEmptyArgsInstance() { return new isLeader_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(Boolean o) { isLeader_result result = new isLeader_result(); result.success = o; result.setSuccessIsSet(true); try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; isLeader_result result = new isLeader_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, isLeader_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.isLeader(args.projection, args.leaderProjection,resultHandler); } } public static class newCuratorProjection extends org.apache.thrift.AsyncProcessFunction { public newCuratorProjection() { super("newCuratorProjection"); } public newCuratorProjection_args getEmptyArgsInstance() { return new newCuratorProjection_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(CuratorProjection o) { newCuratorProjection_result result = new newCuratorProjection_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; newCuratorProjection_result result = new newCuratorProjection_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, newCuratorProjection_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.newCuratorProjection(args.connectionName,resultHandler); } } public static class pingCuratorProjection extends org.apache.thrift.AsyncProcessFunction { public pingCuratorProjection() { super("pingCuratorProjection"); } public pingCuratorProjection_args getEmptyArgsInstance() { return new pingCuratorProjection_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(Void o) { } public void onError(Exception e) { } }; } protected boolean isOneway() { return true; } public void start(I iface, pingCuratorProjection_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.pingCuratorProjection(args.projection,resultHandler); } } public static class setData extends org.apache.thrift.AsyncProcessFunction { public setData() { super("setData"); } public setData_args getEmptyArgsInstance() { return new setData_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(OptionalStat o) { setData_result result = new setData_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; setData_result result = new setData_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, setData_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.setData(args.projection, args.spec,resultHandler); } } public static class startLeaderSelector extends org.apache.thrift.AsyncProcessFunction { public startLeaderSelector() { super("startLeaderSelector"); } public startLeaderSelector_args getEmptyArgsInstance() { return new startLeaderSelector_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(LeaderResult o) { startLeaderSelector_result result = new startLeaderSelector_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; startLeaderSelector_result result = new startLeaderSelector_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, startLeaderSelector_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.startLeaderSelector(args.projection, args.path, args.participantId, args.waitForLeadershipMs,resultHandler); } } public static class startNodeCache extends org.apache.thrift.AsyncProcessFunction { public startNodeCache() { super("startNodeCache"); } public startNodeCache_args getEmptyArgsInstance() { return new startNodeCache_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(NodeCacheProjection o) { startNodeCache_result result = new startNodeCache_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; startNodeCache_result result = new startNodeCache_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, startNodeCache_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.startNodeCache(args.projection, args.path, args.dataIsCompressed, args.buildInitial,resultHandler); } } public static class startPathChildrenCache extends org.apache.thrift.AsyncProcessFunction { public startPathChildrenCache() { super("startPathChildrenCache"); } public startPathChildrenCache_args getEmptyArgsInstance() { return new startPathChildrenCache_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(PathChildrenCacheProjection o) { startPathChildrenCache_result result = new startPathChildrenCache_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; startPathChildrenCache_result result = new startPathChildrenCache_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, startPathChildrenCache_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.startPathChildrenCache(args.projection, args.path, args.cacheData, args.dataIsCompressed, args.startMode,resultHandler); } } public static class startPersistentEphemeralNode extends org.apache.thrift.AsyncProcessFunction { public startPersistentEphemeralNode() { super("startPersistentEphemeralNode"); } public startPersistentEphemeralNode_args getEmptyArgsInstance() { return new startPersistentEphemeralNode_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(PersistentEphemeralNodeProjection o) { startPersistentEphemeralNode_result result = new startPersistentEphemeralNode_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; startPersistentEphemeralNode_result result = new startPersistentEphemeralNode_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, startPersistentEphemeralNode_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.startPersistentEphemeralNode(args.projection, args.path, args.data, args.mode,resultHandler); } } public static class sync extends org.apache.thrift.AsyncProcessFunction { public sync() { super("sync"); } public sync_args getEmptyArgsInstance() { return new sync_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(Void o) { sync_result result = new sync_result(); try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; sync_result result = new sync_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, sync_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.sync(args.projection, args.path, args.asyncContext,resultHandler); } } } public static class acquireLock_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("acquireLock_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField MAX_WAIT_MS_FIELD_DESC = new org.apache.thrift.protocol.TField("maxWaitMs", org.apache.thrift.protocol.TType.I32, (short)3); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new acquireLock_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new acquireLock_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public String path; // required public int maxWaitMs; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), PATH((short)2, "path"), MAX_WAIT_MS((short)3, "maxWaitMs"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // PATH return PATH; case 3: // MAX_WAIT_MS return MAX_WAIT_MS; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __MAXWAITMS_ISSET_ID = 0; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.MAX_WAIT_MS, new org.apache.thrift.meta_data.FieldMetaData("maxWaitMs", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(acquireLock_args.class, metaDataMap); } public acquireLock_args() { } public acquireLock_args( CuratorProjection projection, String path, int maxWaitMs) { this(); this.projection = projection; this.path = path; this.maxWaitMs = maxWaitMs; setMaxWaitMsIsSet(true); } /** * Performs a deep copy on other. */ public acquireLock_args(acquireLock_args other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetPath()) { this.path = other.path; } this.maxWaitMs = other.maxWaitMs; } public acquireLock_args deepCopy() { return new acquireLock_args(this); } @Override public void clear() { this.projection = null; this.path = null; setMaxWaitMsIsSet(false); this.maxWaitMs = 0; } public CuratorProjection getProjection() { return this.projection; } public acquireLock_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public String getPath() { return this.path; } public acquireLock_args setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public int getMaxWaitMs() { return this.maxWaitMs; } public acquireLock_args setMaxWaitMs(int maxWaitMs) { this.maxWaitMs = maxWaitMs; setMaxWaitMsIsSet(true); return this; } public void unsetMaxWaitMs() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __MAXWAITMS_ISSET_ID); } /** Returns true if field maxWaitMs is set (has been assigned a value) and false otherwise */ public boolean isSetMaxWaitMs() { return EncodingUtils.testBit(__isset_bitfield, __MAXWAITMS_ISSET_ID); } public void setMaxWaitMsIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __MAXWAITMS_ISSET_ID, value); } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; case MAX_WAIT_MS: if (value == null) { unsetMaxWaitMs(); } else { setMaxWaitMs((Integer)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case PATH: return getPath(); case MAX_WAIT_MS: return Integer.valueOf(getMaxWaitMs()); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case PATH: return isSetPath(); case MAX_WAIT_MS: return isSetMaxWaitMs(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof acquireLock_args) return this.equals((acquireLock_args)that); return false; } public boolean equals(acquireLock_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } boolean this_present_maxWaitMs = true; boolean that_present_maxWaitMs = true; if (this_present_maxWaitMs || that_present_maxWaitMs) { if (!(this_present_maxWaitMs && that_present_maxWaitMs)) return false; if (this.maxWaitMs != that.maxWaitMs) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(acquireLock_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetMaxWaitMs()).compareTo(other.isSetMaxWaitMs()); if (lastComparison != 0) { return lastComparison; } if (isSetMaxWaitMs()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.maxWaitMs, other.maxWaitMs); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("acquireLock_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; if (!first) sb.append(", "); sb.append("maxWaitMs:"); sb.append(this.maxWaitMs); first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class acquireLock_argsStandardSchemeFactory implements SchemeFactory { public acquireLock_argsStandardScheme getScheme() { return new acquireLock_argsStandardScheme(); } } private static class acquireLock_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, acquireLock_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // MAX_WAIT_MS if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.maxWaitMs = iprot.readI32(); struct.setMaxWaitMsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, acquireLock_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } oprot.writeFieldBegin(MAX_WAIT_MS_FIELD_DESC); oprot.writeI32(struct.maxWaitMs); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class acquireLock_argsTupleSchemeFactory implements SchemeFactory { public acquireLock_argsTupleScheme getScheme() { return new acquireLock_argsTupleScheme(); } } private static class acquireLock_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, acquireLock_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetPath()) { optionals.set(1); } if (struct.isSetMaxWaitMs()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetPath()) { oprot.writeString(struct.path); } if (struct.isSetMaxWaitMs()) { oprot.writeI32(struct.maxWaitMs); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, acquireLock_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } if (incoming.get(2)) { struct.maxWaitMs = iprot.readI32(); struct.setMaxWaitMsIsSet(true); } } } } public static class acquireLock_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("acquireLock_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new acquireLock_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new acquireLock_resultTupleSchemeFactory()); } public OptionalLockProjection success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, OptionalLockProjection.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(acquireLock_result.class, metaDataMap); } public acquireLock_result() { } public acquireLock_result( OptionalLockProjection success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public acquireLock_result(acquireLock_result other) { if (other.isSetSuccess()) { this.success = new OptionalLockProjection(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public acquireLock_result deepCopy() { return new acquireLock_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public OptionalLockProjection getSuccess() { return this.success; } public acquireLock_result setSuccess(OptionalLockProjection success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public acquireLock_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((OptionalLockProjection)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof acquireLock_result) return this.equals((acquireLock_result)that); return false; } public boolean equals(acquireLock_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(acquireLock_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("acquireLock_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class acquireLock_resultStandardSchemeFactory implements SchemeFactory { public acquireLock_resultStandardScheme getScheme() { return new acquireLock_resultStandardScheme(); } } private static class acquireLock_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, acquireLock_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new OptionalLockProjection(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, acquireLock_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class acquireLock_resultTupleSchemeFactory implements SchemeFactory { public acquireLock_resultTupleScheme getScheme() { return new acquireLock_resultTupleScheme(); } } private static class acquireLock_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, acquireLock_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, acquireLock_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new OptionalLockProjection(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class acquireSemaphore_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("acquireSemaphore_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField ACQUIRE_QTY_FIELD_DESC = new org.apache.thrift.protocol.TField("acquireQty", org.apache.thrift.protocol.TType.I32, (short)3); private static final org.apache.thrift.protocol.TField MAX_WAIT_MS_FIELD_DESC = new org.apache.thrift.protocol.TField("maxWaitMs", org.apache.thrift.protocol.TType.I32, (short)4); private static final org.apache.thrift.protocol.TField MAX_LEASES_FIELD_DESC = new org.apache.thrift.protocol.TField("maxLeases", org.apache.thrift.protocol.TType.I32, (short)5); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new acquireSemaphore_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new acquireSemaphore_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public String path; // required public int acquireQty; // required public int maxWaitMs; // required public int maxLeases; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), PATH((short)2, "path"), ACQUIRE_QTY((short)3, "acquireQty"), MAX_WAIT_MS((short)4, "maxWaitMs"), MAX_LEASES((short)5, "maxLeases"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // PATH return PATH; case 3: // ACQUIRE_QTY return ACQUIRE_QTY; case 4: // MAX_WAIT_MS return MAX_WAIT_MS; case 5: // MAX_LEASES return MAX_LEASES; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __ACQUIREQTY_ISSET_ID = 0; private static final int __MAXWAITMS_ISSET_ID = 1; private static final int __MAXLEASES_ISSET_ID = 2; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.ACQUIRE_QTY, new org.apache.thrift.meta_data.FieldMetaData("acquireQty", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.MAX_WAIT_MS, new org.apache.thrift.meta_data.FieldMetaData("maxWaitMs", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.MAX_LEASES, new org.apache.thrift.meta_data.FieldMetaData("maxLeases", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(acquireSemaphore_args.class, metaDataMap); } public acquireSemaphore_args() { } public acquireSemaphore_args( CuratorProjection projection, String path, int acquireQty, int maxWaitMs, int maxLeases) { this(); this.projection = projection; this.path = path; this.acquireQty = acquireQty; setAcquireQtyIsSet(true); this.maxWaitMs = maxWaitMs; setMaxWaitMsIsSet(true); this.maxLeases = maxLeases; setMaxLeasesIsSet(true); } /** * Performs a deep copy on other. */ public acquireSemaphore_args(acquireSemaphore_args other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetPath()) { this.path = other.path; } this.acquireQty = other.acquireQty; this.maxWaitMs = other.maxWaitMs; this.maxLeases = other.maxLeases; } public acquireSemaphore_args deepCopy() { return new acquireSemaphore_args(this); } @Override public void clear() { this.projection = null; this.path = null; setAcquireQtyIsSet(false); this.acquireQty = 0; setMaxWaitMsIsSet(false); this.maxWaitMs = 0; setMaxLeasesIsSet(false); this.maxLeases = 0; } public CuratorProjection getProjection() { return this.projection; } public acquireSemaphore_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public String getPath() { return this.path; } public acquireSemaphore_args setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public int getAcquireQty() { return this.acquireQty; } public acquireSemaphore_args setAcquireQty(int acquireQty) { this.acquireQty = acquireQty; setAcquireQtyIsSet(true); return this; } public void unsetAcquireQty() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __ACQUIREQTY_ISSET_ID); } /** Returns true if field acquireQty is set (has been assigned a value) and false otherwise */ public boolean isSetAcquireQty() { return EncodingUtils.testBit(__isset_bitfield, __ACQUIREQTY_ISSET_ID); } public void setAcquireQtyIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __ACQUIREQTY_ISSET_ID, value); } public int getMaxWaitMs() { return this.maxWaitMs; } public acquireSemaphore_args setMaxWaitMs(int maxWaitMs) { this.maxWaitMs = maxWaitMs; setMaxWaitMsIsSet(true); return this; } public void unsetMaxWaitMs() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __MAXWAITMS_ISSET_ID); } /** Returns true if field maxWaitMs is set (has been assigned a value) and false otherwise */ public boolean isSetMaxWaitMs() { return EncodingUtils.testBit(__isset_bitfield, __MAXWAITMS_ISSET_ID); } public void setMaxWaitMsIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __MAXWAITMS_ISSET_ID, value); } public int getMaxLeases() { return this.maxLeases; } public acquireSemaphore_args setMaxLeases(int maxLeases) { this.maxLeases = maxLeases; setMaxLeasesIsSet(true); return this; } public void unsetMaxLeases() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __MAXLEASES_ISSET_ID); } /** Returns true if field maxLeases is set (has been assigned a value) and false otherwise */ public boolean isSetMaxLeases() { return EncodingUtils.testBit(__isset_bitfield, __MAXLEASES_ISSET_ID); } public void setMaxLeasesIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __MAXLEASES_ISSET_ID, value); } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; case ACQUIRE_QTY: if (value == null) { unsetAcquireQty(); } else { setAcquireQty((Integer)value); } break; case MAX_WAIT_MS: if (value == null) { unsetMaxWaitMs(); } else { setMaxWaitMs((Integer)value); } break; case MAX_LEASES: if (value == null) { unsetMaxLeases(); } else { setMaxLeases((Integer)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case PATH: return getPath(); case ACQUIRE_QTY: return Integer.valueOf(getAcquireQty()); case MAX_WAIT_MS: return Integer.valueOf(getMaxWaitMs()); case MAX_LEASES: return Integer.valueOf(getMaxLeases()); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case PATH: return isSetPath(); case ACQUIRE_QTY: return isSetAcquireQty(); case MAX_WAIT_MS: return isSetMaxWaitMs(); case MAX_LEASES: return isSetMaxLeases(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof acquireSemaphore_args) return this.equals((acquireSemaphore_args)that); return false; } public boolean equals(acquireSemaphore_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } boolean this_present_acquireQty = true; boolean that_present_acquireQty = true; if (this_present_acquireQty || that_present_acquireQty) { if (!(this_present_acquireQty && that_present_acquireQty)) return false; if (this.acquireQty != that.acquireQty) return false; } boolean this_present_maxWaitMs = true; boolean that_present_maxWaitMs = true; if (this_present_maxWaitMs || that_present_maxWaitMs) { if (!(this_present_maxWaitMs && that_present_maxWaitMs)) return false; if (this.maxWaitMs != that.maxWaitMs) return false; } boolean this_present_maxLeases = true; boolean that_present_maxLeases = true; if (this_present_maxLeases || that_present_maxLeases) { if (!(this_present_maxLeases && that_present_maxLeases)) return false; if (this.maxLeases != that.maxLeases) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(acquireSemaphore_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetAcquireQty()).compareTo(other.isSetAcquireQty()); if (lastComparison != 0) { return lastComparison; } if (isSetAcquireQty()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.acquireQty, other.acquireQty); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetMaxWaitMs()).compareTo(other.isSetMaxWaitMs()); if (lastComparison != 0) { return lastComparison; } if (isSetMaxWaitMs()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.maxWaitMs, other.maxWaitMs); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetMaxLeases()).compareTo(other.isSetMaxLeases()); if (lastComparison != 0) { return lastComparison; } if (isSetMaxLeases()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.maxLeases, other.maxLeases); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("acquireSemaphore_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; if (!first) sb.append(", "); sb.append("acquireQty:"); sb.append(this.acquireQty); first = false; if (!first) sb.append(", "); sb.append("maxWaitMs:"); sb.append(this.maxWaitMs); first = false; if (!first) sb.append(", "); sb.append("maxLeases:"); sb.append(this.maxLeases); first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class acquireSemaphore_argsStandardSchemeFactory implements SchemeFactory { public acquireSemaphore_argsStandardScheme getScheme() { return new acquireSemaphore_argsStandardScheme(); } } private static class acquireSemaphore_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, acquireSemaphore_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // ACQUIRE_QTY if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.acquireQty = iprot.readI32(); struct.setAcquireQtyIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // MAX_WAIT_MS if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.maxWaitMs = iprot.readI32(); struct.setMaxWaitMsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // MAX_LEASES if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.maxLeases = iprot.readI32(); struct.setMaxLeasesIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, acquireSemaphore_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } oprot.writeFieldBegin(ACQUIRE_QTY_FIELD_DESC); oprot.writeI32(struct.acquireQty); oprot.writeFieldEnd(); oprot.writeFieldBegin(MAX_WAIT_MS_FIELD_DESC); oprot.writeI32(struct.maxWaitMs); oprot.writeFieldEnd(); oprot.writeFieldBegin(MAX_LEASES_FIELD_DESC); oprot.writeI32(struct.maxLeases); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class acquireSemaphore_argsTupleSchemeFactory implements SchemeFactory { public acquireSemaphore_argsTupleScheme getScheme() { return new acquireSemaphore_argsTupleScheme(); } } private static class acquireSemaphore_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, acquireSemaphore_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetPath()) { optionals.set(1); } if (struct.isSetAcquireQty()) { optionals.set(2); } if (struct.isSetMaxWaitMs()) { optionals.set(3); } if (struct.isSetMaxLeases()) { optionals.set(4); } oprot.writeBitSet(optionals, 5); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetPath()) { oprot.writeString(struct.path); } if (struct.isSetAcquireQty()) { oprot.writeI32(struct.acquireQty); } if (struct.isSetMaxWaitMs()) { oprot.writeI32(struct.maxWaitMs); } if (struct.isSetMaxLeases()) { oprot.writeI32(struct.maxLeases); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, acquireSemaphore_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(5); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } if (incoming.get(2)) { struct.acquireQty = iprot.readI32(); struct.setAcquireQtyIsSet(true); } if (incoming.get(3)) { struct.maxWaitMs = iprot.readI32(); struct.setMaxWaitMsIsSet(true); } if (incoming.get(4)) { struct.maxLeases = iprot.readI32(); struct.setMaxLeasesIsSet(true); } } } } public static class acquireSemaphore_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("acquireSemaphore_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.LIST, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new acquireSemaphore_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new acquireSemaphore_resultTupleSchemeFactory()); } public List success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, LeaseProjection.class)))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(acquireSemaphore_result.class, metaDataMap); } public acquireSemaphore_result() { } public acquireSemaphore_result( List success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public acquireSemaphore_result(acquireSemaphore_result other) { if (other.isSetSuccess()) { List __this__success = new ArrayList(other.success.size()); for (LeaseProjection other_element : other.success) { __this__success.add(new LeaseProjection(other_element)); } this.success = __this__success; } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public acquireSemaphore_result deepCopy() { return new acquireSemaphore_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public int getSuccessSize() { return (this.success == null) ? 0 : this.success.size(); } public java.util.Iterator getSuccessIterator() { return (this.success == null) ? null : this.success.iterator(); } public void addToSuccess(LeaseProjection elem) { if (this.success == null) { this.success = new ArrayList(); } this.success.add(elem); } public List getSuccess() { return this.success; } public acquireSemaphore_result setSuccess(List success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public acquireSemaphore_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((List)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof acquireSemaphore_result) return this.equals((acquireSemaphore_result)that); return false; } public boolean equals(acquireSemaphore_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(acquireSemaphore_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("acquireSemaphore_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class acquireSemaphore_resultStandardSchemeFactory implements SchemeFactory { public acquireSemaphore_resultStandardScheme getScheme() { return new acquireSemaphore_resultStandardScheme(); } } private static class acquireSemaphore_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, acquireSemaphore_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list24 = iprot.readListBegin(); struct.success = new ArrayList(_list24.size); for (int _i25 = 0; _i25 < _list24.size; ++_i25) { LeaseProjection _elem26; _elem26 = new LeaseProjection(); _elem26.read(iprot); struct.success.add(_elem26); } iprot.readListEnd(); } struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, acquireSemaphore_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.success.size())); for (LeaseProjection _iter27 : struct.success) { _iter27.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class acquireSemaphore_resultTupleSchemeFactory implements SchemeFactory { public acquireSemaphore_resultTupleScheme getScheme() { return new acquireSemaphore_resultTupleScheme(); } } private static class acquireSemaphore_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, acquireSemaphore_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { { oprot.writeI32(struct.success.size()); for (LeaseProjection _iter28 : struct.success) { _iter28.write(oprot); } } } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, acquireSemaphore_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { { org.apache.thrift.protocol.TList _list29 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.success = new ArrayList(_list29.size); for (int _i30 = 0; _i30 < _list29.size; ++_i30) { LeaseProjection _elem31; _elem31 = new LeaseProjection(); _elem31.read(iprot); struct.success.add(_elem31); } } struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class closeCuratorProjection_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("closeCuratorProjection_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new closeCuratorProjection_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new closeCuratorProjection_argsTupleSchemeFactory()); } public CuratorProjection projection; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(closeCuratorProjection_args.class, metaDataMap); } public closeCuratorProjection_args() { } public closeCuratorProjection_args( CuratorProjection projection) { this(); this.projection = projection; } /** * Performs a deep copy on other. */ public closeCuratorProjection_args(closeCuratorProjection_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } } public closeCuratorProjection_args deepCopy() { return new closeCuratorProjection_args(this); } @Override public void clear() { this.projection = null; } public CuratorProjection getProjection() { return this.projection; } public closeCuratorProjection_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof closeCuratorProjection_args) return this.equals((closeCuratorProjection_args)that); return false; } public boolean equals(closeCuratorProjection_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(closeCuratorProjection_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("closeCuratorProjection_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class closeCuratorProjection_argsStandardSchemeFactory implements SchemeFactory { public closeCuratorProjection_argsStandardScheme getScheme() { return new closeCuratorProjection_argsStandardScheme(); } } private static class closeCuratorProjection_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, closeCuratorProjection_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, closeCuratorProjection_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class closeCuratorProjection_argsTupleSchemeFactory implements SchemeFactory { public closeCuratorProjection_argsTupleScheme getScheme() { return new closeCuratorProjection_argsTupleScheme(); } } private static class closeCuratorProjection_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, closeCuratorProjection_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetProjection()) { struct.projection.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, closeCuratorProjection_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } } } } public static class closeCuratorProjection_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("closeCuratorProjection_result"); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new closeCuratorProjection_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new closeCuratorProjection_resultTupleSchemeFactory()); } /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ; private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(closeCuratorProjection_result.class, metaDataMap); } public closeCuratorProjection_result() { } /** * Performs a deep copy on other. */ public closeCuratorProjection_result(closeCuratorProjection_result other) { } public closeCuratorProjection_result deepCopy() { return new closeCuratorProjection_result(this); } @Override public void clear() { } public void setFieldValue(_Fields field, Object value) { switch (field) { } } public Object getFieldValue(_Fields field) { switch (field) { } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof closeCuratorProjection_result) return this.equals((closeCuratorProjection_result)that); return false; } public boolean equals(closeCuratorProjection_result that) { if (that == null) return false; return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(closeCuratorProjection_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("closeCuratorProjection_result("); boolean first = true; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class closeCuratorProjection_resultStandardSchemeFactory implements SchemeFactory { public closeCuratorProjection_resultStandardScheme getScheme() { return new closeCuratorProjection_resultStandardScheme(); } } private static class closeCuratorProjection_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, closeCuratorProjection_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, closeCuratorProjection_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class closeCuratorProjection_resultTupleSchemeFactory implements SchemeFactory { public closeCuratorProjection_resultTupleScheme getScheme() { return new closeCuratorProjection_resultTupleScheme(); } } private static class closeCuratorProjection_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, closeCuratorProjection_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; } @Override public void read(org.apache.thrift.protocol.TProtocol prot, closeCuratorProjection_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; } } } public static class closeGenericProjection_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("closeGenericProjection_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.STRING, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new closeGenericProjection_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new closeGenericProjection_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public String id; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), ID((short)2, "id"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // ID return ID; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(closeGenericProjection_args.class, metaDataMap); } public closeGenericProjection_args() { } public closeGenericProjection_args( CuratorProjection projection, String id) { this(); this.projection = projection; this.id = id; } /** * Performs a deep copy on other. */ public closeGenericProjection_args(closeGenericProjection_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetId()) { this.id = other.id; } } public closeGenericProjection_args deepCopy() { return new closeGenericProjection_args(this); } @Override public void clear() { this.projection = null; this.id = null; } public CuratorProjection getProjection() { return this.projection; } public closeGenericProjection_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public String getId() { return this.id; } public closeGenericProjection_args setId(String id) { this.id = id; return this; } public void unsetId() { this.id = null; } /** Returns true if field id is set (has been assigned a value) and false otherwise */ public boolean isSetId() { return this.id != null; } public void setIdIsSet(boolean value) { if (!value) { this.id = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case ID: if (value == null) { unsetId(); } else { setId((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case ID: return getId(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case ID: return isSetId(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof closeGenericProjection_args) return this.equals((closeGenericProjection_args)that); return false; } public boolean equals(closeGenericProjection_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_id = true && this.isSetId(); boolean that_present_id = true && that.isSetId(); if (this_present_id || that_present_id) { if (!(this_present_id && that_present_id)) return false; if (!this.id.equals(that.id)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(closeGenericProjection_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); if (lastComparison != 0) { return lastComparison; } if (isSetId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("closeGenericProjection_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("id:"); if (this.id == null) { sb.append("null"); } else { sb.append(this.id); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class closeGenericProjection_argsStandardSchemeFactory implements SchemeFactory { public closeGenericProjection_argsStandardScheme getScheme() { return new closeGenericProjection_argsStandardScheme(); } } private static class closeGenericProjection_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, closeGenericProjection_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.id = iprot.readString(); struct.setIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, closeGenericProjection_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.id != null) { oprot.writeFieldBegin(ID_FIELD_DESC); oprot.writeString(struct.id); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class closeGenericProjection_argsTupleSchemeFactory implements SchemeFactory { public closeGenericProjection_argsTupleScheme getScheme() { return new closeGenericProjection_argsTupleScheme(); } } private static class closeGenericProjection_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, closeGenericProjection_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetId()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetId()) { oprot.writeString(struct.id); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, closeGenericProjection_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.id = iprot.readString(); struct.setIdIsSet(true); } } } } public static class closeGenericProjection_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("closeGenericProjection_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BOOL, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new closeGenericProjection_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new closeGenericProjection_resultTupleSchemeFactory()); } public boolean success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __SUCCESS_ISSET_ID = 0; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(closeGenericProjection_result.class, metaDataMap); } public closeGenericProjection_result() { } public closeGenericProjection_result( boolean success, CuratorException ex1) { this(); this.success = success; setSuccessIsSet(true); this.ex1 = ex1; } /** * Performs a deep copy on other. */ public closeGenericProjection_result(closeGenericProjection_result other) { __isset_bitfield = other.__isset_bitfield; this.success = other.success; if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public closeGenericProjection_result deepCopy() { return new closeGenericProjection_result(this); } @Override public void clear() { setSuccessIsSet(false); this.success = false; this.ex1 = null; } public boolean isSuccess() { return this.success; } public closeGenericProjection_result setSuccess(boolean success) { this.success = success; setSuccessIsSet(true); return this; } public void unsetSuccess() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID); } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID); } public void setSuccessIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value); } public CuratorException getEx1() { return this.ex1; } public closeGenericProjection_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((Boolean)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return Boolean.valueOf(isSuccess()); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof closeGenericProjection_result) return this.equals((closeGenericProjection_result)that); return false; } public boolean equals(closeGenericProjection_result that) { if (that == null) return false; boolean this_present_success = true; boolean that_present_success = true; if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (this.success != that.success) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(closeGenericProjection_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("closeGenericProjection_result("); boolean first = true; sb.append("success:"); sb.append(this.success); first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class closeGenericProjection_resultStandardSchemeFactory implements SchemeFactory { public closeGenericProjection_resultStandardScheme getScheme() { return new closeGenericProjection_resultStandardScheme(); } } private static class closeGenericProjection_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, closeGenericProjection_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.success = iprot.readBool(); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, closeGenericProjection_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.isSetSuccess()) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); oprot.writeBool(struct.success); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class closeGenericProjection_resultTupleSchemeFactory implements SchemeFactory { public closeGenericProjection_resultTupleScheme getScheme() { return new closeGenericProjection_resultTupleScheme(); } } private static class closeGenericProjection_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, closeGenericProjection_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { oprot.writeBool(struct.success); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, closeGenericProjection_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = iprot.readBool(); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class createNode_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("createNode_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField SPEC_FIELD_DESC = new org.apache.thrift.protocol.TField("spec", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new createNode_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new createNode_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public CreateSpec spec; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), SPEC((short)2, "spec"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // SPEC return SPEC; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.SPEC, new org.apache.thrift.meta_data.FieldMetaData("spec", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CreateSpec.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(createNode_args.class, metaDataMap); } public createNode_args() { } public createNode_args( CuratorProjection projection, CreateSpec spec) { this(); this.projection = projection; this.spec = spec; } /** * Performs a deep copy on other. */ public createNode_args(createNode_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetSpec()) { this.spec = new CreateSpec(other.spec); } } public createNode_args deepCopy() { return new createNode_args(this); } @Override public void clear() { this.projection = null; this.spec = null; } public CuratorProjection getProjection() { return this.projection; } public createNode_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public CreateSpec getSpec() { return this.spec; } public createNode_args setSpec(CreateSpec spec) { this.spec = spec; return this; } public void unsetSpec() { this.spec = null; } /** Returns true if field spec is set (has been assigned a value) and false otherwise */ public boolean isSetSpec() { return this.spec != null; } public void setSpecIsSet(boolean value) { if (!value) { this.spec = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case SPEC: if (value == null) { unsetSpec(); } else { setSpec((CreateSpec)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case SPEC: return getSpec(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case SPEC: return isSetSpec(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof createNode_args) return this.equals((createNode_args)that); return false; } public boolean equals(createNode_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_spec = true && this.isSetSpec(); boolean that_present_spec = true && that.isSetSpec(); if (this_present_spec || that_present_spec) { if (!(this_present_spec && that_present_spec)) return false; if (!this.spec.equals(that.spec)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(createNode_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetSpec()).compareTo(other.isSetSpec()); if (lastComparison != 0) { return lastComparison; } if (isSetSpec()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.spec, other.spec); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("createNode_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("spec:"); if (this.spec == null) { sb.append("null"); } else { sb.append(this.spec); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (spec != null) { spec.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class createNode_argsStandardSchemeFactory implements SchemeFactory { public createNode_argsStandardScheme getScheme() { return new createNode_argsStandardScheme(); } } private static class createNode_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, createNode_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // SPEC if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.spec = new CreateSpec(); struct.spec.read(iprot); struct.setSpecIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, createNode_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.spec != null) { oprot.writeFieldBegin(SPEC_FIELD_DESC); struct.spec.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class createNode_argsTupleSchemeFactory implements SchemeFactory { public createNode_argsTupleScheme getScheme() { return new createNode_argsTupleScheme(); } } private static class createNode_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, createNode_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetSpec()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetSpec()) { struct.spec.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, createNode_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.spec = new CreateSpec(); struct.spec.read(iprot); struct.setSpecIsSet(true); } } } } public static class createNode_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("createNode_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new createNode_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new createNode_resultTupleSchemeFactory()); } public OptionalPath success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, OptionalPath.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(createNode_result.class, metaDataMap); } public createNode_result() { } public createNode_result( OptionalPath success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public createNode_result(createNode_result other) { if (other.isSetSuccess()) { this.success = new OptionalPath(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public createNode_result deepCopy() { return new createNode_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public OptionalPath getSuccess() { return this.success; } public createNode_result setSuccess(OptionalPath success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public createNode_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((OptionalPath)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof createNode_result) return this.equals((createNode_result)that); return false; } public boolean equals(createNode_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(createNode_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("createNode_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class createNode_resultStandardSchemeFactory implements SchemeFactory { public createNode_resultStandardScheme getScheme() { return new createNode_resultStandardScheme(); } } private static class createNode_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, createNode_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new OptionalPath(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, createNode_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class createNode_resultTupleSchemeFactory implements SchemeFactory { public createNode_resultTupleScheme getScheme() { return new createNode_resultTupleScheme(); } } private static class createNode_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, createNode_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, createNode_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new OptionalPath(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class deleteNode_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("deleteNode_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField SPEC_FIELD_DESC = new org.apache.thrift.protocol.TField("spec", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new deleteNode_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new deleteNode_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public DeleteSpec spec; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), SPEC((short)2, "spec"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // SPEC return SPEC; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.SPEC, new org.apache.thrift.meta_data.FieldMetaData("spec", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DeleteSpec.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(deleteNode_args.class, metaDataMap); } public deleteNode_args() { } public deleteNode_args( CuratorProjection projection, DeleteSpec spec) { this(); this.projection = projection; this.spec = spec; } /** * Performs a deep copy on other. */ public deleteNode_args(deleteNode_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetSpec()) { this.spec = new DeleteSpec(other.spec); } } public deleteNode_args deepCopy() { return new deleteNode_args(this); } @Override public void clear() { this.projection = null; this.spec = null; } public CuratorProjection getProjection() { return this.projection; } public deleteNode_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public DeleteSpec getSpec() { return this.spec; } public deleteNode_args setSpec(DeleteSpec spec) { this.spec = spec; return this; } public void unsetSpec() { this.spec = null; } /** Returns true if field spec is set (has been assigned a value) and false otherwise */ public boolean isSetSpec() { return this.spec != null; } public void setSpecIsSet(boolean value) { if (!value) { this.spec = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case SPEC: if (value == null) { unsetSpec(); } else { setSpec((DeleteSpec)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case SPEC: return getSpec(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case SPEC: return isSetSpec(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof deleteNode_args) return this.equals((deleteNode_args)that); return false; } public boolean equals(deleteNode_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_spec = true && this.isSetSpec(); boolean that_present_spec = true && that.isSetSpec(); if (this_present_spec || that_present_spec) { if (!(this_present_spec && that_present_spec)) return false; if (!this.spec.equals(that.spec)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(deleteNode_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetSpec()).compareTo(other.isSetSpec()); if (lastComparison != 0) { return lastComparison; } if (isSetSpec()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.spec, other.spec); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("deleteNode_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("spec:"); if (this.spec == null) { sb.append("null"); } else { sb.append(this.spec); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (spec != null) { spec.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class deleteNode_argsStandardSchemeFactory implements SchemeFactory { public deleteNode_argsStandardScheme getScheme() { return new deleteNode_argsStandardScheme(); } } private static class deleteNode_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, deleteNode_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // SPEC if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.spec = new DeleteSpec(); struct.spec.read(iprot); struct.setSpecIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, deleteNode_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.spec != null) { oprot.writeFieldBegin(SPEC_FIELD_DESC); struct.spec.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class deleteNode_argsTupleSchemeFactory implements SchemeFactory { public deleteNode_argsTupleScheme getScheme() { return new deleteNode_argsTupleScheme(); } } private static class deleteNode_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, deleteNode_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetSpec()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetSpec()) { struct.spec.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, deleteNode_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.spec = new DeleteSpec(); struct.spec.read(iprot); struct.setSpecIsSet(true); } } } } public static class deleteNode_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("deleteNode_result"); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new deleteNode_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new deleteNode_resultTupleSchemeFactory()); } public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(deleteNode_result.class, metaDataMap); } public deleteNode_result() { } public deleteNode_result( CuratorException ex1) { this(); this.ex1 = ex1; } /** * Performs a deep copy on other. */ public deleteNode_result(deleteNode_result other) { if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public deleteNode_result deepCopy() { return new deleteNode_result(this); } @Override public void clear() { this.ex1 = null; } public CuratorException getEx1() { return this.ex1; } public deleteNode_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof deleteNode_result) return this.equals((deleteNode_result)that); return false; } public boolean equals(deleteNode_result that) { if (that == null) return false; boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(deleteNode_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("deleteNode_result("); boolean first = true; sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class deleteNode_resultStandardSchemeFactory implements SchemeFactory { public deleteNode_resultStandardScheme getScheme() { return new deleteNode_resultStandardScheme(); } } private static class deleteNode_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, deleteNode_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, deleteNode_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class deleteNode_resultTupleSchemeFactory implements SchemeFactory { public deleteNode_resultTupleScheme getScheme() { return new deleteNode_resultTupleScheme(); } } private static class deleteNode_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, deleteNode_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetEx1()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, deleteNode_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class exists_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("exists_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField SPEC_FIELD_DESC = new org.apache.thrift.protocol.TField("spec", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new exists_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new exists_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public ExistsSpec spec; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), SPEC((short)2, "spec"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // SPEC return SPEC; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.SPEC, new org.apache.thrift.meta_data.FieldMetaData("spec", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, ExistsSpec.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(exists_args.class, metaDataMap); } public exists_args() { } public exists_args( CuratorProjection projection, ExistsSpec spec) { this(); this.projection = projection; this.spec = spec; } /** * Performs a deep copy on other. */ public exists_args(exists_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetSpec()) { this.spec = new ExistsSpec(other.spec); } } public exists_args deepCopy() { return new exists_args(this); } @Override public void clear() { this.projection = null; this.spec = null; } public CuratorProjection getProjection() { return this.projection; } public exists_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public ExistsSpec getSpec() { return this.spec; } public exists_args setSpec(ExistsSpec spec) { this.spec = spec; return this; } public void unsetSpec() { this.spec = null; } /** Returns true if field spec is set (has been assigned a value) and false otherwise */ public boolean isSetSpec() { return this.spec != null; } public void setSpecIsSet(boolean value) { if (!value) { this.spec = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case SPEC: if (value == null) { unsetSpec(); } else { setSpec((ExistsSpec)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case SPEC: return getSpec(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case SPEC: return isSetSpec(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof exists_args) return this.equals((exists_args)that); return false; } public boolean equals(exists_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_spec = true && this.isSetSpec(); boolean that_present_spec = true && that.isSetSpec(); if (this_present_spec || that_present_spec) { if (!(this_present_spec && that_present_spec)) return false; if (!this.spec.equals(that.spec)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(exists_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetSpec()).compareTo(other.isSetSpec()); if (lastComparison != 0) { return lastComparison; } if (isSetSpec()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.spec, other.spec); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("exists_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("spec:"); if (this.spec == null) { sb.append("null"); } else { sb.append(this.spec); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (spec != null) { spec.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class exists_argsStandardSchemeFactory implements SchemeFactory { public exists_argsStandardScheme getScheme() { return new exists_argsStandardScheme(); } } private static class exists_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, exists_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // SPEC if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.spec = new ExistsSpec(); struct.spec.read(iprot); struct.setSpecIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, exists_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.spec != null) { oprot.writeFieldBegin(SPEC_FIELD_DESC); struct.spec.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class exists_argsTupleSchemeFactory implements SchemeFactory { public exists_argsTupleScheme getScheme() { return new exists_argsTupleScheme(); } } private static class exists_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, exists_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetSpec()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetSpec()) { struct.spec.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, exists_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.spec = new ExistsSpec(); struct.spec.read(iprot); struct.setSpecIsSet(true); } } } } public static class exists_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("exists_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new exists_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new exists_resultTupleSchemeFactory()); } public OptionalStat success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, OptionalStat.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(exists_result.class, metaDataMap); } public exists_result() { } public exists_result( OptionalStat success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public exists_result(exists_result other) { if (other.isSetSuccess()) { this.success = new OptionalStat(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public exists_result deepCopy() { return new exists_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public OptionalStat getSuccess() { return this.success; } public exists_result setSuccess(OptionalStat success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public exists_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((OptionalStat)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof exists_result) return this.equals((exists_result)that); return false; } public boolean equals(exists_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(exists_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("exists_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class exists_resultStandardSchemeFactory implements SchemeFactory { public exists_resultStandardScheme getScheme() { return new exists_resultStandardScheme(); } } private static class exists_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, exists_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new OptionalStat(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, exists_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class exists_resultTupleSchemeFactory implements SchemeFactory { public exists_resultTupleScheme getScheme() { return new exists_resultTupleScheme(); } } private static class exists_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, exists_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, exists_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new OptionalStat(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class getChildren_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getChildren_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField SPEC_FIELD_DESC = new org.apache.thrift.protocol.TField("spec", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getChildren_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new getChildren_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public GetChildrenSpec spec; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), SPEC((short)2, "spec"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // SPEC return SPEC; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.SPEC, new org.apache.thrift.meta_data.FieldMetaData("spec", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, GetChildrenSpec.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getChildren_args.class, metaDataMap); } public getChildren_args() { } public getChildren_args( CuratorProjection projection, GetChildrenSpec spec) { this(); this.projection = projection; this.spec = spec; } /** * Performs a deep copy on other. */ public getChildren_args(getChildren_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetSpec()) { this.spec = new GetChildrenSpec(other.spec); } } public getChildren_args deepCopy() { return new getChildren_args(this); } @Override public void clear() { this.projection = null; this.spec = null; } public CuratorProjection getProjection() { return this.projection; } public getChildren_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public GetChildrenSpec getSpec() { return this.spec; } public getChildren_args setSpec(GetChildrenSpec spec) { this.spec = spec; return this; } public void unsetSpec() { this.spec = null; } /** Returns true if field spec is set (has been assigned a value) and false otherwise */ public boolean isSetSpec() { return this.spec != null; } public void setSpecIsSet(boolean value) { if (!value) { this.spec = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case SPEC: if (value == null) { unsetSpec(); } else { setSpec((GetChildrenSpec)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case SPEC: return getSpec(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case SPEC: return isSetSpec(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getChildren_args) return this.equals((getChildren_args)that); return false; } public boolean equals(getChildren_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_spec = true && this.isSetSpec(); boolean that_present_spec = true && that.isSetSpec(); if (this_present_spec || that_present_spec) { if (!(this_present_spec && that_present_spec)) return false; if (!this.spec.equals(that.spec)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getChildren_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetSpec()).compareTo(other.isSetSpec()); if (lastComparison != 0) { return lastComparison; } if (isSetSpec()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.spec, other.spec); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getChildren_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("spec:"); if (this.spec == null) { sb.append("null"); } else { sb.append(this.spec); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (spec != null) { spec.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getChildren_argsStandardSchemeFactory implements SchemeFactory { public getChildren_argsStandardScheme getScheme() { return new getChildren_argsStandardScheme(); } } private static class getChildren_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getChildren_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // SPEC if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.spec = new GetChildrenSpec(); struct.spec.read(iprot); struct.setSpecIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getChildren_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.spec != null) { oprot.writeFieldBegin(SPEC_FIELD_DESC); struct.spec.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getChildren_argsTupleSchemeFactory implements SchemeFactory { public getChildren_argsTupleScheme getScheme() { return new getChildren_argsTupleScheme(); } } private static class getChildren_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getChildren_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetSpec()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetSpec()) { struct.spec.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getChildren_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.spec = new GetChildrenSpec(); struct.spec.read(iprot); struct.setSpecIsSet(true); } } } } public static class getChildren_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getChildren_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getChildren_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new getChildren_resultTupleSchemeFactory()); } public OptionalChildrenList success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, OptionalChildrenList.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getChildren_result.class, metaDataMap); } public getChildren_result() { } public getChildren_result( OptionalChildrenList success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public getChildren_result(getChildren_result other) { if (other.isSetSuccess()) { this.success = new OptionalChildrenList(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public getChildren_result deepCopy() { return new getChildren_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public OptionalChildrenList getSuccess() { return this.success; } public getChildren_result setSuccess(OptionalChildrenList success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public getChildren_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((OptionalChildrenList)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getChildren_result) return this.equals((getChildren_result)that); return false; } public boolean equals(getChildren_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getChildren_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getChildren_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getChildren_resultStandardSchemeFactory implements SchemeFactory { public getChildren_resultStandardScheme getScheme() { return new getChildren_resultStandardScheme(); } } private static class getChildren_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getChildren_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new OptionalChildrenList(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getChildren_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getChildren_resultTupleSchemeFactory implements SchemeFactory { public getChildren_resultTupleScheme getScheme() { return new getChildren_resultTupleScheme(); } } private static class getChildren_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getChildren_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getChildren_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new OptionalChildrenList(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class getData_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getData_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField SPEC_FIELD_DESC = new org.apache.thrift.protocol.TField("spec", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getData_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new getData_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public GetDataSpec spec; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), SPEC((short)2, "spec"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // SPEC return SPEC; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.SPEC, new org.apache.thrift.meta_data.FieldMetaData("spec", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, GetDataSpec.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getData_args.class, metaDataMap); } public getData_args() { } public getData_args( CuratorProjection projection, GetDataSpec spec) { this(); this.projection = projection; this.spec = spec; } /** * Performs a deep copy on other. */ public getData_args(getData_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetSpec()) { this.spec = new GetDataSpec(other.spec); } } public getData_args deepCopy() { return new getData_args(this); } @Override public void clear() { this.projection = null; this.spec = null; } public CuratorProjection getProjection() { return this.projection; } public getData_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public GetDataSpec getSpec() { return this.spec; } public getData_args setSpec(GetDataSpec spec) { this.spec = spec; return this; } public void unsetSpec() { this.spec = null; } /** Returns true if field spec is set (has been assigned a value) and false otherwise */ public boolean isSetSpec() { return this.spec != null; } public void setSpecIsSet(boolean value) { if (!value) { this.spec = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case SPEC: if (value == null) { unsetSpec(); } else { setSpec((GetDataSpec)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case SPEC: return getSpec(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case SPEC: return isSetSpec(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getData_args) return this.equals((getData_args)that); return false; } public boolean equals(getData_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_spec = true && this.isSetSpec(); boolean that_present_spec = true && that.isSetSpec(); if (this_present_spec || that_present_spec) { if (!(this_present_spec && that_present_spec)) return false; if (!this.spec.equals(that.spec)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getData_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetSpec()).compareTo(other.isSetSpec()); if (lastComparison != 0) { return lastComparison; } if (isSetSpec()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.spec, other.spec); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getData_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("spec:"); if (this.spec == null) { sb.append("null"); } else { sb.append(this.spec); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (spec != null) { spec.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getData_argsStandardSchemeFactory implements SchemeFactory { public getData_argsStandardScheme getScheme() { return new getData_argsStandardScheme(); } } private static class getData_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getData_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // SPEC if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.spec = new GetDataSpec(); struct.spec.read(iprot); struct.setSpecIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getData_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.spec != null) { oprot.writeFieldBegin(SPEC_FIELD_DESC); struct.spec.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getData_argsTupleSchemeFactory implements SchemeFactory { public getData_argsTupleScheme getScheme() { return new getData_argsTupleScheme(); } } private static class getData_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getData_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetSpec()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetSpec()) { struct.spec.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getData_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.spec = new GetDataSpec(); struct.spec.read(iprot); struct.setSpecIsSet(true); } } } } public static class getData_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getData_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getData_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new getData_resultTupleSchemeFactory()); } public OptionalData success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, OptionalData.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getData_result.class, metaDataMap); } public getData_result() { } public getData_result( OptionalData success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public getData_result(getData_result other) { if (other.isSetSuccess()) { this.success = new OptionalData(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public getData_result deepCopy() { return new getData_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public OptionalData getSuccess() { return this.success; } public getData_result setSuccess(OptionalData success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public getData_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((OptionalData)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getData_result) return this.equals((getData_result)that); return false; } public boolean equals(getData_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getData_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getData_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getData_resultStandardSchemeFactory implements SchemeFactory { public getData_resultStandardScheme getScheme() { return new getData_resultStandardScheme(); } } private static class getData_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getData_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new OptionalData(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getData_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getData_resultTupleSchemeFactory implements SchemeFactory { public getData_resultTupleScheme getScheme() { return new getData_resultTupleScheme(); } } private static class getData_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getData_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getData_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new OptionalData(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class getLeaderParticipants_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getLeaderParticipants_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField LEADER_PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("leaderProjection", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getLeaderParticipants_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new getLeaderParticipants_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public LeaderProjection leaderProjection; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), LEADER_PROJECTION((short)2, "leaderProjection"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // LEADER_PROJECTION return LEADER_PROJECTION; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.LEADER_PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("leaderProjection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, LeaderProjection.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getLeaderParticipants_args.class, metaDataMap); } public getLeaderParticipants_args() { } public getLeaderParticipants_args( CuratorProjection projection, LeaderProjection leaderProjection) { this(); this.projection = projection; this.leaderProjection = leaderProjection; } /** * Performs a deep copy on other. */ public getLeaderParticipants_args(getLeaderParticipants_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetLeaderProjection()) { this.leaderProjection = new LeaderProjection(other.leaderProjection); } } public getLeaderParticipants_args deepCopy() { return new getLeaderParticipants_args(this); } @Override public void clear() { this.projection = null; this.leaderProjection = null; } public CuratorProjection getProjection() { return this.projection; } public getLeaderParticipants_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public LeaderProjection getLeaderProjection() { return this.leaderProjection; } public getLeaderParticipants_args setLeaderProjection(LeaderProjection leaderProjection) { this.leaderProjection = leaderProjection; return this; } public void unsetLeaderProjection() { this.leaderProjection = null; } /** Returns true if field leaderProjection is set (has been assigned a value) and false otherwise */ public boolean isSetLeaderProjection() { return this.leaderProjection != null; } public void setLeaderProjectionIsSet(boolean value) { if (!value) { this.leaderProjection = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case LEADER_PROJECTION: if (value == null) { unsetLeaderProjection(); } else { setLeaderProjection((LeaderProjection)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case LEADER_PROJECTION: return getLeaderProjection(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case LEADER_PROJECTION: return isSetLeaderProjection(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getLeaderParticipants_args) return this.equals((getLeaderParticipants_args)that); return false; } public boolean equals(getLeaderParticipants_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_leaderProjection = true && this.isSetLeaderProjection(); boolean that_present_leaderProjection = true && that.isSetLeaderProjection(); if (this_present_leaderProjection || that_present_leaderProjection) { if (!(this_present_leaderProjection && that_present_leaderProjection)) return false; if (!this.leaderProjection.equals(that.leaderProjection)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getLeaderParticipants_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetLeaderProjection()).compareTo(other.isSetLeaderProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetLeaderProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.leaderProjection, other.leaderProjection); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getLeaderParticipants_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("leaderProjection:"); if (this.leaderProjection == null) { sb.append("null"); } else { sb.append(this.leaderProjection); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (leaderProjection != null) { leaderProjection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getLeaderParticipants_argsStandardSchemeFactory implements SchemeFactory { public getLeaderParticipants_argsStandardScheme getScheme() { return new getLeaderParticipants_argsStandardScheme(); } } private static class getLeaderParticipants_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getLeaderParticipants_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // LEADER_PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.leaderProjection = new LeaderProjection(); struct.leaderProjection.read(iprot); struct.setLeaderProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getLeaderParticipants_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.leaderProjection != null) { oprot.writeFieldBegin(LEADER_PROJECTION_FIELD_DESC); struct.leaderProjection.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getLeaderParticipants_argsTupleSchemeFactory implements SchemeFactory { public getLeaderParticipants_argsTupleScheme getScheme() { return new getLeaderParticipants_argsTupleScheme(); } } private static class getLeaderParticipants_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getLeaderParticipants_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetLeaderProjection()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetLeaderProjection()) { struct.leaderProjection.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getLeaderParticipants_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.leaderProjection = new LeaderProjection(); struct.leaderProjection.read(iprot); struct.setLeaderProjectionIsSet(true); } } } } public static class getLeaderParticipants_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getLeaderParticipants_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.LIST, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getLeaderParticipants_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new getLeaderParticipants_resultTupleSchemeFactory()); } public List success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, Participant.class)))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getLeaderParticipants_result.class, metaDataMap); } public getLeaderParticipants_result() { } public getLeaderParticipants_result( List success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public getLeaderParticipants_result(getLeaderParticipants_result other) { if (other.isSetSuccess()) { List __this__success = new ArrayList(other.success.size()); for (Participant other_element : other.success) { __this__success.add(new Participant(other_element)); } this.success = __this__success; } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public getLeaderParticipants_result deepCopy() { return new getLeaderParticipants_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public int getSuccessSize() { return (this.success == null) ? 0 : this.success.size(); } public java.util.Iterator getSuccessIterator() { return (this.success == null) ? null : this.success.iterator(); } public void addToSuccess(Participant elem) { if (this.success == null) { this.success = new ArrayList(); } this.success.add(elem); } public List getSuccess() { return this.success; } public getLeaderParticipants_result setSuccess(List success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public getLeaderParticipants_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((List)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getLeaderParticipants_result) return this.equals((getLeaderParticipants_result)that); return false; } public boolean equals(getLeaderParticipants_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getLeaderParticipants_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getLeaderParticipants_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getLeaderParticipants_resultStandardSchemeFactory implements SchemeFactory { public getLeaderParticipants_resultStandardScheme getScheme() { return new getLeaderParticipants_resultStandardScheme(); } } private static class getLeaderParticipants_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getLeaderParticipants_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list32 = iprot.readListBegin(); struct.success = new ArrayList(_list32.size); for (int _i33 = 0; _i33 < _list32.size; ++_i33) { Participant _elem34; _elem34 = new Participant(); _elem34.read(iprot); struct.success.add(_elem34); } iprot.readListEnd(); } struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getLeaderParticipants_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.success.size())); for (Participant _iter35 : struct.success) { _iter35.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getLeaderParticipants_resultTupleSchemeFactory implements SchemeFactory { public getLeaderParticipants_resultTupleScheme getScheme() { return new getLeaderParticipants_resultTupleScheme(); } } private static class getLeaderParticipants_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getLeaderParticipants_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { { oprot.writeI32(struct.success.size()); for (Participant _iter36 : struct.success) { _iter36.write(oprot); } } } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getLeaderParticipants_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { { org.apache.thrift.protocol.TList _list37 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.success = new ArrayList(_list37.size); for (int _i38 = 0; _i38 < _list37.size; ++_i38) { Participant _elem39; _elem39 = new Participant(); _elem39.read(iprot); struct.success.add(_elem39); } } struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class getNodeCacheData_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getNodeCacheData_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField CACHE_PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("cacheProjection", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getNodeCacheData_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new getNodeCacheData_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public NodeCacheProjection cacheProjection; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), CACHE_PROJECTION((short)2, "cacheProjection"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // CACHE_PROJECTION return CACHE_PROJECTION; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.CACHE_PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("cacheProjection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, NodeCacheProjection.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getNodeCacheData_args.class, metaDataMap); } public getNodeCacheData_args() { } public getNodeCacheData_args( CuratorProjection projection, NodeCacheProjection cacheProjection) { this(); this.projection = projection; this.cacheProjection = cacheProjection; } /** * Performs a deep copy on other. */ public getNodeCacheData_args(getNodeCacheData_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetCacheProjection()) { this.cacheProjection = new NodeCacheProjection(other.cacheProjection); } } public getNodeCacheData_args deepCopy() { return new getNodeCacheData_args(this); } @Override public void clear() { this.projection = null; this.cacheProjection = null; } public CuratorProjection getProjection() { return this.projection; } public getNodeCacheData_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public NodeCacheProjection getCacheProjection() { return this.cacheProjection; } public getNodeCacheData_args setCacheProjection(NodeCacheProjection cacheProjection) { this.cacheProjection = cacheProjection; return this; } public void unsetCacheProjection() { this.cacheProjection = null; } /** Returns true if field cacheProjection is set (has been assigned a value) and false otherwise */ public boolean isSetCacheProjection() { return this.cacheProjection != null; } public void setCacheProjectionIsSet(boolean value) { if (!value) { this.cacheProjection = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case CACHE_PROJECTION: if (value == null) { unsetCacheProjection(); } else { setCacheProjection((NodeCacheProjection)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case CACHE_PROJECTION: return getCacheProjection(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case CACHE_PROJECTION: return isSetCacheProjection(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getNodeCacheData_args) return this.equals((getNodeCacheData_args)that); return false; } public boolean equals(getNodeCacheData_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_cacheProjection = true && this.isSetCacheProjection(); boolean that_present_cacheProjection = true && that.isSetCacheProjection(); if (this_present_cacheProjection || that_present_cacheProjection) { if (!(this_present_cacheProjection && that_present_cacheProjection)) return false; if (!this.cacheProjection.equals(that.cacheProjection)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getNodeCacheData_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetCacheProjection()).compareTo(other.isSetCacheProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetCacheProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.cacheProjection, other.cacheProjection); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getNodeCacheData_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("cacheProjection:"); if (this.cacheProjection == null) { sb.append("null"); } else { sb.append(this.cacheProjection); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (cacheProjection != null) { cacheProjection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getNodeCacheData_argsStandardSchemeFactory implements SchemeFactory { public getNodeCacheData_argsStandardScheme getScheme() { return new getNodeCacheData_argsStandardScheme(); } } private static class getNodeCacheData_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getNodeCacheData_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // CACHE_PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.cacheProjection = new NodeCacheProjection(); struct.cacheProjection.read(iprot); struct.setCacheProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getNodeCacheData_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.cacheProjection != null) { oprot.writeFieldBegin(CACHE_PROJECTION_FIELD_DESC); struct.cacheProjection.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getNodeCacheData_argsTupleSchemeFactory implements SchemeFactory { public getNodeCacheData_argsTupleScheme getScheme() { return new getNodeCacheData_argsTupleScheme(); } } private static class getNodeCacheData_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getNodeCacheData_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetCacheProjection()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetCacheProjection()) { struct.cacheProjection.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getNodeCacheData_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.cacheProjection = new NodeCacheProjection(); struct.cacheProjection.read(iprot); struct.setCacheProjectionIsSet(true); } } } } public static class getNodeCacheData_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getNodeCacheData_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getNodeCacheData_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new getNodeCacheData_resultTupleSchemeFactory()); } public ChildData success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, ChildData.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getNodeCacheData_result.class, metaDataMap); } public getNodeCacheData_result() { } public getNodeCacheData_result( ChildData success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public getNodeCacheData_result(getNodeCacheData_result other) { if (other.isSetSuccess()) { this.success = new ChildData(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public getNodeCacheData_result deepCopy() { return new getNodeCacheData_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public ChildData getSuccess() { return this.success; } public getNodeCacheData_result setSuccess(ChildData success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public getNodeCacheData_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((ChildData)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getNodeCacheData_result) return this.equals((getNodeCacheData_result)that); return false; } public boolean equals(getNodeCacheData_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getNodeCacheData_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getNodeCacheData_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getNodeCacheData_resultStandardSchemeFactory implements SchemeFactory { public getNodeCacheData_resultStandardScheme getScheme() { return new getNodeCacheData_resultStandardScheme(); } } private static class getNodeCacheData_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getNodeCacheData_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new ChildData(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getNodeCacheData_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getNodeCacheData_resultTupleSchemeFactory implements SchemeFactory { public getNodeCacheData_resultTupleScheme getScheme() { return new getNodeCacheData_resultTupleScheme(); } } private static class getNodeCacheData_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getNodeCacheData_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getNodeCacheData_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new ChildData(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class getPathChildrenCacheData_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getPathChildrenCacheData_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField CACHE_PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("cacheProjection", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getPathChildrenCacheData_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new getPathChildrenCacheData_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public PathChildrenCacheProjection cacheProjection; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), CACHE_PROJECTION((short)2, "cacheProjection"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // CACHE_PROJECTION return CACHE_PROJECTION; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.CACHE_PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("cacheProjection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, PathChildrenCacheProjection.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getPathChildrenCacheData_args.class, metaDataMap); } public getPathChildrenCacheData_args() { } public getPathChildrenCacheData_args( CuratorProjection projection, PathChildrenCacheProjection cacheProjection) { this(); this.projection = projection; this.cacheProjection = cacheProjection; } /** * Performs a deep copy on other. */ public getPathChildrenCacheData_args(getPathChildrenCacheData_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetCacheProjection()) { this.cacheProjection = new PathChildrenCacheProjection(other.cacheProjection); } } public getPathChildrenCacheData_args deepCopy() { return new getPathChildrenCacheData_args(this); } @Override public void clear() { this.projection = null; this.cacheProjection = null; } public CuratorProjection getProjection() { return this.projection; } public getPathChildrenCacheData_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public PathChildrenCacheProjection getCacheProjection() { return this.cacheProjection; } public getPathChildrenCacheData_args setCacheProjection(PathChildrenCacheProjection cacheProjection) { this.cacheProjection = cacheProjection; return this; } public void unsetCacheProjection() { this.cacheProjection = null; } /** Returns true if field cacheProjection is set (has been assigned a value) and false otherwise */ public boolean isSetCacheProjection() { return this.cacheProjection != null; } public void setCacheProjectionIsSet(boolean value) { if (!value) { this.cacheProjection = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case CACHE_PROJECTION: if (value == null) { unsetCacheProjection(); } else { setCacheProjection((PathChildrenCacheProjection)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case CACHE_PROJECTION: return getCacheProjection(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case CACHE_PROJECTION: return isSetCacheProjection(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getPathChildrenCacheData_args) return this.equals((getPathChildrenCacheData_args)that); return false; } public boolean equals(getPathChildrenCacheData_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_cacheProjection = true && this.isSetCacheProjection(); boolean that_present_cacheProjection = true && that.isSetCacheProjection(); if (this_present_cacheProjection || that_present_cacheProjection) { if (!(this_present_cacheProjection && that_present_cacheProjection)) return false; if (!this.cacheProjection.equals(that.cacheProjection)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getPathChildrenCacheData_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetCacheProjection()).compareTo(other.isSetCacheProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetCacheProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.cacheProjection, other.cacheProjection); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getPathChildrenCacheData_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("cacheProjection:"); if (this.cacheProjection == null) { sb.append("null"); } else { sb.append(this.cacheProjection); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (cacheProjection != null) { cacheProjection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getPathChildrenCacheData_argsStandardSchemeFactory implements SchemeFactory { public getPathChildrenCacheData_argsStandardScheme getScheme() { return new getPathChildrenCacheData_argsStandardScheme(); } } private static class getPathChildrenCacheData_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getPathChildrenCacheData_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // CACHE_PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.cacheProjection = new PathChildrenCacheProjection(); struct.cacheProjection.read(iprot); struct.setCacheProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getPathChildrenCacheData_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.cacheProjection != null) { oprot.writeFieldBegin(CACHE_PROJECTION_FIELD_DESC); struct.cacheProjection.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getPathChildrenCacheData_argsTupleSchemeFactory implements SchemeFactory { public getPathChildrenCacheData_argsTupleScheme getScheme() { return new getPathChildrenCacheData_argsTupleScheme(); } } private static class getPathChildrenCacheData_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getPathChildrenCacheData_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetCacheProjection()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetCacheProjection()) { struct.cacheProjection.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getPathChildrenCacheData_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.cacheProjection = new PathChildrenCacheProjection(); struct.cacheProjection.read(iprot); struct.setCacheProjectionIsSet(true); } } } } public static class getPathChildrenCacheData_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getPathChildrenCacheData_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.LIST, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getPathChildrenCacheData_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new getPathChildrenCacheData_resultTupleSchemeFactory()); } public List success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, ChildData.class)))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getPathChildrenCacheData_result.class, metaDataMap); } public getPathChildrenCacheData_result() { } public getPathChildrenCacheData_result( List success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public getPathChildrenCacheData_result(getPathChildrenCacheData_result other) { if (other.isSetSuccess()) { List __this__success = new ArrayList(other.success.size()); for (ChildData other_element : other.success) { __this__success.add(new ChildData(other_element)); } this.success = __this__success; } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public getPathChildrenCacheData_result deepCopy() { return new getPathChildrenCacheData_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public int getSuccessSize() { return (this.success == null) ? 0 : this.success.size(); } public java.util.Iterator getSuccessIterator() { return (this.success == null) ? null : this.success.iterator(); } public void addToSuccess(ChildData elem) { if (this.success == null) { this.success = new ArrayList(); } this.success.add(elem); } public List getSuccess() { return this.success; } public getPathChildrenCacheData_result setSuccess(List success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public getPathChildrenCacheData_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((List)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getPathChildrenCacheData_result) return this.equals((getPathChildrenCacheData_result)that); return false; } public boolean equals(getPathChildrenCacheData_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getPathChildrenCacheData_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getPathChildrenCacheData_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getPathChildrenCacheData_resultStandardSchemeFactory implements SchemeFactory { public getPathChildrenCacheData_resultStandardScheme getScheme() { return new getPathChildrenCacheData_resultStandardScheme(); } } private static class getPathChildrenCacheData_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getPathChildrenCacheData_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list40 = iprot.readListBegin(); struct.success = new ArrayList(_list40.size); for (int _i41 = 0; _i41 < _list40.size; ++_i41) { ChildData _elem42; _elem42 = new ChildData(); _elem42.read(iprot); struct.success.add(_elem42); } iprot.readListEnd(); } struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getPathChildrenCacheData_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.success.size())); for (ChildData _iter43 : struct.success) { _iter43.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getPathChildrenCacheData_resultTupleSchemeFactory implements SchemeFactory { public getPathChildrenCacheData_resultTupleScheme getScheme() { return new getPathChildrenCacheData_resultTupleScheme(); } } private static class getPathChildrenCacheData_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getPathChildrenCacheData_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { { oprot.writeI32(struct.success.size()); for (ChildData _iter44 : struct.success) { _iter44.write(oprot); } } } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getPathChildrenCacheData_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { { org.apache.thrift.protocol.TList _list45 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.success = new ArrayList(_list45.size); for (int _i46 = 0; _i46 < _list45.size; ++_i46) { ChildData _elem47; _elem47 = new ChildData(); _elem47.read(iprot); struct.success.add(_elem47); } } struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class getPathChildrenCacheDataForPath_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getPathChildrenCacheDataForPath_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField CACHE_PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("cacheProjection", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)3); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getPathChildrenCacheDataForPath_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new getPathChildrenCacheDataForPath_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public PathChildrenCacheProjection cacheProjection; // required public String path; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), CACHE_PROJECTION((short)2, "cacheProjection"), PATH((short)3, "path"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // CACHE_PROJECTION return CACHE_PROJECTION; case 3: // PATH return PATH; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.CACHE_PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("cacheProjection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, PathChildrenCacheProjection.class))); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getPathChildrenCacheDataForPath_args.class, metaDataMap); } public getPathChildrenCacheDataForPath_args() { } public getPathChildrenCacheDataForPath_args( CuratorProjection projection, PathChildrenCacheProjection cacheProjection, String path) { this(); this.projection = projection; this.cacheProjection = cacheProjection; this.path = path; } /** * Performs a deep copy on other. */ public getPathChildrenCacheDataForPath_args(getPathChildrenCacheDataForPath_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetCacheProjection()) { this.cacheProjection = new PathChildrenCacheProjection(other.cacheProjection); } if (other.isSetPath()) { this.path = other.path; } } public getPathChildrenCacheDataForPath_args deepCopy() { return new getPathChildrenCacheDataForPath_args(this); } @Override public void clear() { this.projection = null; this.cacheProjection = null; this.path = null; } public CuratorProjection getProjection() { return this.projection; } public getPathChildrenCacheDataForPath_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public PathChildrenCacheProjection getCacheProjection() { return this.cacheProjection; } public getPathChildrenCacheDataForPath_args setCacheProjection(PathChildrenCacheProjection cacheProjection) { this.cacheProjection = cacheProjection; return this; } public void unsetCacheProjection() { this.cacheProjection = null; } /** Returns true if field cacheProjection is set (has been assigned a value) and false otherwise */ public boolean isSetCacheProjection() { return this.cacheProjection != null; } public void setCacheProjectionIsSet(boolean value) { if (!value) { this.cacheProjection = null; } } public String getPath() { return this.path; } public getPathChildrenCacheDataForPath_args setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case CACHE_PROJECTION: if (value == null) { unsetCacheProjection(); } else { setCacheProjection((PathChildrenCacheProjection)value); } break; case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case CACHE_PROJECTION: return getCacheProjection(); case PATH: return getPath(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case CACHE_PROJECTION: return isSetCacheProjection(); case PATH: return isSetPath(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getPathChildrenCacheDataForPath_args) return this.equals((getPathChildrenCacheDataForPath_args)that); return false; } public boolean equals(getPathChildrenCacheDataForPath_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_cacheProjection = true && this.isSetCacheProjection(); boolean that_present_cacheProjection = true && that.isSetCacheProjection(); if (this_present_cacheProjection || that_present_cacheProjection) { if (!(this_present_cacheProjection && that_present_cacheProjection)) return false; if (!this.cacheProjection.equals(that.cacheProjection)) return false; } boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getPathChildrenCacheDataForPath_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetCacheProjection()).compareTo(other.isSetCacheProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetCacheProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.cacheProjection, other.cacheProjection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getPathChildrenCacheDataForPath_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("cacheProjection:"); if (this.cacheProjection == null) { sb.append("null"); } else { sb.append(this.cacheProjection); } first = false; if (!first) sb.append(", "); sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (cacheProjection != null) { cacheProjection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getPathChildrenCacheDataForPath_argsStandardSchemeFactory implements SchemeFactory { public getPathChildrenCacheDataForPath_argsStandardScheme getScheme() { return new getPathChildrenCacheDataForPath_argsStandardScheme(); } } private static class getPathChildrenCacheDataForPath_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getPathChildrenCacheDataForPath_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // CACHE_PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.cacheProjection = new PathChildrenCacheProjection(); struct.cacheProjection.read(iprot); struct.setCacheProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getPathChildrenCacheDataForPath_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.cacheProjection != null) { oprot.writeFieldBegin(CACHE_PROJECTION_FIELD_DESC); struct.cacheProjection.write(oprot); oprot.writeFieldEnd(); } if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getPathChildrenCacheDataForPath_argsTupleSchemeFactory implements SchemeFactory { public getPathChildrenCacheDataForPath_argsTupleScheme getScheme() { return new getPathChildrenCacheDataForPath_argsTupleScheme(); } } private static class getPathChildrenCacheDataForPath_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getPathChildrenCacheDataForPath_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetCacheProjection()) { optionals.set(1); } if (struct.isSetPath()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetCacheProjection()) { struct.cacheProjection.write(oprot); } if (struct.isSetPath()) { oprot.writeString(struct.path); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getPathChildrenCacheDataForPath_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.cacheProjection = new PathChildrenCacheProjection(); struct.cacheProjection.read(iprot); struct.setCacheProjectionIsSet(true); } if (incoming.get(2)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } } } } public static class getPathChildrenCacheDataForPath_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getPathChildrenCacheDataForPath_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getPathChildrenCacheDataForPath_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new getPathChildrenCacheDataForPath_resultTupleSchemeFactory()); } public ChildData success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, ChildData.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getPathChildrenCacheDataForPath_result.class, metaDataMap); } public getPathChildrenCacheDataForPath_result() { } public getPathChildrenCacheDataForPath_result( ChildData success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public getPathChildrenCacheDataForPath_result(getPathChildrenCacheDataForPath_result other) { if (other.isSetSuccess()) { this.success = new ChildData(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public getPathChildrenCacheDataForPath_result deepCopy() { return new getPathChildrenCacheDataForPath_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public ChildData getSuccess() { return this.success; } public getPathChildrenCacheDataForPath_result setSuccess(ChildData success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public getPathChildrenCacheDataForPath_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((ChildData)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getPathChildrenCacheDataForPath_result) return this.equals((getPathChildrenCacheDataForPath_result)that); return false; } public boolean equals(getPathChildrenCacheDataForPath_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getPathChildrenCacheDataForPath_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getPathChildrenCacheDataForPath_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getPathChildrenCacheDataForPath_resultStandardSchemeFactory implements SchemeFactory { public getPathChildrenCacheDataForPath_resultStandardScheme getScheme() { return new getPathChildrenCacheDataForPath_resultStandardScheme(); } } private static class getPathChildrenCacheDataForPath_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getPathChildrenCacheDataForPath_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new ChildData(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getPathChildrenCacheDataForPath_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getPathChildrenCacheDataForPath_resultTupleSchemeFactory implements SchemeFactory { public getPathChildrenCacheDataForPath_resultTupleScheme getScheme() { return new getPathChildrenCacheDataForPath_resultTupleScheme(); } } private static class getPathChildrenCacheDataForPath_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getPathChildrenCacheDataForPath_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getPathChildrenCacheDataForPath_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new ChildData(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class isLeader_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("isLeader_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField LEADER_PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("leaderProjection", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new isLeader_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new isLeader_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public LeaderProjection leaderProjection; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), LEADER_PROJECTION((short)2, "leaderProjection"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // LEADER_PROJECTION return LEADER_PROJECTION; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.LEADER_PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("leaderProjection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, LeaderProjection.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(isLeader_args.class, metaDataMap); } public isLeader_args() { } public isLeader_args( CuratorProjection projection, LeaderProjection leaderProjection) { this(); this.projection = projection; this.leaderProjection = leaderProjection; } /** * Performs a deep copy on other. */ public isLeader_args(isLeader_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetLeaderProjection()) { this.leaderProjection = new LeaderProjection(other.leaderProjection); } } public isLeader_args deepCopy() { return new isLeader_args(this); } @Override public void clear() { this.projection = null; this.leaderProjection = null; } public CuratorProjection getProjection() { return this.projection; } public isLeader_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public LeaderProjection getLeaderProjection() { return this.leaderProjection; } public isLeader_args setLeaderProjection(LeaderProjection leaderProjection) { this.leaderProjection = leaderProjection; return this; } public void unsetLeaderProjection() { this.leaderProjection = null; } /** Returns true if field leaderProjection is set (has been assigned a value) and false otherwise */ public boolean isSetLeaderProjection() { return this.leaderProjection != null; } public void setLeaderProjectionIsSet(boolean value) { if (!value) { this.leaderProjection = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case LEADER_PROJECTION: if (value == null) { unsetLeaderProjection(); } else { setLeaderProjection((LeaderProjection)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case LEADER_PROJECTION: return getLeaderProjection(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case LEADER_PROJECTION: return isSetLeaderProjection(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof isLeader_args) return this.equals((isLeader_args)that); return false; } public boolean equals(isLeader_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_leaderProjection = true && this.isSetLeaderProjection(); boolean that_present_leaderProjection = true && that.isSetLeaderProjection(); if (this_present_leaderProjection || that_present_leaderProjection) { if (!(this_present_leaderProjection && that_present_leaderProjection)) return false; if (!this.leaderProjection.equals(that.leaderProjection)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(isLeader_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetLeaderProjection()).compareTo(other.isSetLeaderProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetLeaderProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.leaderProjection, other.leaderProjection); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("isLeader_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("leaderProjection:"); if (this.leaderProjection == null) { sb.append("null"); } else { sb.append(this.leaderProjection); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (leaderProjection != null) { leaderProjection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class isLeader_argsStandardSchemeFactory implements SchemeFactory { public isLeader_argsStandardScheme getScheme() { return new isLeader_argsStandardScheme(); } } private static class isLeader_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, isLeader_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // LEADER_PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.leaderProjection = new LeaderProjection(); struct.leaderProjection.read(iprot); struct.setLeaderProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, isLeader_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.leaderProjection != null) { oprot.writeFieldBegin(LEADER_PROJECTION_FIELD_DESC); struct.leaderProjection.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class isLeader_argsTupleSchemeFactory implements SchemeFactory { public isLeader_argsTupleScheme getScheme() { return new isLeader_argsTupleScheme(); } } private static class isLeader_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, isLeader_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetLeaderProjection()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetLeaderProjection()) { struct.leaderProjection.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, isLeader_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.leaderProjection = new LeaderProjection(); struct.leaderProjection.read(iprot); struct.setLeaderProjectionIsSet(true); } } } } public static class isLeader_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("isLeader_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BOOL, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new isLeader_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new isLeader_resultTupleSchemeFactory()); } public boolean success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __SUCCESS_ISSET_ID = 0; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(isLeader_result.class, metaDataMap); } public isLeader_result() { } public isLeader_result( boolean success, CuratorException ex1) { this(); this.success = success; setSuccessIsSet(true); this.ex1 = ex1; } /** * Performs a deep copy on other. */ public isLeader_result(isLeader_result other) { __isset_bitfield = other.__isset_bitfield; this.success = other.success; if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public isLeader_result deepCopy() { return new isLeader_result(this); } @Override public void clear() { setSuccessIsSet(false); this.success = false; this.ex1 = null; } public boolean isSuccess() { return this.success; } public isLeader_result setSuccess(boolean success) { this.success = success; setSuccessIsSet(true); return this; } public void unsetSuccess() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID); } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID); } public void setSuccessIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value); } public CuratorException getEx1() { return this.ex1; } public isLeader_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((Boolean)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return Boolean.valueOf(isSuccess()); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof isLeader_result) return this.equals((isLeader_result)that); return false; } public boolean equals(isLeader_result that) { if (that == null) return false; boolean this_present_success = true; boolean that_present_success = true; if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (this.success != that.success) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(isLeader_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("isLeader_result("); boolean first = true; sb.append("success:"); sb.append(this.success); first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class isLeader_resultStandardSchemeFactory implements SchemeFactory { public isLeader_resultStandardScheme getScheme() { return new isLeader_resultStandardScheme(); } } private static class isLeader_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, isLeader_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.success = iprot.readBool(); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, isLeader_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.isSetSuccess()) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); oprot.writeBool(struct.success); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class isLeader_resultTupleSchemeFactory implements SchemeFactory { public isLeader_resultTupleScheme getScheme() { return new isLeader_resultTupleScheme(); } } private static class isLeader_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, isLeader_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { oprot.writeBool(struct.success); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, isLeader_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = iprot.readBool(); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class newCuratorProjection_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("newCuratorProjection_args"); private static final org.apache.thrift.protocol.TField CONNECTION_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("connectionName", org.apache.thrift.protocol.TType.STRING, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new newCuratorProjection_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new newCuratorProjection_argsTupleSchemeFactory()); } public String connectionName; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { CONNECTION_NAME((short)1, "connectionName"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // CONNECTION_NAME return CONNECTION_NAME; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.CONNECTION_NAME, new org.apache.thrift.meta_data.FieldMetaData("connectionName", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(newCuratorProjection_args.class, metaDataMap); } public newCuratorProjection_args() { } public newCuratorProjection_args( String connectionName) { this(); this.connectionName = connectionName; } /** * Performs a deep copy on other. */ public newCuratorProjection_args(newCuratorProjection_args other) { if (other.isSetConnectionName()) { this.connectionName = other.connectionName; } } public newCuratorProjection_args deepCopy() { return new newCuratorProjection_args(this); } @Override public void clear() { this.connectionName = null; } public String getConnectionName() { return this.connectionName; } public newCuratorProjection_args setConnectionName(String connectionName) { this.connectionName = connectionName; return this; } public void unsetConnectionName() { this.connectionName = null; } /** Returns true if field connectionName is set (has been assigned a value) and false otherwise */ public boolean isSetConnectionName() { return this.connectionName != null; } public void setConnectionNameIsSet(boolean value) { if (!value) { this.connectionName = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case CONNECTION_NAME: if (value == null) { unsetConnectionName(); } else { setConnectionName((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case CONNECTION_NAME: return getConnectionName(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case CONNECTION_NAME: return isSetConnectionName(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof newCuratorProjection_args) return this.equals((newCuratorProjection_args)that); return false; } public boolean equals(newCuratorProjection_args that) { if (that == null) return false; boolean this_present_connectionName = true && this.isSetConnectionName(); boolean that_present_connectionName = true && that.isSetConnectionName(); if (this_present_connectionName || that_present_connectionName) { if (!(this_present_connectionName && that_present_connectionName)) return false; if (!this.connectionName.equals(that.connectionName)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(newCuratorProjection_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetConnectionName()).compareTo(other.isSetConnectionName()); if (lastComparison != 0) { return lastComparison; } if (isSetConnectionName()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.connectionName, other.connectionName); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("newCuratorProjection_args("); boolean first = true; sb.append("connectionName:"); if (this.connectionName == null) { sb.append("null"); } else { sb.append(this.connectionName); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class newCuratorProjection_argsStandardSchemeFactory implements SchemeFactory { public newCuratorProjection_argsStandardScheme getScheme() { return new newCuratorProjection_argsStandardScheme(); } } private static class newCuratorProjection_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, newCuratorProjection_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // CONNECTION_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.connectionName = iprot.readString(); struct.setConnectionNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, newCuratorProjection_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.connectionName != null) { oprot.writeFieldBegin(CONNECTION_NAME_FIELD_DESC); oprot.writeString(struct.connectionName); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class newCuratorProjection_argsTupleSchemeFactory implements SchemeFactory { public newCuratorProjection_argsTupleScheme getScheme() { return new newCuratorProjection_argsTupleScheme(); } } private static class newCuratorProjection_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, newCuratorProjection_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetConnectionName()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetConnectionName()) { oprot.writeString(struct.connectionName); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, newCuratorProjection_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.connectionName = iprot.readString(); struct.setConnectionNameIsSet(true); } } } } public static class newCuratorProjection_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("newCuratorProjection_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new newCuratorProjection_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new newCuratorProjection_resultTupleSchemeFactory()); } public CuratorProjection success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(newCuratorProjection_result.class, metaDataMap); } public newCuratorProjection_result() { } public newCuratorProjection_result( CuratorProjection success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public newCuratorProjection_result(newCuratorProjection_result other) { if (other.isSetSuccess()) { this.success = new CuratorProjection(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public newCuratorProjection_result deepCopy() { return new newCuratorProjection_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public CuratorProjection getSuccess() { return this.success; } public newCuratorProjection_result setSuccess(CuratorProjection success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public newCuratorProjection_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((CuratorProjection)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof newCuratorProjection_result) return this.equals((newCuratorProjection_result)that); return false; } public boolean equals(newCuratorProjection_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(newCuratorProjection_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("newCuratorProjection_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class newCuratorProjection_resultStandardSchemeFactory implements SchemeFactory { public newCuratorProjection_resultStandardScheme getScheme() { return new newCuratorProjection_resultStandardScheme(); } } private static class newCuratorProjection_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, newCuratorProjection_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new CuratorProjection(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, newCuratorProjection_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class newCuratorProjection_resultTupleSchemeFactory implements SchemeFactory { public newCuratorProjection_resultTupleScheme getScheme() { return new newCuratorProjection_resultTupleScheme(); } } private static class newCuratorProjection_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, newCuratorProjection_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, newCuratorProjection_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new CuratorProjection(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class pingCuratorProjection_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("pingCuratorProjection_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new pingCuratorProjection_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new pingCuratorProjection_argsTupleSchemeFactory()); } public CuratorProjection projection; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(pingCuratorProjection_args.class, metaDataMap); } public pingCuratorProjection_args() { } public pingCuratorProjection_args( CuratorProjection projection) { this(); this.projection = projection; } /** * Performs a deep copy on other. */ public pingCuratorProjection_args(pingCuratorProjection_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } } public pingCuratorProjection_args deepCopy() { return new pingCuratorProjection_args(this); } @Override public void clear() { this.projection = null; } public CuratorProjection getProjection() { return this.projection; } public pingCuratorProjection_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof pingCuratorProjection_args) return this.equals((pingCuratorProjection_args)that); return false; } public boolean equals(pingCuratorProjection_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(pingCuratorProjection_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("pingCuratorProjection_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class pingCuratorProjection_argsStandardSchemeFactory implements SchemeFactory { public pingCuratorProjection_argsStandardScheme getScheme() { return new pingCuratorProjection_argsStandardScheme(); } } private static class pingCuratorProjection_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, pingCuratorProjection_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, pingCuratorProjection_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class pingCuratorProjection_argsTupleSchemeFactory implements SchemeFactory { public pingCuratorProjection_argsTupleScheme getScheme() { return new pingCuratorProjection_argsTupleScheme(); } } private static class pingCuratorProjection_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, pingCuratorProjection_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetProjection()) { struct.projection.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, pingCuratorProjection_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } } } } public static class setData_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("setData_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField SPEC_FIELD_DESC = new org.apache.thrift.protocol.TField("spec", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new setData_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new setData_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public SetDataSpec spec; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), SPEC((short)2, "spec"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // SPEC return SPEC; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.SPEC, new org.apache.thrift.meta_data.FieldMetaData("spec", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, SetDataSpec.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(setData_args.class, metaDataMap); } public setData_args() { } public setData_args( CuratorProjection projection, SetDataSpec spec) { this(); this.projection = projection; this.spec = spec; } /** * Performs a deep copy on other. */ public setData_args(setData_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetSpec()) { this.spec = new SetDataSpec(other.spec); } } public setData_args deepCopy() { return new setData_args(this); } @Override public void clear() { this.projection = null; this.spec = null; } public CuratorProjection getProjection() { return this.projection; } public setData_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public SetDataSpec getSpec() { return this.spec; } public setData_args setSpec(SetDataSpec spec) { this.spec = spec; return this; } public void unsetSpec() { this.spec = null; } /** Returns true if field spec is set (has been assigned a value) and false otherwise */ public boolean isSetSpec() { return this.spec != null; } public void setSpecIsSet(boolean value) { if (!value) { this.spec = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case SPEC: if (value == null) { unsetSpec(); } else { setSpec((SetDataSpec)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case SPEC: return getSpec(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case SPEC: return isSetSpec(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof setData_args) return this.equals((setData_args)that); return false; } public boolean equals(setData_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_spec = true && this.isSetSpec(); boolean that_present_spec = true && that.isSetSpec(); if (this_present_spec || that_present_spec) { if (!(this_present_spec && that_present_spec)) return false; if (!this.spec.equals(that.spec)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(setData_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetSpec()).compareTo(other.isSetSpec()); if (lastComparison != 0) { return lastComparison; } if (isSetSpec()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.spec, other.spec); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("setData_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("spec:"); if (this.spec == null) { sb.append("null"); } else { sb.append(this.spec); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (spec != null) { spec.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class setData_argsStandardSchemeFactory implements SchemeFactory { public setData_argsStandardScheme getScheme() { return new setData_argsStandardScheme(); } } private static class setData_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, setData_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // SPEC if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.spec = new SetDataSpec(); struct.spec.read(iprot); struct.setSpecIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, setData_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.spec != null) { oprot.writeFieldBegin(SPEC_FIELD_DESC); struct.spec.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class setData_argsTupleSchemeFactory implements SchemeFactory { public setData_argsTupleScheme getScheme() { return new setData_argsTupleScheme(); } } private static class setData_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, setData_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetSpec()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetSpec()) { struct.spec.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, setData_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.spec = new SetDataSpec(); struct.spec.read(iprot); struct.setSpecIsSet(true); } } } } public static class setData_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("setData_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new setData_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new setData_resultTupleSchemeFactory()); } public OptionalStat success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, OptionalStat.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(setData_result.class, metaDataMap); } public setData_result() { } public setData_result( OptionalStat success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public setData_result(setData_result other) { if (other.isSetSuccess()) { this.success = new OptionalStat(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public setData_result deepCopy() { return new setData_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public OptionalStat getSuccess() { return this.success; } public setData_result setSuccess(OptionalStat success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public setData_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((OptionalStat)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof setData_result) return this.equals((setData_result)that); return false; } public boolean equals(setData_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(setData_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("setData_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class setData_resultStandardSchemeFactory implements SchemeFactory { public setData_resultStandardScheme getScheme() { return new setData_resultStandardScheme(); } } private static class setData_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, setData_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new OptionalStat(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, setData_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class setData_resultTupleSchemeFactory implements SchemeFactory { public setData_resultTupleScheme getScheme() { return new setData_resultTupleScheme(); } } private static class setData_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, setData_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, setData_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new OptionalStat(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class startLeaderSelector_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("startLeaderSelector_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField PARTICIPANT_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("participantId", org.apache.thrift.protocol.TType.STRING, (short)3); private static final org.apache.thrift.protocol.TField WAIT_FOR_LEADERSHIP_MS_FIELD_DESC = new org.apache.thrift.protocol.TField("waitForLeadershipMs", org.apache.thrift.protocol.TType.I32, (short)4); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new startLeaderSelector_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new startLeaderSelector_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public String path; // required public String participantId; // required public int waitForLeadershipMs; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), PATH((short)2, "path"), PARTICIPANT_ID((short)3, "participantId"), WAIT_FOR_LEADERSHIP_MS((short)4, "waitForLeadershipMs"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // PATH return PATH; case 3: // PARTICIPANT_ID return PARTICIPANT_ID; case 4: // WAIT_FOR_LEADERSHIP_MS return WAIT_FOR_LEADERSHIP_MS; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __WAITFORLEADERSHIPMS_ISSET_ID = 0; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.PARTICIPANT_ID, new org.apache.thrift.meta_data.FieldMetaData("participantId", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.WAIT_FOR_LEADERSHIP_MS, new org.apache.thrift.meta_data.FieldMetaData("waitForLeadershipMs", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(startLeaderSelector_args.class, metaDataMap); } public startLeaderSelector_args() { } public startLeaderSelector_args( CuratorProjection projection, String path, String participantId, int waitForLeadershipMs) { this(); this.projection = projection; this.path = path; this.participantId = participantId; this.waitForLeadershipMs = waitForLeadershipMs; setWaitForLeadershipMsIsSet(true); } /** * Performs a deep copy on other. */ public startLeaderSelector_args(startLeaderSelector_args other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetPath()) { this.path = other.path; } if (other.isSetParticipantId()) { this.participantId = other.participantId; } this.waitForLeadershipMs = other.waitForLeadershipMs; } public startLeaderSelector_args deepCopy() { return new startLeaderSelector_args(this); } @Override public void clear() { this.projection = null; this.path = null; this.participantId = null; setWaitForLeadershipMsIsSet(false); this.waitForLeadershipMs = 0; } public CuratorProjection getProjection() { return this.projection; } public startLeaderSelector_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public String getPath() { return this.path; } public startLeaderSelector_args setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public String getParticipantId() { return this.participantId; } public startLeaderSelector_args setParticipantId(String participantId) { this.participantId = participantId; return this; } public void unsetParticipantId() { this.participantId = null; } /** Returns true if field participantId is set (has been assigned a value) and false otherwise */ public boolean isSetParticipantId() { return this.participantId != null; } public void setParticipantIdIsSet(boolean value) { if (!value) { this.participantId = null; } } public int getWaitForLeadershipMs() { return this.waitForLeadershipMs; } public startLeaderSelector_args setWaitForLeadershipMs(int waitForLeadershipMs) { this.waitForLeadershipMs = waitForLeadershipMs; setWaitForLeadershipMsIsSet(true); return this; } public void unsetWaitForLeadershipMs() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __WAITFORLEADERSHIPMS_ISSET_ID); } /** Returns true if field waitForLeadershipMs is set (has been assigned a value) and false otherwise */ public boolean isSetWaitForLeadershipMs() { return EncodingUtils.testBit(__isset_bitfield, __WAITFORLEADERSHIPMS_ISSET_ID); } public void setWaitForLeadershipMsIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __WAITFORLEADERSHIPMS_ISSET_ID, value); } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; case PARTICIPANT_ID: if (value == null) { unsetParticipantId(); } else { setParticipantId((String)value); } break; case WAIT_FOR_LEADERSHIP_MS: if (value == null) { unsetWaitForLeadershipMs(); } else { setWaitForLeadershipMs((Integer)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case PATH: return getPath(); case PARTICIPANT_ID: return getParticipantId(); case WAIT_FOR_LEADERSHIP_MS: return Integer.valueOf(getWaitForLeadershipMs()); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case PATH: return isSetPath(); case PARTICIPANT_ID: return isSetParticipantId(); case WAIT_FOR_LEADERSHIP_MS: return isSetWaitForLeadershipMs(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof startLeaderSelector_args) return this.equals((startLeaderSelector_args)that); return false; } public boolean equals(startLeaderSelector_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } boolean this_present_participantId = true && this.isSetParticipantId(); boolean that_present_participantId = true && that.isSetParticipantId(); if (this_present_participantId || that_present_participantId) { if (!(this_present_participantId && that_present_participantId)) return false; if (!this.participantId.equals(that.participantId)) return false; } boolean this_present_waitForLeadershipMs = true; boolean that_present_waitForLeadershipMs = true; if (this_present_waitForLeadershipMs || that_present_waitForLeadershipMs) { if (!(this_present_waitForLeadershipMs && that_present_waitForLeadershipMs)) return false; if (this.waitForLeadershipMs != that.waitForLeadershipMs) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(startLeaderSelector_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetParticipantId()).compareTo(other.isSetParticipantId()); if (lastComparison != 0) { return lastComparison; } if (isSetParticipantId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.participantId, other.participantId); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetWaitForLeadershipMs()).compareTo(other.isSetWaitForLeadershipMs()); if (lastComparison != 0) { return lastComparison; } if (isSetWaitForLeadershipMs()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.waitForLeadershipMs, other.waitForLeadershipMs); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("startLeaderSelector_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; if (!first) sb.append(", "); sb.append("participantId:"); if (this.participantId == null) { sb.append("null"); } else { sb.append(this.participantId); } first = false; if (!first) sb.append(", "); sb.append("waitForLeadershipMs:"); sb.append(this.waitForLeadershipMs); first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class startLeaderSelector_argsStandardSchemeFactory implements SchemeFactory { public startLeaderSelector_argsStandardScheme getScheme() { return new startLeaderSelector_argsStandardScheme(); } } private static class startLeaderSelector_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, startLeaderSelector_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // PARTICIPANT_ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.participantId = iprot.readString(); struct.setParticipantIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // WAIT_FOR_LEADERSHIP_MS if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.waitForLeadershipMs = iprot.readI32(); struct.setWaitForLeadershipMsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, startLeaderSelector_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } if (struct.participantId != null) { oprot.writeFieldBegin(PARTICIPANT_ID_FIELD_DESC); oprot.writeString(struct.participantId); oprot.writeFieldEnd(); } oprot.writeFieldBegin(WAIT_FOR_LEADERSHIP_MS_FIELD_DESC); oprot.writeI32(struct.waitForLeadershipMs); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class startLeaderSelector_argsTupleSchemeFactory implements SchemeFactory { public startLeaderSelector_argsTupleScheme getScheme() { return new startLeaderSelector_argsTupleScheme(); } } private static class startLeaderSelector_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, startLeaderSelector_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetPath()) { optionals.set(1); } if (struct.isSetParticipantId()) { optionals.set(2); } if (struct.isSetWaitForLeadershipMs()) { optionals.set(3); } oprot.writeBitSet(optionals, 4); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetPath()) { oprot.writeString(struct.path); } if (struct.isSetParticipantId()) { oprot.writeString(struct.participantId); } if (struct.isSetWaitForLeadershipMs()) { oprot.writeI32(struct.waitForLeadershipMs); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, startLeaderSelector_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(4); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } if (incoming.get(2)) { struct.participantId = iprot.readString(); struct.setParticipantIdIsSet(true); } if (incoming.get(3)) { struct.waitForLeadershipMs = iprot.readI32(); struct.setWaitForLeadershipMsIsSet(true); } } } } public static class startLeaderSelector_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("startLeaderSelector_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new startLeaderSelector_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new startLeaderSelector_resultTupleSchemeFactory()); } public LeaderResult success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, LeaderResult.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(startLeaderSelector_result.class, metaDataMap); } public startLeaderSelector_result() { } public startLeaderSelector_result( LeaderResult success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public startLeaderSelector_result(startLeaderSelector_result other) { if (other.isSetSuccess()) { this.success = new LeaderResult(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public startLeaderSelector_result deepCopy() { return new startLeaderSelector_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public LeaderResult getSuccess() { return this.success; } public startLeaderSelector_result setSuccess(LeaderResult success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public startLeaderSelector_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((LeaderResult)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof startLeaderSelector_result) return this.equals((startLeaderSelector_result)that); return false; } public boolean equals(startLeaderSelector_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(startLeaderSelector_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("startLeaderSelector_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class startLeaderSelector_resultStandardSchemeFactory implements SchemeFactory { public startLeaderSelector_resultStandardScheme getScheme() { return new startLeaderSelector_resultStandardScheme(); } } private static class startLeaderSelector_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, startLeaderSelector_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new LeaderResult(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, startLeaderSelector_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class startLeaderSelector_resultTupleSchemeFactory implements SchemeFactory { public startLeaderSelector_resultTupleScheme getScheme() { return new startLeaderSelector_resultTupleScheme(); } } private static class startLeaderSelector_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, startLeaderSelector_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, startLeaderSelector_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new LeaderResult(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class startNodeCache_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("startNodeCache_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField DATA_IS_COMPRESSED_FIELD_DESC = new org.apache.thrift.protocol.TField("dataIsCompressed", org.apache.thrift.protocol.TType.BOOL, (short)3); private static final org.apache.thrift.protocol.TField BUILD_INITIAL_FIELD_DESC = new org.apache.thrift.protocol.TField("buildInitial", org.apache.thrift.protocol.TType.BOOL, (short)4); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new startNodeCache_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new startNodeCache_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public String path; // required public boolean dataIsCompressed; // required public boolean buildInitial; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), PATH((short)2, "path"), DATA_IS_COMPRESSED((short)3, "dataIsCompressed"), BUILD_INITIAL((short)4, "buildInitial"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // PATH return PATH; case 3: // DATA_IS_COMPRESSED return DATA_IS_COMPRESSED; case 4: // BUILD_INITIAL return BUILD_INITIAL; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __DATAISCOMPRESSED_ISSET_ID = 0; private static final int __BUILDINITIAL_ISSET_ID = 1; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.DATA_IS_COMPRESSED, new org.apache.thrift.meta_data.FieldMetaData("dataIsCompressed", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.BUILD_INITIAL, new org.apache.thrift.meta_data.FieldMetaData("buildInitial", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(startNodeCache_args.class, metaDataMap); } public startNodeCache_args() { } public startNodeCache_args( CuratorProjection projection, String path, boolean dataIsCompressed, boolean buildInitial) { this(); this.projection = projection; this.path = path; this.dataIsCompressed = dataIsCompressed; setDataIsCompressedIsSet(true); this.buildInitial = buildInitial; setBuildInitialIsSet(true); } /** * Performs a deep copy on other. */ public startNodeCache_args(startNodeCache_args other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetPath()) { this.path = other.path; } this.dataIsCompressed = other.dataIsCompressed; this.buildInitial = other.buildInitial; } public startNodeCache_args deepCopy() { return new startNodeCache_args(this); } @Override public void clear() { this.projection = null; this.path = null; setDataIsCompressedIsSet(false); this.dataIsCompressed = false; setBuildInitialIsSet(false); this.buildInitial = false; } public CuratorProjection getProjection() { return this.projection; } public startNodeCache_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public String getPath() { return this.path; } public startNodeCache_args setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public boolean isDataIsCompressed() { return this.dataIsCompressed; } public startNodeCache_args setDataIsCompressed(boolean dataIsCompressed) { this.dataIsCompressed = dataIsCompressed; setDataIsCompressedIsSet(true); return this; } public void unsetDataIsCompressed() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __DATAISCOMPRESSED_ISSET_ID); } /** Returns true if field dataIsCompressed is set (has been assigned a value) and false otherwise */ public boolean isSetDataIsCompressed() { return EncodingUtils.testBit(__isset_bitfield, __DATAISCOMPRESSED_ISSET_ID); } public void setDataIsCompressedIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __DATAISCOMPRESSED_ISSET_ID, value); } public boolean isBuildInitial() { return this.buildInitial; } public startNodeCache_args setBuildInitial(boolean buildInitial) { this.buildInitial = buildInitial; setBuildInitialIsSet(true); return this; } public void unsetBuildInitial() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __BUILDINITIAL_ISSET_ID); } /** Returns true if field buildInitial is set (has been assigned a value) and false otherwise */ public boolean isSetBuildInitial() { return EncodingUtils.testBit(__isset_bitfield, __BUILDINITIAL_ISSET_ID); } public void setBuildInitialIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __BUILDINITIAL_ISSET_ID, value); } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; case DATA_IS_COMPRESSED: if (value == null) { unsetDataIsCompressed(); } else { setDataIsCompressed((Boolean)value); } break; case BUILD_INITIAL: if (value == null) { unsetBuildInitial(); } else { setBuildInitial((Boolean)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case PATH: return getPath(); case DATA_IS_COMPRESSED: return Boolean.valueOf(isDataIsCompressed()); case BUILD_INITIAL: return Boolean.valueOf(isBuildInitial()); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case PATH: return isSetPath(); case DATA_IS_COMPRESSED: return isSetDataIsCompressed(); case BUILD_INITIAL: return isSetBuildInitial(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof startNodeCache_args) return this.equals((startNodeCache_args)that); return false; } public boolean equals(startNodeCache_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } boolean this_present_dataIsCompressed = true; boolean that_present_dataIsCompressed = true; if (this_present_dataIsCompressed || that_present_dataIsCompressed) { if (!(this_present_dataIsCompressed && that_present_dataIsCompressed)) return false; if (this.dataIsCompressed != that.dataIsCompressed) return false; } boolean this_present_buildInitial = true; boolean that_present_buildInitial = true; if (this_present_buildInitial || that_present_buildInitial) { if (!(this_present_buildInitial && that_present_buildInitial)) return false; if (this.buildInitial != that.buildInitial) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(startNodeCache_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetDataIsCompressed()).compareTo(other.isSetDataIsCompressed()); if (lastComparison != 0) { return lastComparison; } if (isSetDataIsCompressed()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.dataIsCompressed, other.dataIsCompressed); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetBuildInitial()).compareTo(other.isSetBuildInitial()); if (lastComparison != 0) { return lastComparison; } if (isSetBuildInitial()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.buildInitial, other.buildInitial); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("startNodeCache_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; if (!first) sb.append(", "); sb.append("dataIsCompressed:"); sb.append(this.dataIsCompressed); first = false; if (!first) sb.append(", "); sb.append("buildInitial:"); sb.append(this.buildInitial); first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class startNodeCache_argsStandardSchemeFactory implements SchemeFactory { public startNodeCache_argsStandardScheme getScheme() { return new startNodeCache_argsStandardScheme(); } } private static class startNodeCache_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, startNodeCache_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // DATA_IS_COMPRESSED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.dataIsCompressed = iprot.readBool(); struct.setDataIsCompressedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // BUILD_INITIAL if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.buildInitial = iprot.readBool(); struct.setBuildInitialIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, startNodeCache_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } oprot.writeFieldBegin(DATA_IS_COMPRESSED_FIELD_DESC); oprot.writeBool(struct.dataIsCompressed); oprot.writeFieldEnd(); oprot.writeFieldBegin(BUILD_INITIAL_FIELD_DESC); oprot.writeBool(struct.buildInitial); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class startNodeCache_argsTupleSchemeFactory implements SchemeFactory { public startNodeCache_argsTupleScheme getScheme() { return new startNodeCache_argsTupleScheme(); } } private static class startNodeCache_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, startNodeCache_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetPath()) { optionals.set(1); } if (struct.isSetDataIsCompressed()) { optionals.set(2); } if (struct.isSetBuildInitial()) { optionals.set(3); } oprot.writeBitSet(optionals, 4); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetPath()) { oprot.writeString(struct.path); } if (struct.isSetDataIsCompressed()) { oprot.writeBool(struct.dataIsCompressed); } if (struct.isSetBuildInitial()) { oprot.writeBool(struct.buildInitial); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, startNodeCache_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(4); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } if (incoming.get(2)) { struct.dataIsCompressed = iprot.readBool(); struct.setDataIsCompressedIsSet(true); } if (incoming.get(3)) { struct.buildInitial = iprot.readBool(); struct.setBuildInitialIsSet(true); } } } } public static class startNodeCache_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("startNodeCache_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new startNodeCache_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new startNodeCache_resultTupleSchemeFactory()); } public NodeCacheProjection success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, NodeCacheProjection.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(startNodeCache_result.class, metaDataMap); } public startNodeCache_result() { } public startNodeCache_result( NodeCacheProjection success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public startNodeCache_result(startNodeCache_result other) { if (other.isSetSuccess()) { this.success = new NodeCacheProjection(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public startNodeCache_result deepCopy() { return new startNodeCache_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public NodeCacheProjection getSuccess() { return this.success; } public startNodeCache_result setSuccess(NodeCacheProjection success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public startNodeCache_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((NodeCacheProjection)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof startNodeCache_result) return this.equals((startNodeCache_result)that); return false; } public boolean equals(startNodeCache_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(startNodeCache_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("startNodeCache_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class startNodeCache_resultStandardSchemeFactory implements SchemeFactory { public startNodeCache_resultStandardScheme getScheme() { return new startNodeCache_resultStandardScheme(); } } private static class startNodeCache_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, startNodeCache_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new NodeCacheProjection(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, startNodeCache_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class startNodeCache_resultTupleSchemeFactory implements SchemeFactory { public startNodeCache_resultTupleScheme getScheme() { return new startNodeCache_resultTupleScheme(); } } private static class startNodeCache_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, startNodeCache_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, startNodeCache_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new NodeCacheProjection(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class startPathChildrenCache_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("startPathChildrenCache_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField CACHE_DATA_FIELD_DESC = new org.apache.thrift.protocol.TField("cacheData", org.apache.thrift.protocol.TType.BOOL, (short)3); private static final org.apache.thrift.protocol.TField DATA_IS_COMPRESSED_FIELD_DESC = new org.apache.thrift.protocol.TField("dataIsCompressed", org.apache.thrift.protocol.TType.BOOL, (short)4); private static final org.apache.thrift.protocol.TField START_MODE_FIELD_DESC = new org.apache.thrift.protocol.TField("startMode", org.apache.thrift.protocol.TType.I32, (short)5); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new startPathChildrenCache_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new startPathChildrenCache_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public String path; // required public boolean cacheData; // required public boolean dataIsCompressed; // required /** * * @see PathChildrenCacheStartMode */ public PathChildrenCacheStartMode startMode; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), PATH((short)2, "path"), CACHE_DATA((short)3, "cacheData"), DATA_IS_COMPRESSED((short)4, "dataIsCompressed"), /** * * @see PathChildrenCacheStartMode */ START_MODE((short)5, "startMode"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // PATH return PATH; case 3: // CACHE_DATA return CACHE_DATA; case 4: // DATA_IS_COMPRESSED return DATA_IS_COMPRESSED; case 5: // START_MODE return START_MODE; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __CACHEDATA_ISSET_ID = 0; private static final int __DATAISCOMPRESSED_ISSET_ID = 1; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.CACHE_DATA, new org.apache.thrift.meta_data.FieldMetaData("cacheData", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.DATA_IS_COMPRESSED, new org.apache.thrift.meta_data.FieldMetaData("dataIsCompressed", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.START_MODE, new org.apache.thrift.meta_data.FieldMetaData("startMode", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, PathChildrenCacheStartMode.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(startPathChildrenCache_args.class, metaDataMap); } public startPathChildrenCache_args() { } public startPathChildrenCache_args( CuratorProjection projection, String path, boolean cacheData, boolean dataIsCompressed, PathChildrenCacheStartMode startMode) { this(); this.projection = projection; this.path = path; this.cacheData = cacheData; setCacheDataIsSet(true); this.dataIsCompressed = dataIsCompressed; setDataIsCompressedIsSet(true); this.startMode = startMode; } /** * Performs a deep copy on other. */ public startPathChildrenCache_args(startPathChildrenCache_args other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetPath()) { this.path = other.path; } this.cacheData = other.cacheData; this.dataIsCompressed = other.dataIsCompressed; if (other.isSetStartMode()) { this.startMode = other.startMode; } } public startPathChildrenCache_args deepCopy() { return new startPathChildrenCache_args(this); } @Override public void clear() { this.projection = null; this.path = null; setCacheDataIsSet(false); this.cacheData = false; setDataIsCompressedIsSet(false); this.dataIsCompressed = false; this.startMode = null; } public CuratorProjection getProjection() { return this.projection; } public startPathChildrenCache_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public String getPath() { return this.path; } public startPathChildrenCache_args setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public boolean isCacheData() { return this.cacheData; } public startPathChildrenCache_args setCacheData(boolean cacheData) { this.cacheData = cacheData; setCacheDataIsSet(true); return this; } public void unsetCacheData() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __CACHEDATA_ISSET_ID); } /** Returns true if field cacheData is set (has been assigned a value) and false otherwise */ public boolean isSetCacheData() { return EncodingUtils.testBit(__isset_bitfield, __CACHEDATA_ISSET_ID); } public void setCacheDataIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __CACHEDATA_ISSET_ID, value); } public boolean isDataIsCompressed() { return this.dataIsCompressed; } public startPathChildrenCache_args setDataIsCompressed(boolean dataIsCompressed) { this.dataIsCompressed = dataIsCompressed; setDataIsCompressedIsSet(true); return this; } public void unsetDataIsCompressed() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __DATAISCOMPRESSED_ISSET_ID); } /** Returns true if field dataIsCompressed is set (has been assigned a value) and false otherwise */ public boolean isSetDataIsCompressed() { return EncodingUtils.testBit(__isset_bitfield, __DATAISCOMPRESSED_ISSET_ID); } public void setDataIsCompressedIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __DATAISCOMPRESSED_ISSET_ID, value); } /** * * @see PathChildrenCacheStartMode */ public PathChildrenCacheStartMode getStartMode() { return this.startMode; } /** * * @see PathChildrenCacheStartMode */ public startPathChildrenCache_args setStartMode(PathChildrenCacheStartMode startMode) { this.startMode = startMode; return this; } public void unsetStartMode() { this.startMode = null; } /** Returns true if field startMode is set (has been assigned a value) and false otherwise */ public boolean isSetStartMode() { return this.startMode != null; } public void setStartModeIsSet(boolean value) { if (!value) { this.startMode = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; case CACHE_DATA: if (value == null) { unsetCacheData(); } else { setCacheData((Boolean)value); } break; case DATA_IS_COMPRESSED: if (value == null) { unsetDataIsCompressed(); } else { setDataIsCompressed((Boolean)value); } break; case START_MODE: if (value == null) { unsetStartMode(); } else { setStartMode((PathChildrenCacheStartMode)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case PATH: return getPath(); case CACHE_DATA: return Boolean.valueOf(isCacheData()); case DATA_IS_COMPRESSED: return Boolean.valueOf(isDataIsCompressed()); case START_MODE: return getStartMode(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case PATH: return isSetPath(); case CACHE_DATA: return isSetCacheData(); case DATA_IS_COMPRESSED: return isSetDataIsCompressed(); case START_MODE: return isSetStartMode(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof startPathChildrenCache_args) return this.equals((startPathChildrenCache_args)that); return false; } public boolean equals(startPathChildrenCache_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } boolean this_present_cacheData = true; boolean that_present_cacheData = true; if (this_present_cacheData || that_present_cacheData) { if (!(this_present_cacheData && that_present_cacheData)) return false; if (this.cacheData != that.cacheData) return false; } boolean this_present_dataIsCompressed = true; boolean that_present_dataIsCompressed = true; if (this_present_dataIsCompressed || that_present_dataIsCompressed) { if (!(this_present_dataIsCompressed && that_present_dataIsCompressed)) return false; if (this.dataIsCompressed != that.dataIsCompressed) return false; } boolean this_present_startMode = true && this.isSetStartMode(); boolean that_present_startMode = true && that.isSetStartMode(); if (this_present_startMode || that_present_startMode) { if (!(this_present_startMode && that_present_startMode)) return false; if (!this.startMode.equals(that.startMode)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(startPathChildrenCache_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetCacheData()).compareTo(other.isSetCacheData()); if (lastComparison != 0) { return lastComparison; } if (isSetCacheData()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.cacheData, other.cacheData); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetDataIsCompressed()).compareTo(other.isSetDataIsCompressed()); if (lastComparison != 0) { return lastComparison; } if (isSetDataIsCompressed()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.dataIsCompressed, other.dataIsCompressed); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetStartMode()).compareTo(other.isSetStartMode()); if (lastComparison != 0) { return lastComparison; } if (isSetStartMode()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.startMode, other.startMode); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("startPathChildrenCache_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; if (!first) sb.append(", "); sb.append("cacheData:"); sb.append(this.cacheData); first = false; if (!first) sb.append(", "); sb.append("dataIsCompressed:"); sb.append(this.dataIsCompressed); first = false; if (!first) sb.append(", "); sb.append("startMode:"); if (this.startMode == null) { sb.append("null"); } else { sb.append(this.startMode); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class startPathChildrenCache_argsStandardSchemeFactory implements SchemeFactory { public startPathChildrenCache_argsStandardScheme getScheme() { return new startPathChildrenCache_argsStandardScheme(); } } private static class startPathChildrenCache_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, startPathChildrenCache_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // CACHE_DATA if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.cacheData = iprot.readBool(); struct.setCacheDataIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // DATA_IS_COMPRESSED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.dataIsCompressed = iprot.readBool(); struct.setDataIsCompressedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // START_MODE if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.startMode = PathChildrenCacheStartMode.findByValue(iprot.readI32()); struct.setStartModeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, startPathChildrenCache_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } oprot.writeFieldBegin(CACHE_DATA_FIELD_DESC); oprot.writeBool(struct.cacheData); oprot.writeFieldEnd(); oprot.writeFieldBegin(DATA_IS_COMPRESSED_FIELD_DESC); oprot.writeBool(struct.dataIsCompressed); oprot.writeFieldEnd(); if (struct.startMode != null) { oprot.writeFieldBegin(START_MODE_FIELD_DESC); oprot.writeI32(struct.startMode.getValue()); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class startPathChildrenCache_argsTupleSchemeFactory implements SchemeFactory { public startPathChildrenCache_argsTupleScheme getScheme() { return new startPathChildrenCache_argsTupleScheme(); } } private static class startPathChildrenCache_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, startPathChildrenCache_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetPath()) { optionals.set(1); } if (struct.isSetCacheData()) { optionals.set(2); } if (struct.isSetDataIsCompressed()) { optionals.set(3); } if (struct.isSetStartMode()) { optionals.set(4); } oprot.writeBitSet(optionals, 5); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetPath()) { oprot.writeString(struct.path); } if (struct.isSetCacheData()) { oprot.writeBool(struct.cacheData); } if (struct.isSetDataIsCompressed()) { oprot.writeBool(struct.dataIsCompressed); } if (struct.isSetStartMode()) { oprot.writeI32(struct.startMode.getValue()); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, startPathChildrenCache_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(5); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } if (incoming.get(2)) { struct.cacheData = iprot.readBool(); struct.setCacheDataIsSet(true); } if (incoming.get(3)) { struct.dataIsCompressed = iprot.readBool(); struct.setDataIsCompressedIsSet(true); } if (incoming.get(4)) { struct.startMode = PathChildrenCacheStartMode.findByValue(iprot.readI32()); struct.setStartModeIsSet(true); } } } } public static class startPathChildrenCache_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("startPathChildrenCache_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new startPathChildrenCache_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new startPathChildrenCache_resultTupleSchemeFactory()); } public PathChildrenCacheProjection success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, PathChildrenCacheProjection.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(startPathChildrenCache_result.class, metaDataMap); } public startPathChildrenCache_result() { } public startPathChildrenCache_result( PathChildrenCacheProjection success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public startPathChildrenCache_result(startPathChildrenCache_result other) { if (other.isSetSuccess()) { this.success = new PathChildrenCacheProjection(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public startPathChildrenCache_result deepCopy() { return new startPathChildrenCache_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public PathChildrenCacheProjection getSuccess() { return this.success; } public startPathChildrenCache_result setSuccess(PathChildrenCacheProjection success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public startPathChildrenCache_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((PathChildrenCacheProjection)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof startPathChildrenCache_result) return this.equals((startPathChildrenCache_result)that); return false; } public boolean equals(startPathChildrenCache_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(startPathChildrenCache_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("startPathChildrenCache_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class startPathChildrenCache_resultStandardSchemeFactory implements SchemeFactory { public startPathChildrenCache_resultStandardScheme getScheme() { return new startPathChildrenCache_resultStandardScheme(); } } private static class startPathChildrenCache_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, startPathChildrenCache_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new PathChildrenCacheProjection(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, startPathChildrenCache_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class startPathChildrenCache_resultTupleSchemeFactory implements SchemeFactory { public startPathChildrenCache_resultTupleScheme getScheme() { return new startPathChildrenCache_resultTupleScheme(); } } private static class startPathChildrenCache_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, startPathChildrenCache_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, startPathChildrenCache_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new PathChildrenCacheProjection(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class startPersistentEphemeralNode_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("startPersistentEphemeralNode_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField DATA_FIELD_DESC = new org.apache.thrift.protocol.TField("data", org.apache.thrift.protocol.TType.STRING, (short)3); private static final org.apache.thrift.protocol.TField MODE_FIELD_DESC = new org.apache.thrift.protocol.TField("mode", org.apache.thrift.protocol.TType.I32, (short)4); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new startPersistentEphemeralNode_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new startPersistentEphemeralNode_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public String path; // required public ByteBuffer data; // required /** * * @see PersistentEphemeralNodeMode */ public PersistentEphemeralNodeMode mode; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), PATH((short)2, "path"), DATA((short)3, "data"), /** * * @see PersistentEphemeralNodeMode */ MODE((short)4, "mode"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // PATH return PATH; case 3: // DATA return DATA; case 4: // MODE return MODE; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.DATA, new org.apache.thrift.meta_data.FieldMetaData("data", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true))); tmpMap.put(_Fields.MODE, new org.apache.thrift.meta_data.FieldMetaData("mode", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, PersistentEphemeralNodeMode.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(startPersistentEphemeralNode_args.class, metaDataMap); } public startPersistentEphemeralNode_args() { } public startPersistentEphemeralNode_args( CuratorProjection projection, String path, ByteBuffer data, PersistentEphemeralNodeMode mode) { this(); this.projection = projection; this.path = path; this.data = data; this.mode = mode; } /** * Performs a deep copy on other. */ public startPersistentEphemeralNode_args(startPersistentEphemeralNode_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetPath()) { this.path = other.path; } if (other.isSetData()) { this.data = org.apache.thrift.TBaseHelper.copyBinary(other.data); ; } if (other.isSetMode()) { this.mode = other.mode; } } public startPersistentEphemeralNode_args deepCopy() { return new startPersistentEphemeralNode_args(this); } @Override public void clear() { this.projection = null; this.path = null; this.data = null; this.mode = null; } public CuratorProjection getProjection() { return this.projection; } public startPersistentEphemeralNode_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public String getPath() { return this.path; } public startPersistentEphemeralNode_args setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public byte[] getData() { setData(org.apache.thrift.TBaseHelper.rightSize(data)); return data == null ? null : data.array(); } public ByteBuffer bufferForData() { return data; } public startPersistentEphemeralNode_args setData(byte[] data) { setData(data == null ? (ByteBuffer)null : ByteBuffer.wrap(data)); return this; } public startPersistentEphemeralNode_args setData(ByteBuffer data) { this.data = data; return this; } public void unsetData() { this.data = null; } /** Returns true if field data is set (has been assigned a value) and false otherwise */ public boolean isSetData() { return this.data != null; } public void setDataIsSet(boolean value) { if (!value) { this.data = null; } } /** * * @see PersistentEphemeralNodeMode */ public PersistentEphemeralNodeMode getMode() { return this.mode; } /** * * @see PersistentEphemeralNodeMode */ public startPersistentEphemeralNode_args setMode(PersistentEphemeralNodeMode mode) { this.mode = mode; return this; } public void unsetMode() { this.mode = null; } /** Returns true if field mode is set (has been assigned a value) and false otherwise */ public boolean isSetMode() { return this.mode != null; } public void setModeIsSet(boolean value) { if (!value) { this.mode = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; case DATA: if (value == null) { unsetData(); } else { setData((ByteBuffer)value); } break; case MODE: if (value == null) { unsetMode(); } else { setMode((PersistentEphemeralNodeMode)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case PATH: return getPath(); case DATA: return getData(); case MODE: return getMode(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case PATH: return isSetPath(); case DATA: return isSetData(); case MODE: return isSetMode(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof startPersistentEphemeralNode_args) return this.equals((startPersistentEphemeralNode_args)that); return false; } public boolean equals(startPersistentEphemeralNode_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } boolean this_present_data = true && this.isSetData(); boolean that_present_data = true && that.isSetData(); if (this_present_data || that_present_data) { if (!(this_present_data && that_present_data)) return false; if (!this.data.equals(that.data)) return false; } boolean this_present_mode = true && this.isSetMode(); boolean that_present_mode = true && that.isSetMode(); if (this_present_mode || that_present_mode) { if (!(this_present_mode && that_present_mode)) return false; if (!this.mode.equals(that.mode)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(startPersistentEphemeralNode_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetData()).compareTo(other.isSetData()); if (lastComparison != 0) { return lastComparison; } if (isSetData()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.data, other.data); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetMode()).compareTo(other.isSetMode()); if (lastComparison != 0) { return lastComparison; } if (isSetMode()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.mode, other.mode); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("startPersistentEphemeralNode_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; if (!first) sb.append(", "); sb.append("data:"); if (this.data == null) { sb.append("null"); } else { org.apache.thrift.TBaseHelper.toString(this.data, sb); } first = false; if (!first) sb.append(", "); sb.append("mode:"); if (this.mode == null) { sb.append("null"); } else { sb.append(this.mode); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class startPersistentEphemeralNode_argsStandardSchemeFactory implements SchemeFactory { public startPersistentEphemeralNode_argsStandardScheme getScheme() { return new startPersistentEphemeralNode_argsStandardScheme(); } } private static class startPersistentEphemeralNode_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, startPersistentEphemeralNode_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // DATA if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.data = iprot.readBinary(); struct.setDataIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // MODE if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.mode = PersistentEphemeralNodeMode.findByValue(iprot.readI32()); struct.setModeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, startPersistentEphemeralNode_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } if (struct.data != null) { oprot.writeFieldBegin(DATA_FIELD_DESC); oprot.writeBinary(struct.data); oprot.writeFieldEnd(); } if (struct.mode != null) { oprot.writeFieldBegin(MODE_FIELD_DESC); oprot.writeI32(struct.mode.getValue()); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class startPersistentEphemeralNode_argsTupleSchemeFactory implements SchemeFactory { public startPersistentEphemeralNode_argsTupleScheme getScheme() { return new startPersistentEphemeralNode_argsTupleScheme(); } } private static class startPersistentEphemeralNode_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, startPersistentEphemeralNode_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetPath()) { optionals.set(1); } if (struct.isSetData()) { optionals.set(2); } if (struct.isSetMode()) { optionals.set(3); } oprot.writeBitSet(optionals, 4); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetPath()) { oprot.writeString(struct.path); } if (struct.isSetData()) { oprot.writeBinary(struct.data); } if (struct.isSetMode()) { oprot.writeI32(struct.mode.getValue()); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, startPersistentEphemeralNode_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(4); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } if (incoming.get(2)) { struct.data = iprot.readBinary(); struct.setDataIsSet(true); } if (incoming.get(3)) { struct.mode = PersistentEphemeralNodeMode.findByValue(iprot.readI32()); struct.setModeIsSet(true); } } } } public static class startPersistentEphemeralNode_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("startPersistentEphemeralNode_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new startPersistentEphemeralNode_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new startPersistentEphemeralNode_resultTupleSchemeFactory()); } public PersistentEphemeralNodeProjection success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, PersistentEphemeralNodeProjection.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(startPersistentEphemeralNode_result.class, metaDataMap); } public startPersistentEphemeralNode_result() { } public startPersistentEphemeralNode_result( PersistentEphemeralNodeProjection success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public startPersistentEphemeralNode_result(startPersistentEphemeralNode_result other) { if (other.isSetSuccess()) { this.success = new PersistentEphemeralNodeProjection(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public startPersistentEphemeralNode_result deepCopy() { return new startPersistentEphemeralNode_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public PersistentEphemeralNodeProjection getSuccess() { return this.success; } public startPersistentEphemeralNode_result setSuccess(PersistentEphemeralNodeProjection success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public startPersistentEphemeralNode_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((PersistentEphemeralNodeProjection)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof startPersistentEphemeralNode_result) return this.equals((startPersistentEphemeralNode_result)that); return false; } public boolean equals(startPersistentEphemeralNode_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(startPersistentEphemeralNode_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("startPersistentEphemeralNode_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class startPersistentEphemeralNode_resultStandardSchemeFactory implements SchemeFactory { public startPersistentEphemeralNode_resultStandardScheme getScheme() { return new startPersistentEphemeralNode_resultStandardScheme(); } } private static class startPersistentEphemeralNode_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, startPersistentEphemeralNode_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new PersistentEphemeralNodeProjection(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, startPersistentEphemeralNode_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class startPersistentEphemeralNode_resultTupleSchemeFactory implements SchemeFactory { public startPersistentEphemeralNode_resultTupleScheme getScheme() { return new startPersistentEphemeralNode_resultTupleScheme(); } } private static class startPersistentEphemeralNode_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, startPersistentEphemeralNode_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, startPersistentEphemeralNode_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new PersistentEphemeralNodeProjection(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class sync_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sync_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField ASYNC_CONTEXT_FIELD_DESC = new org.apache.thrift.protocol.TField("asyncContext", org.apache.thrift.protocol.TType.STRING, (short)3); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new sync_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new sync_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public String path; // required public String asyncContext; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), PATH((short)2, "path"), ASYNC_CONTEXT((short)3, "asyncContext"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // PATH return PATH; case 3: // ASYNC_CONTEXT return ASYNC_CONTEXT; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.ASYNC_CONTEXT, new org.apache.thrift.meta_data.FieldMetaData("asyncContext", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sync_args.class, metaDataMap); } public sync_args() { } public sync_args( CuratorProjection projection, String path, String asyncContext) { this(); this.projection = projection; this.path = path; this.asyncContext = asyncContext; } /** * Performs a deep copy on other. */ public sync_args(sync_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetPath()) { this.path = other.path; } if (other.isSetAsyncContext()) { this.asyncContext = other.asyncContext; } } public sync_args deepCopy() { return new sync_args(this); } @Override public void clear() { this.projection = null; this.path = null; this.asyncContext = null; } public CuratorProjection getProjection() { return this.projection; } public sync_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public String getPath() { return this.path; } public sync_args setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public String getAsyncContext() { return this.asyncContext; } public sync_args setAsyncContext(String asyncContext) { this.asyncContext = asyncContext; return this; } public void unsetAsyncContext() { this.asyncContext = null; } /** Returns true if field asyncContext is set (has been assigned a value) and false otherwise */ public boolean isSetAsyncContext() { return this.asyncContext != null; } public void setAsyncContextIsSet(boolean value) { if (!value) { this.asyncContext = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; case ASYNC_CONTEXT: if (value == null) { unsetAsyncContext(); } else { setAsyncContext((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case PATH: return getPath(); case ASYNC_CONTEXT: return getAsyncContext(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case PATH: return isSetPath(); case ASYNC_CONTEXT: return isSetAsyncContext(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof sync_args) return this.equals((sync_args)that); return false; } public boolean equals(sync_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } boolean this_present_asyncContext = true && this.isSetAsyncContext(); boolean that_present_asyncContext = true && that.isSetAsyncContext(); if (this_present_asyncContext || that_present_asyncContext) { if (!(this_present_asyncContext && that_present_asyncContext)) return false; if (!this.asyncContext.equals(that.asyncContext)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(sync_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetAsyncContext()).compareTo(other.isSetAsyncContext()); if (lastComparison != 0) { return lastComparison; } if (isSetAsyncContext()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.asyncContext, other.asyncContext); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("sync_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; if (!first) sb.append(", "); sb.append("asyncContext:"); if (this.asyncContext == null) { sb.append("null"); } else { sb.append(this.asyncContext); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class sync_argsStandardSchemeFactory implements SchemeFactory { public sync_argsStandardScheme getScheme() { return new sync_argsStandardScheme(); } } private static class sync_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, sync_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // ASYNC_CONTEXT if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.asyncContext = iprot.readString(); struct.setAsyncContextIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, sync_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } if (struct.asyncContext != null) { oprot.writeFieldBegin(ASYNC_CONTEXT_FIELD_DESC); oprot.writeString(struct.asyncContext); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class sync_argsTupleSchemeFactory implements SchemeFactory { public sync_argsTupleScheme getScheme() { return new sync_argsTupleScheme(); } } private static class sync_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, sync_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetPath()) { optionals.set(1); } if (struct.isSetAsyncContext()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetPath()) { oprot.writeString(struct.path); } if (struct.isSetAsyncContext()) { oprot.writeString(struct.asyncContext); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, sync_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } if (incoming.get(2)) { struct.asyncContext = iprot.readString(); struct.setAsyncContextIsSet(true); } } } } public static class sync_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sync_result"); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new sync_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new sync_resultTupleSchemeFactory()); } public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sync_result.class, metaDataMap); } public sync_result() { } public sync_result( CuratorException ex1) { this(); this.ex1 = ex1; } /** * Performs a deep copy on other. */ public sync_result(sync_result other) { if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public sync_result deepCopy() { return new sync_result(this); } @Override public void clear() { this.ex1 = null; } public CuratorException getEx1() { return this.ex1; } public sync_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof sync_result) return this.equals((sync_result)that); return false; } public boolean equals(sync_result that) { if (that == null) return false; boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(sync_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("sync_result("); boolean first = true; sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class sync_resultStandardSchemeFactory implements SchemeFactory { public sync_resultStandardScheme getScheme() { return new sync_resultStandardScheme(); } } private static class sync_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, sync_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, sync_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class sync_resultTupleSchemeFactory implements SchemeFactory { public sync_resultTupleScheme getScheme() { return new sync_resultTupleScheme(); } } private static class sync_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, sync_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetEx1()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, sync_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } } DeleteSpec.java000066400000000000000000000516721245521677600335510ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DeleteSpec implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("DeleteSpec"); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField GUARANTEED_FIELD_DESC = new org.apache.thrift.protocol.TField("guaranteed", org.apache.thrift.protocol.TType.BOOL, (short)2); private static final org.apache.thrift.protocol.TField ASYNC_CONTEXT_FIELD_DESC = new org.apache.thrift.protocol.TField("asyncContext", org.apache.thrift.protocol.TType.STRING, (short)3); private static final org.apache.thrift.protocol.TField VERSION_FIELD_DESC = new org.apache.thrift.protocol.TField("version", org.apache.thrift.protocol.TType.STRUCT, (short)4); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new DeleteSpecStandardSchemeFactory()); schemes.put(TupleScheme.class, new DeleteSpecTupleSchemeFactory()); } public String path; // required public boolean guaranteed; // required public String asyncContext; // required public Version version; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PATH((short)1, "path"), GUARANTEED((short)2, "guaranteed"), ASYNC_CONTEXT((short)3, "asyncContext"), VERSION((short)4, "version"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PATH return PATH; case 2: // GUARANTEED return GUARANTEED; case 3: // ASYNC_CONTEXT return ASYNC_CONTEXT; case 4: // VERSION return VERSION; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __GUARANTEED_ISSET_ID = 0; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.GUARANTEED, new org.apache.thrift.meta_data.FieldMetaData("guaranteed", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.ASYNC_CONTEXT, new org.apache.thrift.meta_data.FieldMetaData("asyncContext", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.VERSION, new org.apache.thrift.meta_data.FieldMetaData("version", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, Version.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(DeleteSpec.class, metaDataMap); } public DeleteSpec() { } public DeleteSpec( String path, boolean guaranteed, String asyncContext, Version version) { this(); this.path = path; this.guaranteed = guaranteed; setGuaranteedIsSet(true); this.asyncContext = asyncContext; this.version = version; } /** * Performs a deep copy on other. */ public DeleteSpec(DeleteSpec other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetPath()) { this.path = other.path; } this.guaranteed = other.guaranteed; if (other.isSetAsyncContext()) { this.asyncContext = other.asyncContext; } if (other.isSetVersion()) { this.version = new Version(other.version); } } public DeleteSpec deepCopy() { return new DeleteSpec(this); } @Override public void clear() { this.path = null; setGuaranteedIsSet(false); this.guaranteed = false; this.asyncContext = null; this.version = null; } public String getPath() { return this.path; } public DeleteSpec setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public boolean isGuaranteed() { return this.guaranteed; } public DeleteSpec setGuaranteed(boolean guaranteed) { this.guaranteed = guaranteed; setGuaranteedIsSet(true); return this; } public void unsetGuaranteed() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __GUARANTEED_ISSET_ID); } /** Returns true if field guaranteed is set (has been assigned a value) and false otherwise */ public boolean isSetGuaranteed() { return EncodingUtils.testBit(__isset_bitfield, __GUARANTEED_ISSET_ID); } public void setGuaranteedIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __GUARANTEED_ISSET_ID, value); } public String getAsyncContext() { return this.asyncContext; } public DeleteSpec setAsyncContext(String asyncContext) { this.asyncContext = asyncContext; return this; } public void unsetAsyncContext() { this.asyncContext = null; } /** Returns true if field asyncContext is set (has been assigned a value) and false otherwise */ public boolean isSetAsyncContext() { return this.asyncContext != null; } public void setAsyncContextIsSet(boolean value) { if (!value) { this.asyncContext = null; } } public Version getVersion() { return this.version; } public DeleteSpec setVersion(Version version) { this.version = version; return this; } public void unsetVersion() { this.version = null; } /** Returns true if field version is set (has been assigned a value) and false otherwise */ public boolean isSetVersion() { return this.version != null; } public void setVersionIsSet(boolean value) { if (!value) { this.version = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; case GUARANTEED: if (value == null) { unsetGuaranteed(); } else { setGuaranteed((Boolean)value); } break; case ASYNC_CONTEXT: if (value == null) { unsetAsyncContext(); } else { setAsyncContext((String)value); } break; case VERSION: if (value == null) { unsetVersion(); } else { setVersion((Version)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PATH: return getPath(); case GUARANTEED: return Boolean.valueOf(isGuaranteed()); case ASYNC_CONTEXT: return getAsyncContext(); case VERSION: return getVersion(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PATH: return isSetPath(); case GUARANTEED: return isSetGuaranteed(); case ASYNC_CONTEXT: return isSetAsyncContext(); case VERSION: return isSetVersion(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof DeleteSpec) return this.equals((DeleteSpec)that); return false; } public boolean equals(DeleteSpec that) { if (that == null) return false; boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } boolean this_present_guaranteed = true; boolean that_present_guaranteed = true; if (this_present_guaranteed || that_present_guaranteed) { if (!(this_present_guaranteed && that_present_guaranteed)) return false; if (this.guaranteed != that.guaranteed) return false; } boolean this_present_asyncContext = true && this.isSetAsyncContext(); boolean that_present_asyncContext = true && that.isSetAsyncContext(); if (this_present_asyncContext || that_present_asyncContext) { if (!(this_present_asyncContext && that_present_asyncContext)) return false; if (!this.asyncContext.equals(that.asyncContext)) return false; } boolean this_present_version = true && this.isSetVersion(); boolean that_present_version = true && that.isSetVersion(); if (this_present_version || that_present_version) { if (!(this_present_version && that_present_version)) return false; if (!this.version.equals(that.version)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(DeleteSpec other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetGuaranteed()).compareTo(other.isSetGuaranteed()); if (lastComparison != 0) { return lastComparison; } if (isSetGuaranteed()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.guaranteed, other.guaranteed); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetAsyncContext()).compareTo(other.isSetAsyncContext()); if (lastComparison != 0) { return lastComparison; } if (isSetAsyncContext()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.asyncContext, other.asyncContext); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetVersion()).compareTo(other.isSetVersion()); if (lastComparison != 0) { return lastComparison; } if (isSetVersion()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.version, other.version); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("DeleteSpec("); boolean first = true; sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; if (!first) sb.append(", "); sb.append("guaranteed:"); sb.append(this.guaranteed); first = false; if (!first) sb.append(", "); sb.append("asyncContext:"); if (this.asyncContext == null) { sb.append("null"); } else { sb.append(this.asyncContext); } first = false; if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (version != null) { version.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class DeleteSpecStandardSchemeFactory implements SchemeFactory { public DeleteSpecStandardScheme getScheme() { return new DeleteSpecStandardScheme(); } } private static class DeleteSpecStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, DeleteSpec struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // GUARANTEED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.guaranteed = iprot.readBool(); struct.setGuaranteedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // ASYNC_CONTEXT if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.asyncContext = iprot.readString(); struct.setAsyncContextIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // VERSION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.version = new Version(); struct.version.read(iprot); struct.setVersionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, DeleteSpec struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } oprot.writeFieldBegin(GUARANTEED_FIELD_DESC); oprot.writeBool(struct.guaranteed); oprot.writeFieldEnd(); if (struct.asyncContext != null) { oprot.writeFieldBegin(ASYNC_CONTEXT_FIELD_DESC); oprot.writeString(struct.asyncContext); oprot.writeFieldEnd(); } if (struct.version != null) { oprot.writeFieldBegin(VERSION_FIELD_DESC); struct.version.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class DeleteSpecTupleSchemeFactory implements SchemeFactory { public DeleteSpecTupleScheme getScheme() { return new DeleteSpecTupleScheme(); } } private static class DeleteSpecTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, DeleteSpec struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetPath()) { optionals.set(0); } if (struct.isSetGuaranteed()) { optionals.set(1); } if (struct.isSetAsyncContext()) { optionals.set(2); } if (struct.isSetVersion()) { optionals.set(3); } oprot.writeBitSet(optionals, 4); if (struct.isSetPath()) { oprot.writeString(struct.path); } if (struct.isSetGuaranteed()) { oprot.writeBool(struct.guaranteed); } if (struct.isSetAsyncContext()) { oprot.writeString(struct.asyncContext); } if (struct.isSetVersion()) { struct.version.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, DeleteSpec struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(4); if (incoming.get(0)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } if (incoming.get(1)) { struct.guaranteed = iprot.readBool(); struct.setGuaranteedIsSet(true); } if (incoming.get(2)) { struct.asyncContext = iprot.readString(); struct.setAsyncContextIsSet(true); } if (incoming.get(3)) { struct.version = new Version(); struct.version.read(iprot); struct.setVersionIsSet(true); } } } } DiscoveryInstance.java000066400000000000000000001117361245521677600351660ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DiscoveryInstance implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("DiscoveryInstance"); private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField ADDRESS_FIELD_DESC = new org.apache.thrift.protocol.TField("address", org.apache.thrift.protocol.TType.STRING, (short)3); private static final org.apache.thrift.protocol.TField PORT_FIELD_DESC = new org.apache.thrift.protocol.TField("port", org.apache.thrift.protocol.TType.I32, (short)4); private static final org.apache.thrift.protocol.TField SSL_PORT_FIELD_DESC = new org.apache.thrift.protocol.TField("sslPort", org.apache.thrift.protocol.TType.I32, (short)5); private static final org.apache.thrift.protocol.TField PAYLOAD_FIELD_DESC = new org.apache.thrift.protocol.TField("payload", org.apache.thrift.protocol.TType.STRING, (short)6); private static final org.apache.thrift.protocol.TField REGISTRATION_TIME_UTC_FIELD_DESC = new org.apache.thrift.protocol.TField("registrationTimeUTC", org.apache.thrift.protocol.TType.I64, (short)7); private static final org.apache.thrift.protocol.TField SERVICE_TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("serviceType", org.apache.thrift.protocol.TType.I32, (short)8); private static final org.apache.thrift.protocol.TField URI_SPEC_FIELD_DESC = new org.apache.thrift.protocol.TField("uriSpec", org.apache.thrift.protocol.TType.STRING, (short)9); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new DiscoveryInstanceStandardSchemeFactory()); schemes.put(TupleScheme.class, new DiscoveryInstanceTupleSchemeFactory()); } public String name; // required public String id; // required public String address; // required public int port; // required public int sslPort; // required public ByteBuffer payload; // required public long registrationTimeUTC; // required /** * * @see DiscoveryInstanceType */ public DiscoveryInstanceType serviceType; // required public String uriSpec; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { NAME((short)1, "name"), ID((short)2, "id"), ADDRESS((short)3, "address"), PORT((short)4, "port"), SSL_PORT((short)5, "sslPort"), PAYLOAD((short)6, "payload"), REGISTRATION_TIME_UTC((short)7, "registrationTimeUTC"), /** * * @see DiscoveryInstanceType */ SERVICE_TYPE((short)8, "serviceType"), URI_SPEC((short)9, "uriSpec"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // NAME return NAME; case 2: // ID return ID; case 3: // ADDRESS return ADDRESS; case 4: // PORT return PORT; case 5: // SSL_PORT return SSL_PORT; case 6: // PAYLOAD return PAYLOAD; case 7: // REGISTRATION_TIME_UTC return REGISTRATION_TIME_UTC; case 8: // SERVICE_TYPE return SERVICE_TYPE; case 9: // URI_SPEC return URI_SPEC; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __PORT_ISSET_ID = 0; private static final int __SSLPORT_ISSET_ID = 1; private static final int __REGISTRATIONTIMEUTC_ISSET_ID = 2; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.ADDRESS, new org.apache.thrift.meta_data.FieldMetaData("address", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.PORT, new org.apache.thrift.meta_data.FieldMetaData("port", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.SSL_PORT, new org.apache.thrift.meta_data.FieldMetaData("sslPort", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.PAYLOAD, new org.apache.thrift.meta_data.FieldMetaData("payload", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true))); tmpMap.put(_Fields.REGISTRATION_TIME_UTC, new org.apache.thrift.meta_data.FieldMetaData("registrationTimeUTC", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); tmpMap.put(_Fields.SERVICE_TYPE, new org.apache.thrift.meta_data.FieldMetaData("serviceType", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, DiscoveryInstanceType.class))); tmpMap.put(_Fields.URI_SPEC, new org.apache.thrift.meta_data.FieldMetaData("uriSpec", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(DiscoveryInstance.class, metaDataMap); } public DiscoveryInstance() { } public DiscoveryInstance( String name, String id, String address, int port, int sslPort, ByteBuffer payload, long registrationTimeUTC, DiscoveryInstanceType serviceType, String uriSpec) { this(); this.name = name; this.id = id; this.address = address; this.port = port; setPortIsSet(true); this.sslPort = sslPort; setSslPortIsSet(true); this.payload = payload; this.registrationTimeUTC = registrationTimeUTC; setRegistrationTimeUTCIsSet(true); this.serviceType = serviceType; this.uriSpec = uriSpec; } /** * Performs a deep copy on other. */ public DiscoveryInstance(DiscoveryInstance other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetName()) { this.name = other.name; } if (other.isSetId()) { this.id = other.id; } if (other.isSetAddress()) { this.address = other.address; } this.port = other.port; this.sslPort = other.sslPort; if (other.isSetPayload()) { this.payload = org.apache.thrift.TBaseHelper.copyBinary(other.payload); ; } this.registrationTimeUTC = other.registrationTimeUTC; if (other.isSetServiceType()) { this.serviceType = other.serviceType; } if (other.isSetUriSpec()) { this.uriSpec = other.uriSpec; } } public DiscoveryInstance deepCopy() { return new DiscoveryInstance(this); } @Override public void clear() { this.name = null; this.id = null; this.address = null; setPortIsSet(false); this.port = 0; setSslPortIsSet(false); this.sslPort = 0; this.payload = null; setRegistrationTimeUTCIsSet(false); this.registrationTimeUTC = 0; this.serviceType = null; this.uriSpec = null; } public String getName() { return this.name; } public DiscoveryInstance setName(String name) { this.name = name; return this; } public void unsetName() { this.name = null; } /** Returns true if field name is set (has been assigned a value) and false otherwise */ public boolean isSetName() { return this.name != null; } public void setNameIsSet(boolean value) { if (!value) { this.name = null; } } public String getId() { return this.id; } public DiscoveryInstance setId(String id) { this.id = id; return this; } public void unsetId() { this.id = null; } /** Returns true if field id is set (has been assigned a value) and false otherwise */ public boolean isSetId() { return this.id != null; } public void setIdIsSet(boolean value) { if (!value) { this.id = null; } } public String getAddress() { return this.address; } public DiscoveryInstance setAddress(String address) { this.address = address; return this; } public void unsetAddress() { this.address = null; } /** Returns true if field address is set (has been assigned a value) and false otherwise */ public boolean isSetAddress() { return this.address != null; } public void setAddressIsSet(boolean value) { if (!value) { this.address = null; } } public int getPort() { return this.port; } public DiscoveryInstance setPort(int port) { this.port = port; setPortIsSet(true); return this; } public void unsetPort() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __PORT_ISSET_ID); } /** Returns true if field port is set (has been assigned a value) and false otherwise */ public boolean isSetPort() { return EncodingUtils.testBit(__isset_bitfield, __PORT_ISSET_ID); } public void setPortIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __PORT_ISSET_ID, value); } public int getSslPort() { return this.sslPort; } public DiscoveryInstance setSslPort(int sslPort) { this.sslPort = sslPort; setSslPortIsSet(true); return this; } public void unsetSslPort() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SSLPORT_ISSET_ID); } /** Returns true if field sslPort is set (has been assigned a value) and false otherwise */ public boolean isSetSslPort() { return EncodingUtils.testBit(__isset_bitfield, __SSLPORT_ISSET_ID); } public void setSslPortIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SSLPORT_ISSET_ID, value); } public byte[] getPayload() { setPayload(org.apache.thrift.TBaseHelper.rightSize(payload)); return payload == null ? null : payload.array(); } public ByteBuffer bufferForPayload() { return payload; } public DiscoveryInstance setPayload(byte[] payload) { setPayload(payload == null ? (ByteBuffer)null : ByteBuffer.wrap(payload)); return this; } public DiscoveryInstance setPayload(ByteBuffer payload) { this.payload = payload; return this; } public void unsetPayload() { this.payload = null; } /** Returns true if field payload is set (has been assigned a value) and false otherwise */ public boolean isSetPayload() { return this.payload != null; } public void setPayloadIsSet(boolean value) { if (!value) { this.payload = null; } } public long getRegistrationTimeUTC() { return this.registrationTimeUTC; } public DiscoveryInstance setRegistrationTimeUTC(long registrationTimeUTC) { this.registrationTimeUTC = registrationTimeUTC; setRegistrationTimeUTCIsSet(true); return this; } public void unsetRegistrationTimeUTC() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __REGISTRATIONTIMEUTC_ISSET_ID); } /** Returns true if field registrationTimeUTC is set (has been assigned a value) and false otherwise */ public boolean isSetRegistrationTimeUTC() { return EncodingUtils.testBit(__isset_bitfield, __REGISTRATIONTIMEUTC_ISSET_ID); } public void setRegistrationTimeUTCIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __REGISTRATIONTIMEUTC_ISSET_ID, value); } /** * * @see DiscoveryInstanceType */ public DiscoveryInstanceType getServiceType() { return this.serviceType; } /** * * @see DiscoveryInstanceType */ public DiscoveryInstance setServiceType(DiscoveryInstanceType serviceType) { this.serviceType = serviceType; return this; } public void unsetServiceType() { this.serviceType = null; } /** Returns true if field serviceType is set (has been assigned a value) and false otherwise */ public boolean isSetServiceType() { return this.serviceType != null; } public void setServiceTypeIsSet(boolean value) { if (!value) { this.serviceType = null; } } public String getUriSpec() { return this.uriSpec; } public DiscoveryInstance setUriSpec(String uriSpec) { this.uriSpec = uriSpec; return this; } public void unsetUriSpec() { this.uriSpec = null; } /** Returns true if field uriSpec is set (has been assigned a value) and false otherwise */ public boolean isSetUriSpec() { return this.uriSpec != null; } public void setUriSpecIsSet(boolean value) { if (!value) { this.uriSpec = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case NAME: if (value == null) { unsetName(); } else { setName((String)value); } break; case ID: if (value == null) { unsetId(); } else { setId((String)value); } break; case ADDRESS: if (value == null) { unsetAddress(); } else { setAddress((String)value); } break; case PORT: if (value == null) { unsetPort(); } else { setPort((Integer)value); } break; case SSL_PORT: if (value == null) { unsetSslPort(); } else { setSslPort((Integer)value); } break; case PAYLOAD: if (value == null) { unsetPayload(); } else { setPayload((ByteBuffer)value); } break; case REGISTRATION_TIME_UTC: if (value == null) { unsetRegistrationTimeUTC(); } else { setRegistrationTimeUTC((Long)value); } break; case SERVICE_TYPE: if (value == null) { unsetServiceType(); } else { setServiceType((DiscoveryInstanceType)value); } break; case URI_SPEC: if (value == null) { unsetUriSpec(); } else { setUriSpec((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case NAME: return getName(); case ID: return getId(); case ADDRESS: return getAddress(); case PORT: return Integer.valueOf(getPort()); case SSL_PORT: return Integer.valueOf(getSslPort()); case PAYLOAD: return getPayload(); case REGISTRATION_TIME_UTC: return Long.valueOf(getRegistrationTimeUTC()); case SERVICE_TYPE: return getServiceType(); case URI_SPEC: return getUriSpec(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case NAME: return isSetName(); case ID: return isSetId(); case ADDRESS: return isSetAddress(); case PORT: return isSetPort(); case SSL_PORT: return isSetSslPort(); case PAYLOAD: return isSetPayload(); case REGISTRATION_TIME_UTC: return isSetRegistrationTimeUTC(); case SERVICE_TYPE: return isSetServiceType(); case URI_SPEC: return isSetUriSpec(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof DiscoveryInstance) return this.equals((DiscoveryInstance)that); return false; } public boolean equals(DiscoveryInstance that) { if (that == null) return false; boolean this_present_name = true && this.isSetName(); boolean that_present_name = true && that.isSetName(); if (this_present_name || that_present_name) { if (!(this_present_name && that_present_name)) return false; if (!this.name.equals(that.name)) return false; } boolean this_present_id = true && this.isSetId(); boolean that_present_id = true && that.isSetId(); if (this_present_id || that_present_id) { if (!(this_present_id && that_present_id)) return false; if (!this.id.equals(that.id)) return false; } boolean this_present_address = true && this.isSetAddress(); boolean that_present_address = true && that.isSetAddress(); if (this_present_address || that_present_address) { if (!(this_present_address && that_present_address)) return false; if (!this.address.equals(that.address)) return false; } boolean this_present_port = true; boolean that_present_port = true; if (this_present_port || that_present_port) { if (!(this_present_port && that_present_port)) return false; if (this.port != that.port) return false; } boolean this_present_sslPort = true; boolean that_present_sslPort = true; if (this_present_sslPort || that_present_sslPort) { if (!(this_present_sslPort && that_present_sslPort)) return false; if (this.sslPort != that.sslPort) return false; } boolean this_present_payload = true && this.isSetPayload(); boolean that_present_payload = true && that.isSetPayload(); if (this_present_payload || that_present_payload) { if (!(this_present_payload && that_present_payload)) return false; if (!this.payload.equals(that.payload)) return false; } boolean this_present_registrationTimeUTC = true; boolean that_present_registrationTimeUTC = true; if (this_present_registrationTimeUTC || that_present_registrationTimeUTC) { if (!(this_present_registrationTimeUTC && that_present_registrationTimeUTC)) return false; if (this.registrationTimeUTC != that.registrationTimeUTC) return false; } boolean this_present_serviceType = true && this.isSetServiceType(); boolean that_present_serviceType = true && that.isSetServiceType(); if (this_present_serviceType || that_present_serviceType) { if (!(this_present_serviceType && that_present_serviceType)) return false; if (!this.serviceType.equals(that.serviceType)) return false; } boolean this_present_uriSpec = true && this.isSetUriSpec(); boolean that_present_uriSpec = true && that.isSetUriSpec(); if (this_present_uriSpec || that_present_uriSpec) { if (!(this_present_uriSpec && that_present_uriSpec)) return false; if (!this.uriSpec.equals(that.uriSpec)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(DiscoveryInstance other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetName()).compareTo(other.isSetName()); if (lastComparison != 0) { return lastComparison; } if (isSetName()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); if (lastComparison != 0) { return lastComparison; } if (isSetId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetAddress()).compareTo(other.isSetAddress()); if (lastComparison != 0) { return lastComparison; } if (isSetAddress()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.address, other.address); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPort()).compareTo(other.isSetPort()); if (lastComparison != 0) { return lastComparison; } if (isSetPort()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.port, other.port); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetSslPort()).compareTo(other.isSetSslPort()); if (lastComparison != 0) { return lastComparison; } if (isSetSslPort()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.sslPort, other.sslPort); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPayload()).compareTo(other.isSetPayload()); if (lastComparison != 0) { return lastComparison; } if (isSetPayload()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.payload, other.payload); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetRegistrationTimeUTC()).compareTo(other.isSetRegistrationTimeUTC()); if (lastComparison != 0) { return lastComparison; } if (isSetRegistrationTimeUTC()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.registrationTimeUTC, other.registrationTimeUTC); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetServiceType()).compareTo(other.isSetServiceType()); if (lastComparison != 0) { return lastComparison; } if (isSetServiceType()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.serviceType, other.serviceType); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetUriSpec()).compareTo(other.isSetUriSpec()); if (lastComparison != 0) { return lastComparison; } if (isSetUriSpec()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.uriSpec, other.uriSpec); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("DiscoveryInstance("); boolean first = true; sb.append("name:"); if (this.name == null) { sb.append("null"); } else { sb.append(this.name); } first = false; if (!first) sb.append(", "); sb.append("id:"); if (this.id == null) { sb.append("null"); } else { sb.append(this.id); } first = false; if (!first) sb.append(", "); sb.append("address:"); if (this.address == null) { sb.append("null"); } else { sb.append(this.address); } first = false; if (!first) sb.append(", "); sb.append("port:"); sb.append(this.port); first = false; if (!first) sb.append(", "); sb.append("sslPort:"); sb.append(this.sslPort); first = false; if (!first) sb.append(", "); sb.append("payload:"); if (this.payload == null) { sb.append("null"); } else { org.apache.thrift.TBaseHelper.toString(this.payload, sb); } first = false; if (!first) sb.append(", "); sb.append("registrationTimeUTC:"); sb.append(this.registrationTimeUTC); first = false; if (!first) sb.append(", "); sb.append("serviceType:"); if (this.serviceType == null) { sb.append("null"); } else { sb.append(this.serviceType); } first = false; if (!first) sb.append(", "); sb.append("uriSpec:"); if (this.uriSpec == null) { sb.append("null"); } else { sb.append(this.uriSpec); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class DiscoveryInstanceStandardSchemeFactory implements SchemeFactory { public DiscoveryInstanceStandardScheme getScheme() { return new DiscoveryInstanceStandardScheme(); } } private static class DiscoveryInstanceStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, DiscoveryInstance struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.name = iprot.readString(); struct.setNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.id = iprot.readString(); struct.setIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // ADDRESS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.address = iprot.readString(); struct.setAddressIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // PORT if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.port = iprot.readI32(); struct.setPortIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // SSL_PORT if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.sslPort = iprot.readI32(); struct.setSslPortIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // PAYLOAD if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.payload = iprot.readBinary(); struct.setPayloadIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 7: // REGISTRATION_TIME_UTC if (schemeField.type == org.apache.thrift.protocol.TType.I64) { struct.registrationTimeUTC = iprot.readI64(); struct.setRegistrationTimeUTCIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 8: // SERVICE_TYPE if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.serviceType = DiscoveryInstanceType.findByValue(iprot.readI32()); struct.setServiceTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 9: // URI_SPEC if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.uriSpec = iprot.readString(); struct.setUriSpecIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, DiscoveryInstance struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.name != null) { oprot.writeFieldBegin(NAME_FIELD_DESC); oprot.writeString(struct.name); oprot.writeFieldEnd(); } if (struct.id != null) { oprot.writeFieldBegin(ID_FIELD_DESC); oprot.writeString(struct.id); oprot.writeFieldEnd(); } if (struct.address != null) { oprot.writeFieldBegin(ADDRESS_FIELD_DESC); oprot.writeString(struct.address); oprot.writeFieldEnd(); } oprot.writeFieldBegin(PORT_FIELD_DESC); oprot.writeI32(struct.port); oprot.writeFieldEnd(); oprot.writeFieldBegin(SSL_PORT_FIELD_DESC); oprot.writeI32(struct.sslPort); oprot.writeFieldEnd(); if (struct.payload != null) { oprot.writeFieldBegin(PAYLOAD_FIELD_DESC); oprot.writeBinary(struct.payload); oprot.writeFieldEnd(); } oprot.writeFieldBegin(REGISTRATION_TIME_UTC_FIELD_DESC); oprot.writeI64(struct.registrationTimeUTC); oprot.writeFieldEnd(); if (struct.serviceType != null) { oprot.writeFieldBegin(SERVICE_TYPE_FIELD_DESC); oprot.writeI32(struct.serviceType.getValue()); oprot.writeFieldEnd(); } if (struct.uriSpec != null) { oprot.writeFieldBegin(URI_SPEC_FIELD_DESC); oprot.writeString(struct.uriSpec); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class DiscoveryInstanceTupleSchemeFactory implements SchemeFactory { public DiscoveryInstanceTupleScheme getScheme() { return new DiscoveryInstanceTupleScheme(); } } private static class DiscoveryInstanceTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, DiscoveryInstance struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetName()) { optionals.set(0); } if (struct.isSetId()) { optionals.set(1); } if (struct.isSetAddress()) { optionals.set(2); } if (struct.isSetPort()) { optionals.set(3); } if (struct.isSetSslPort()) { optionals.set(4); } if (struct.isSetPayload()) { optionals.set(5); } if (struct.isSetRegistrationTimeUTC()) { optionals.set(6); } if (struct.isSetServiceType()) { optionals.set(7); } if (struct.isSetUriSpec()) { optionals.set(8); } oprot.writeBitSet(optionals, 9); if (struct.isSetName()) { oprot.writeString(struct.name); } if (struct.isSetId()) { oprot.writeString(struct.id); } if (struct.isSetAddress()) { oprot.writeString(struct.address); } if (struct.isSetPort()) { oprot.writeI32(struct.port); } if (struct.isSetSslPort()) { oprot.writeI32(struct.sslPort); } if (struct.isSetPayload()) { oprot.writeBinary(struct.payload); } if (struct.isSetRegistrationTimeUTC()) { oprot.writeI64(struct.registrationTimeUTC); } if (struct.isSetServiceType()) { oprot.writeI32(struct.serviceType.getValue()); } if (struct.isSetUriSpec()) { oprot.writeString(struct.uriSpec); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, DiscoveryInstance struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(9); if (incoming.get(0)) { struct.name = iprot.readString(); struct.setNameIsSet(true); } if (incoming.get(1)) { struct.id = iprot.readString(); struct.setIdIsSet(true); } if (incoming.get(2)) { struct.address = iprot.readString(); struct.setAddressIsSet(true); } if (incoming.get(3)) { struct.port = iprot.readI32(); struct.setPortIsSet(true); } if (incoming.get(4)) { struct.sslPort = iprot.readI32(); struct.setSslPortIsSet(true); } if (incoming.get(5)) { struct.payload = iprot.readBinary(); struct.setPayloadIsSet(true); } if (incoming.get(6)) { struct.registrationTimeUTC = iprot.readI64(); struct.setRegistrationTimeUTCIsSet(true); } if (incoming.get(7)) { struct.serviceType = DiscoveryInstanceType.findByValue(iprot.readI32()); struct.setServiceTypeIsSet(true); } if (incoming.get(8)) { struct.uriSpec = iprot.readString(); struct.setUriSpecIsSet(true); } } } } DiscoveryInstanceType.java000066400000000000000000000017451245521677600360260ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import java.util.Map; import java.util.HashMap; import org.apache.thrift.TEnum; public enum DiscoveryInstanceType implements org.apache.thrift.TEnum { DYNAMIC(0), STATIC(1), PERMANENT(2); private final int value; private DiscoveryInstanceType(int value) { this.value = value; } /** * Get the integer value of this enum value, as defined in the Thrift IDL. */ public int getValue() { return value; } /** * Find a the enum type by its integer value, as defined in the Thrift IDL. * @return null if the value is not found. */ public static DiscoveryInstanceType findByValue(int value) { switch (value) { case 0: return DYNAMIC; case 1: return STATIC; case 2: return PERMANENT; default: return null; } } } DiscoveryProjection.java000066400000000000000000000262071245521677600355340ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DiscoveryProjection implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("DiscoveryProjection"); private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.STRING, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new DiscoveryProjectionStandardSchemeFactory()); schemes.put(TupleScheme.class, new DiscoveryProjectionTupleSchemeFactory()); } public String id; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ID((short)1, "id"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // ID return ID; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(DiscoveryProjection.class, metaDataMap); } public DiscoveryProjection() { } public DiscoveryProjection( String id) { this(); this.id = id; } /** * Performs a deep copy on other. */ public DiscoveryProjection(DiscoveryProjection other) { if (other.isSetId()) { this.id = other.id; } } public DiscoveryProjection deepCopy() { return new DiscoveryProjection(this); } @Override public void clear() { this.id = null; } public String getId() { return this.id; } public DiscoveryProjection setId(String id) { this.id = id; return this; } public void unsetId() { this.id = null; } /** Returns true if field id is set (has been assigned a value) and false otherwise */ public boolean isSetId() { return this.id != null; } public void setIdIsSet(boolean value) { if (!value) { this.id = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case ID: if (value == null) { unsetId(); } else { setId((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case ID: return getId(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case ID: return isSetId(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof DiscoveryProjection) return this.equals((DiscoveryProjection)that); return false; } public boolean equals(DiscoveryProjection that) { if (that == null) return false; boolean this_present_id = true && this.isSetId(); boolean that_present_id = true && that.isSetId(); if (this_present_id || that_present_id) { if (!(this_present_id && that_present_id)) return false; if (!this.id.equals(that.id)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(DiscoveryProjection other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); if (lastComparison != 0) { return lastComparison; } if (isSetId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("DiscoveryProjection("); boolean first = true; sb.append("id:"); if (this.id == null) { sb.append("null"); } else { sb.append(this.id); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class DiscoveryProjectionStandardSchemeFactory implements SchemeFactory { public DiscoveryProjectionStandardScheme getScheme() { return new DiscoveryProjectionStandardScheme(); } } private static class DiscoveryProjectionStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, DiscoveryProjection struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.id = iprot.readString(); struct.setIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, DiscoveryProjection struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.id != null) { oprot.writeFieldBegin(ID_FIELD_DESC); oprot.writeString(struct.id); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class DiscoveryProjectionTupleSchemeFactory implements SchemeFactory { public DiscoveryProjectionTupleScheme getScheme() { return new DiscoveryProjectionTupleScheme(); } } private static class DiscoveryProjectionTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, DiscoveryProjection struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetId()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetId()) { oprot.writeString(struct.id); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, DiscoveryProjection struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.id = iprot.readString(); struct.setIdIsSet(true); } } } } DiscoveryProviderProjection.java000066400000000000000000000266271245521677600372550ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DiscoveryProviderProjection implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("DiscoveryProviderProjection"); private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.STRING, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new DiscoveryProviderProjectionStandardSchemeFactory()); schemes.put(TupleScheme.class, new DiscoveryProviderProjectionTupleSchemeFactory()); } public String id; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ID((short)1, "id"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // ID return ID; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(DiscoveryProviderProjection.class, metaDataMap); } public DiscoveryProviderProjection() { } public DiscoveryProviderProjection( String id) { this(); this.id = id; } /** * Performs a deep copy on other. */ public DiscoveryProviderProjection(DiscoveryProviderProjection other) { if (other.isSetId()) { this.id = other.id; } } public DiscoveryProviderProjection deepCopy() { return new DiscoveryProviderProjection(this); } @Override public void clear() { this.id = null; } public String getId() { return this.id; } public DiscoveryProviderProjection setId(String id) { this.id = id; return this; } public void unsetId() { this.id = null; } /** Returns true if field id is set (has been assigned a value) and false otherwise */ public boolean isSetId() { return this.id != null; } public void setIdIsSet(boolean value) { if (!value) { this.id = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case ID: if (value == null) { unsetId(); } else { setId((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case ID: return getId(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case ID: return isSetId(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof DiscoveryProviderProjection) return this.equals((DiscoveryProviderProjection)that); return false; } public boolean equals(DiscoveryProviderProjection that) { if (that == null) return false; boolean this_present_id = true && this.isSetId(); boolean that_present_id = true && that.isSetId(); if (this_present_id || that_present_id) { if (!(this_present_id && that_present_id)) return false; if (!this.id.equals(that.id)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(DiscoveryProviderProjection other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); if (lastComparison != 0) { return lastComparison; } if (isSetId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("DiscoveryProviderProjection("); boolean first = true; sb.append("id:"); if (this.id == null) { sb.append("null"); } else { sb.append(this.id); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class DiscoveryProviderProjectionStandardSchemeFactory implements SchemeFactory { public DiscoveryProviderProjectionStandardScheme getScheme() { return new DiscoveryProviderProjectionStandardScheme(); } } private static class DiscoveryProviderProjectionStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, DiscoveryProviderProjection struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.id = iprot.readString(); struct.setIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, DiscoveryProviderProjection struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.id != null) { oprot.writeFieldBegin(ID_FIELD_DESC); oprot.writeString(struct.id); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class DiscoveryProviderProjectionTupleSchemeFactory implements SchemeFactory { public DiscoveryProviderProjectionTupleScheme getScheme() { return new DiscoveryProviderProjectionTupleScheme(); } } private static class DiscoveryProviderProjectionTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, DiscoveryProviderProjection struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetId()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetId()) { oprot.writeString(struct.id); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, DiscoveryProviderProjection struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.id = iprot.readString(); struct.setIdIsSet(true); } } } } DiscoveryService.java000066400000000000000000007660451245521677600350330ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DiscoveryService { public interface Iface { public List getAllInstances(CuratorProjection projection, DiscoveryProviderProjection providerProjection) throws CuratorException, org.apache.thrift.TException; public DiscoveryInstance getInstance(CuratorProjection projection, DiscoveryProviderProjection providerProjection) throws CuratorException, org.apache.thrift.TException; public DiscoveryInstance makeDiscoveryInstance(String name, ByteBuffer payload, int port) throws CuratorException, org.apache.thrift.TException; public void noteError(CuratorProjection projection, DiscoveryProviderProjection providerProjection, String instanceId) throws CuratorException, org.apache.thrift.TException; public DiscoveryProjection startDiscovery(CuratorProjection projection, String basePath, DiscoveryInstance yourInstance) throws CuratorException, org.apache.thrift.TException; public DiscoveryProviderProjection startProvider(CuratorProjection projection, DiscoveryProjection discoveryProjection, String serviceName, ProviderStrategyType providerStrategy, int downTimeoutMs, int downErrorThreshold) throws CuratorException, org.apache.thrift.TException; } public interface AsyncIface { public void getAllInstances(CuratorProjection projection, DiscoveryProviderProjection providerProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void getInstance(CuratorProjection projection, DiscoveryProviderProjection providerProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void makeDiscoveryInstance(String name, ByteBuffer payload, int port, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void noteError(CuratorProjection projection, DiscoveryProviderProjection providerProjection, String instanceId, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void startDiscovery(CuratorProjection projection, String basePath, DiscoveryInstance yourInstance, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void startProvider(CuratorProjection projection, DiscoveryProjection discoveryProjection, String serviceName, ProviderStrategyType providerStrategy, int downTimeoutMs, int downErrorThreshold, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; } public static class Client extends org.apache.thrift.TServiceClient implements Iface { public static class Factory implements org.apache.thrift.TServiceClientFactory { public Factory() {} public Client getClient(org.apache.thrift.protocol.TProtocol prot) { return new Client(prot); } public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { return new Client(iprot, oprot); } } public Client(org.apache.thrift.protocol.TProtocol prot) { super(prot, prot); } public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { super(iprot, oprot); } public List getAllInstances(CuratorProjection projection, DiscoveryProviderProjection providerProjection) throws CuratorException, org.apache.thrift.TException { send_getAllInstances(projection, providerProjection); return recv_getAllInstances(); } public void send_getAllInstances(CuratorProjection projection, DiscoveryProviderProjection providerProjection) throws org.apache.thrift.TException { getAllInstances_args args = new getAllInstances_args(); args.setProjection(projection); args.setProviderProjection(providerProjection); sendBase("getAllInstances", args); } public List recv_getAllInstances() throws CuratorException, org.apache.thrift.TException { getAllInstances_result result = new getAllInstances_result(); receiveBase(result, "getAllInstances"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getAllInstances failed: unknown result"); } public DiscoveryInstance getInstance(CuratorProjection projection, DiscoveryProviderProjection providerProjection) throws CuratorException, org.apache.thrift.TException { send_getInstance(projection, providerProjection); return recv_getInstance(); } public void send_getInstance(CuratorProjection projection, DiscoveryProviderProjection providerProjection) throws org.apache.thrift.TException { getInstance_args args = new getInstance_args(); args.setProjection(projection); args.setProviderProjection(providerProjection); sendBase("getInstance", args); } public DiscoveryInstance recv_getInstance() throws CuratorException, org.apache.thrift.TException { getInstance_result result = new getInstance_result(); receiveBase(result, "getInstance"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getInstance failed: unknown result"); } public DiscoveryInstance makeDiscoveryInstance(String name, ByteBuffer payload, int port) throws CuratorException, org.apache.thrift.TException { send_makeDiscoveryInstance(name, payload, port); return recv_makeDiscoveryInstance(); } public void send_makeDiscoveryInstance(String name, ByteBuffer payload, int port) throws org.apache.thrift.TException { makeDiscoveryInstance_args args = new makeDiscoveryInstance_args(); args.setName(name); args.setPayload(payload); args.setPort(port); sendBase("makeDiscoveryInstance", args); } public DiscoveryInstance recv_makeDiscoveryInstance() throws CuratorException, org.apache.thrift.TException { makeDiscoveryInstance_result result = new makeDiscoveryInstance_result(); receiveBase(result, "makeDiscoveryInstance"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "makeDiscoveryInstance failed: unknown result"); } public void noteError(CuratorProjection projection, DiscoveryProviderProjection providerProjection, String instanceId) throws CuratorException, org.apache.thrift.TException { send_noteError(projection, providerProjection, instanceId); recv_noteError(); } public void send_noteError(CuratorProjection projection, DiscoveryProviderProjection providerProjection, String instanceId) throws org.apache.thrift.TException { noteError_args args = new noteError_args(); args.setProjection(projection); args.setProviderProjection(providerProjection); args.setInstanceId(instanceId); sendBase("noteError", args); } public void recv_noteError() throws CuratorException, org.apache.thrift.TException { noteError_result result = new noteError_result(); receiveBase(result, "noteError"); if (result.ex1 != null) { throw result.ex1; } return; } public DiscoveryProjection startDiscovery(CuratorProjection projection, String basePath, DiscoveryInstance yourInstance) throws CuratorException, org.apache.thrift.TException { send_startDiscovery(projection, basePath, yourInstance); return recv_startDiscovery(); } public void send_startDiscovery(CuratorProjection projection, String basePath, DiscoveryInstance yourInstance) throws org.apache.thrift.TException { startDiscovery_args args = new startDiscovery_args(); args.setProjection(projection); args.setBasePath(basePath); args.setYourInstance(yourInstance); sendBase("startDiscovery", args); } public DiscoveryProjection recv_startDiscovery() throws CuratorException, org.apache.thrift.TException { startDiscovery_result result = new startDiscovery_result(); receiveBase(result, "startDiscovery"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "startDiscovery failed: unknown result"); } public DiscoveryProviderProjection startProvider(CuratorProjection projection, DiscoveryProjection discoveryProjection, String serviceName, ProviderStrategyType providerStrategy, int downTimeoutMs, int downErrorThreshold) throws CuratorException, org.apache.thrift.TException { send_startProvider(projection, discoveryProjection, serviceName, providerStrategy, downTimeoutMs, downErrorThreshold); return recv_startProvider(); } public void send_startProvider(CuratorProjection projection, DiscoveryProjection discoveryProjection, String serviceName, ProviderStrategyType providerStrategy, int downTimeoutMs, int downErrorThreshold) throws org.apache.thrift.TException { startProvider_args args = new startProvider_args(); args.setProjection(projection); args.setDiscoveryProjection(discoveryProjection); args.setServiceName(serviceName); args.setProviderStrategy(providerStrategy); args.setDownTimeoutMs(downTimeoutMs); args.setDownErrorThreshold(downErrorThreshold); sendBase("startProvider", args); } public DiscoveryProviderProjection recv_startProvider() throws CuratorException, org.apache.thrift.TException { startProvider_result result = new startProvider_result(); receiveBase(result, "startProvider"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "startProvider failed: unknown result"); } } public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface { public static class Factory implements org.apache.thrift.async.TAsyncClientFactory { private org.apache.thrift.async.TAsyncClientManager clientManager; private org.apache.thrift.protocol.TProtocolFactory protocolFactory; public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) { this.clientManager = clientManager; this.protocolFactory = protocolFactory; } public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) { return new AsyncClient(protocolFactory, clientManager, transport); } } public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) { super(protocolFactory, clientManager, transport); } public void getAllInstances(CuratorProjection projection, DiscoveryProviderProjection providerProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); getAllInstances_call method_call = new getAllInstances_call(projection, providerProjection, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class getAllInstances_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private DiscoveryProviderProjection providerProjection; public getAllInstances_call(CuratorProjection projection, DiscoveryProviderProjection providerProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.providerProjection = providerProjection; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getAllInstances", org.apache.thrift.protocol.TMessageType.CALL, 0)); getAllInstances_args args = new getAllInstances_args(); args.setProjection(projection); args.setProviderProjection(providerProjection); args.write(prot); prot.writeMessageEnd(); } public List getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_getAllInstances(); } } public void getInstance(CuratorProjection projection, DiscoveryProviderProjection providerProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); getInstance_call method_call = new getInstance_call(projection, providerProjection, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class getInstance_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private DiscoveryProviderProjection providerProjection; public getInstance_call(CuratorProjection projection, DiscoveryProviderProjection providerProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.providerProjection = providerProjection; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getInstance", org.apache.thrift.protocol.TMessageType.CALL, 0)); getInstance_args args = new getInstance_args(); args.setProjection(projection); args.setProviderProjection(providerProjection); args.write(prot); prot.writeMessageEnd(); } public DiscoveryInstance getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_getInstance(); } } public void makeDiscoveryInstance(String name, ByteBuffer payload, int port, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); makeDiscoveryInstance_call method_call = new makeDiscoveryInstance_call(name, payload, port, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class makeDiscoveryInstance_call extends org.apache.thrift.async.TAsyncMethodCall { private String name; private ByteBuffer payload; private int port; public makeDiscoveryInstance_call(String name, ByteBuffer payload, int port, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.name = name; this.payload = payload; this.port = port; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("makeDiscoveryInstance", org.apache.thrift.protocol.TMessageType.CALL, 0)); makeDiscoveryInstance_args args = new makeDiscoveryInstance_args(); args.setName(name); args.setPayload(payload); args.setPort(port); args.write(prot); prot.writeMessageEnd(); } public DiscoveryInstance getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_makeDiscoveryInstance(); } } public void noteError(CuratorProjection projection, DiscoveryProviderProjection providerProjection, String instanceId, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); noteError_call method_call = new noteError_call(projection, providerProjection, instanceId, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class noteError_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private DiscoveryProviderProjection providerProjection; private String instanceId; public noteError_call(CuratorProjection projection, DiscoveryProviderProjection providerProjection, String instanceId, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.providerProjection = providerProjection; this.instanceId = instanceId; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("noteError", org.apache.thrift.protocol.TMessageType.CALL, 0)); noteError_args args = new noteError_args(); args.setProjection(projection); args.setProviderProjection(providerProjection); args.setInstanceId(instanceId); args.write(prot); prot.writeMessageEnd(); } public void getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); (new Client(prot)).recv_noteError(); } } public void startDiscovery(CuratorProjection projection, String basePath, DiscoveryInstance yourInstance, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); startDiscovery_call method_call = new startDiscovery_call(projection, basePath, yourInstance, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class startDiscovery_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private String basePath; private DiscoveryInstance yourInstance; public startDiscovery_call(CuratorProjection projection, String basePath, DiscoveryInstance yourInstance, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.basePath = basePath; this.yourInstance = yourInstance; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("startDiscovery", org.apache.thrift.protocol.TMessageType.CALL, 0)); startDiscovery_args args = new startDiscovery_args(); args.setProjection(projection); args.setBasePath(basePath); args.setYourInstance(yourInstance); args.write(prot); prot.writeMessageEnd(); } public DiscoveryProjection getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_startDiscovery(); } } public void startProvider(CuratorProjection projection, DiscoveryProjection discoveryProjection, String serviceName, ProviderStrategyType providerStrategy, int downTimeoutMs, int downErrorThreshold, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); startProvider_call method_call = new startProvider_call(projection, discoveryProjection, serviceName, providerStrategy, downTimeoutMs, downErrorThreshold, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class startProvider_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private DiscoveryProjection discoveryProjection; private String serviceName; private ProviderStrategyType providerStrategy; private int downTimeoutMs; private int downErrorThreshold; public startProvider_call(CuratorProjection projection, DiscoveryProjection discoveryProjection, String serviceName, ProviderStrategyType providerStrategy, int downTimeoutMs, int downErrorThreshold, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.discoveryProjection = discoveryProjection; this.serviceName = serviceName; this.providerStrategy = providerStrategy; this.downTimeoutMs = downTimeoutMs; this.downErrorThreshold = downErrorThreshold; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("startProvider", org.apache.thrift.protocol.TMessageType.CALL, 0)); startProvider_args args = new startProvider_args(); args.setProjection(projection); args.setDiscoveryProjection(discoveryProjection); args.setServiceName(serviceName); args.setProviderStrategy(providerStrategy); args.setDownTimeoutMs(downTimeoutMs); args.setDownErrorThreshold(downErrorThreshold); args.write(prot); prot.writeMessageEnd(); } public DiscoveryProviderProjection getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_startProvider(); } } } public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName()); public Processor(I iface) { super(iface, getProcessMap(new HashMap>())); } protected Processor(I iface, Map> processMap) { super(iface, getProcessMap(processMap)); } private static Map> getProcessMap(Map> processMap) { processMap.put("getAllInstances", new getAllInstances()); processMap.put("getInstance", new getInstance()); processMap.put("makeDiscoveryInstance", new makeDiscoveryInstance()); processMap.put("noteError", new noteError()); processMap.put("startDiscovery", new startDiscovery()); processMap.put("startProvider", new startProvider()); return processMap; } public static class getAllInstances extends org.apache.thrift.ProcessFunction { public getAllInstances() { super("getAllInstances"); } public getAllInstances_args getEmptyArgsInstance() { return new getAllInstances_args(); } protected boolean isOneway() { return false; } public getAllInstances_result getResult(I iface, getAllInstances_args args) throws org.apache.thrift.TException { getAllInstances_result result = new getAllInstances_result(); try { result.success = iface.getAllInstances(args.projection, args.providerProjection); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class getInstance extends org.apache.thrift.ProcessFunction { public getInstance() { super("getInstance"); } public getInstance_args getEmptyArgsInstance() { return new getInstance_args(); } protected boolean isOneway() { return false; } public getInstance_result getResult(I iface, getInstance_args args) throws org.apache.thrift.TException { getInstance_result result = new getInstance_result(); try { result.success = iface.getInstance(args.projection, args.providerProjection); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class makeDiscoveryInstance extends org.apache.thrift.ProcessFunction { public makeDiscoveryInstance() { super("makeDiscoveryInstance"); } public makeDiscoveryInstance_args getEmptyArgsInstance() { return new makeDiscoveryInstance_args(); } protected boolean isOneway() { return false; } public makeDiscoveryInstance_result getResult(I iface, makeDiscoveryInstance_args args) throws org.apache.thrift.TException { makeDiscoveryInstance_result result = new makeDiscoveryInstance_result(); try { result.success = iface.makeDiscoveryInstance(args.name, args.payload, args.port); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class noteError extends org.apache.thrift.ProcessFunction { public noteError() { super("noteError"); } public noteError_args getEmptyArgsInstance() { return new noteError_args(); } protected boolean isOneway() { return false; } public noteError_result getResult(I iface, noteError_args args) throws org.apache.thrift.TException { noteError_result result = new noteError_result(); try { iface.noteError(args.projection, args.providerProjection, args.instanceId); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class startDiscovery extends org.apache.thrift.ProcessFunction { public startDiscovery() { super("startDiscovery"); } public startDiscovery_args getEmptyArgsInstance() { return new startDiscovery_args(); } protected boolean isOneway() { return false; } public startDiscovery_result getResult(I iface, startDiscovery_args args) throws org.apache.thrift.TException { startDiscovery_result result = new startDiscovery_result(); try { result.success = iface.startDiscovery(args.projection, args.basePath, args.yourInstance); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class startProvider extends org.apache.thrift.ProcessFunction { public startProvider() { super("startProvider"); } public startProvider_args getEmptyArgsInstance() { return new startProvider_args(); } protected boolean isOneway() { return false; } public startProvider_result getResult(I iface, startProvider_args args) throws org.apache.thrift.TException { startProvider_result result = new startProvider_result(); try { result.success = iface.startProvider(args.projection, args.discoveryProjection, args.serviceName, args.providerStrategy, args.downTimeoutMs, args.downErrorThreshold); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } } public static class AsyncProcessor extends org.apache.thrift.TBaseAsyncProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName()); public AsyncProcessor(I iface) { super(iface, getProcessMap(new HashMap>())); } protected AsyncProcessor(I iface, Map> processMap) { super(iface, getProcessMap(processMap)); } private static Map> getProcessMap(Map> processMap) { processMap.put("getAllInstances", new getAllInstances()); processMap.put("getInstance", new getInstance()); processMap.put("makeDiscoveryInstance", new makeDiscoveryInstance()); processMap.put("noteError", new noteError()); processMap.put("startDiscovery", new startDiscovery()); processMap.put("startProvider", new startProvider()); return processMap; } public static class getAllInstances extends org.apache.thrift.AsyncProcessFunction> { public getAllInstances() { super("getAllInstances"); } public getAllInstances_args getEmptyArgsInstance() { return new getAllInstances_args(); } public AsyncMethodCallback> getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback>() { public void onComplete(List o) { getAllInstances_result result = new getAllInstances_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; getAllInstances_result result = new getAllInstances_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, getAllInstances_args args, org.apache.thrift.async.AsyncMethodCallback> resultHandler) throws TException { iface.getAllInstances(args.projection, args.providerProjection,resultHandler); } } public static class getInstance extends org.apache.thrift.AsyncProcessFunction { public getInstance() { super("getInstance"); } public getInstance_args getEmptyArgsInstance() { return new getInstance_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(DiscoveryInstance o) { getInstance_result result = new getInstance_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; getInstance_result result = new getInstance_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, getInstance_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.getInstance(args.projection, args.providerProjection,resultHandler); } } public static class makeDiscoveryInstance extends org.apache.thrift.AsyncProcessFunction { public makeDiscoveryInstance() { super("makeDiscoveryInstance"); } public makeDiscoveryInstance_args getEmptyArgsInstance() { return new makeDiscoveryInstance_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(DiscoveryInstance o) { makeDiscoveryInstance_result result = new makeDiscoveryInstance_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; makeDiscoveryInstance_result result = new makeDiscoveryInstance_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, makeDiscoveryInstance_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.makeDiscoveryInstance(args.name, args.payload, args.port,resultHandler); } } public static class noteError extends org.apache.thrift.AsyncProcessFunction { public noteError() { super("noteError"); } public noteError_args getEmptyArgsInstance() { return new noteError_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(Void o) { noteError_result result = new noteError_result(); try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; noteError_result result = new noteError_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, noteError_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.noteError(args.projection, args.providerProjection, args.instanceId,resultHandler); } } public static class startDiscovery extends org.apache.thrift.AsyncProcessFunction { public startDiscovery() { super("startDiscovery"); } public startDiscovery_args getEmptyArgsInstance() { return new startDiscovery_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(DiscoveryProjection o) { startDiscovery_result result = new startDiscovery_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; startDiscovery_result result = new startDiscovery_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, startDiscovery_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.startDiscovery(args.projection, args.basePath, args.yourInstance,resultHandler); } } public static class startProvider extends org.apache.thrift.AsyncProcessFunction { public startProvider() { super("startProvider"); } public startProvider_args getEmptyArgsInstance() { return new startProvider_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(DiscoveryProviderProjection o) { startProvider_result result = new startProvider_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; startProvider_result result = new startProvider_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, startProvider_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.startProvider(args.projection, args.discoveryProjection, args.serviceName, args.providerStrategy, args.downTimeoutMs, args.downErrorThreshold,resultHandler); } } } public static class getAllInstances_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getAllInstances_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField PROVIDER_PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("providerProjection", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getAllInstances_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new getAllInstances_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public DiscoveryProviderProjection providerProjection; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), PROVIDER_PROJECTION((short)2, "providerProjection"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // PROVIDER_PROJECTION return PROVIDER_PROJECTION; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.PROVIDER_PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("providerProjection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryProviderProjection.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getAllInstances_args.class, metaDataMap); } public getAllInstances_args() { } public getAllInstances_args( CuratorProjection projection, DiscoveryProviderProjection providerProjection) { this(); this.projection = projection; this.providerProjection = providerProjection; } /** * Performs a deep copy on other. */ public getAllInstances_args(getAllInstances_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetProviderProjection()) { this.providerProjection = new DiscoveryProviderProjection(other.providerProjection); } } public getAllInstances_args deepCopy() { return new getAllInstances_args(this); } @Override public void clear() { this.projection = null; this.providerProjection = null; } public CuratorProjection getProjection() { return this.projection; } public getAllInstances_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public DiscoveryProviderProjection getProviderProjection() { return this.providerProjection; } public getAllInstances_args setProviderProjection(DiscoveryProviderProjection providerProjection) { this.providerProjection = providerProjection; return this; } public void unsetProviderProjection() { this.providerProjection = null; } /** Returns true if field providerProjection is set (has been assigned a value) and false otherwise */ public boolean isSetProviderProjection() { return this.providerProjection != null; } public void setProviderProjectionIsSet(boolean value) { if (!value) { this.providerProjection = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case PROVIDER_PROJECTION: if (value == null) { unsetProviderProjection(); } else { setProviderProjection((DiscoveryProviderProjection)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case PROVIDER_PROJECTION: return getProviderProjection(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case PROVIDER_PROJECTION: return isSetProviderProjection(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getAllInstances_args) return this.equals((getAllInstances_args)that); return false; } public boolean equals(getAllInstances_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_providerProjection = true && this.isSetProviderProjection(); boolean that_present_providerProjection = true && that.isSetProviderProjection(); if (this_present_providerProjection || that_present_providerProjection) { if (!(this_present_providerProjection && that_present_providerProjection)) return false; if (!this.providerProjection.equals(that.providerProjection)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getAllInstances_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetProviderProjection()).compareTo(other.isSetProviderProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProviderProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.providerProjection, other.providerProjection); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getAllInstances_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("providerProjection:"); if (this.providerProjection == null) { sb.append("null"); } else { sb.append(this.providerProjection); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (providerProjection != null) { providerProjection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getAllInstances_argsStandardSchemeFactory implements SchemeFactory { public getAllInstances_argsStandardScheme getScheme() { return new getAllInstances_argsStandardScheme(); } } private static class getAllInstances_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getAllInstances_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // PROVIDER_PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.providerProjection = new DiscoveryProviderProjection(); struct.providerProjection.read(iprot); struct.setProviderProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getAllInstances_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.providerProjection != null) { oprot.writeFieldBegin(PROVIDER_PROJECTION_FIELD_DESC); struct.providerProjection.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getAllInstances_argsTupleSchemeFactory implements SchemeFactory { public getAllInstances_argsTupleScheme getScheme() { return new getAllInstances_argsTupleScheme(); } } private static class getAllInstances_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getAllInstances_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetProviderProjection()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetProviderProjection()) { struct.providerProjection.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getAllInstances_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.providerProjection = new DiscoveryProviderProjection(); struct.providerProjection.read(iprot); struct.setProviderProjectionIsSet(true); } } } } public static class getAllInstances_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getAllInstances_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.LIST, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getAllInstances_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new getAllInstances_resultTupleSchemeFactory()); } public List success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryInstance.class)))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getAllInstances_result.class, metaDataMap); } public getAllInstances_result() { } public getAllInstances_result( List success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public getAllInstances_result(getAllInstances_result other) { if (other.isSetSuccess()) { List __this__success = new ArrayList(other.success.size()); for (DiscoveryInstance other_element : other.success) { __this__success.add(new DiscoveryInstance(other_element)); } this.success = __this__success; } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public getAllInstances_result deepCopy() { return new getAllInstances_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public int getSuccessSize() { return (this.success == null) ? 0 : this.success.size(); } public java.util.Iterator getSuccessIterator() { return (this.success == null) ? null : this.success.iterator(); } public void addToSuccess(DiscoveryInstance elem) { if (this.success == null) { this.success = new ArrayList(); } this.success.add(elem); } public List getSuccess() { return this.success; } public getAllInstances_result setSuccess(List success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public getAllInstances_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((List)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getAllInstances_result) return this.equals((getAllInstances_result)that); return false; } public boolean equals(getAllInstances_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getAllInstances_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getAllInstances_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getAllInstances_resultStandardSchemeFactory implements SchemeFactory { public getAllInstances_resultStandardScheme getScheme() { return new getAllInstances_resultStandardScheme(); } } private static class getAllInstances_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getAllInstances_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list48 = iprot.readListBegin(); struct.success = new ArrayList(_list48.size); for (int _i49 = 0; _i49 < _list48.size; ++_i49) { DiscoveryInstance _elem50; _elem50 = new DiscoveryInstance(); _elem50.read(iprot); struct.success.add(_elem50); } iprot.readListEnd(); } struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getAllInstances_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.success.size())); for (DiscoveryInstance _iter51 : struct.success) { _iter51.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getAllInstances_resultTupleSchemeFactory implements SchemeFactory { public getAllInstances_resultTupleScheme getScheme() { return new getAllInstances_resultTupleScheme(); } } private static class getAllInstances_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getAllInstances_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { { oprot.writeI32(struct.success.size()); for (DiscoveryInstance _iter52 : struct.success) { _iter52.write(oprot); } } } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getAllInstances_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { { org.apache.thrift.protocol.TList _list53 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.success = new ArrayList(_list53.size); for (int _i54 = 0; _i54 < _list53.size; ++_i54) { DiscoveryInstance _elem55; _elem55 = new DiscoveryInstance(); _elem55.read(iprot); struct.success.add(_elem55); } } struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class getInstance_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getInstance_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField PROVIDER_PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("providerProjection", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getInstance_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new getInstance_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public DiscoveryProviderProjection providerProjection; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), PROVIDER_PROJECTION((short)2, "providerProjection"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // PROVIDER_PROJECTION return PROVIDER_PROJECTION; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.PROVIDER_PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("providerProjection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryProviderProjection.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getInstance_args.class, metaDataMap); } public getInstance_args() { } public getInstance_args( CuratorProjection projection, DiscoveryProviderProjection providerProjection) { this(); this.projection = projection; this.providerProjection = providerProjection; } /** * Performs a deep copy on other. */ public getInstance_args(getInstance_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetProviderProjection()) { this.providerProjection = new DiscoveryProviderProjection(other.providerProjection); } } public getInstance_args deepCopy() { return new getInstance_args(this); } @Override public void clear() { this.projection = null; this.providerProjection = null; } public CuratorProjection getProjection() { return this.projection; } public getInstance_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public DiscoveryProviderProjection getProviderProjection() { return this.providerProjection; } public getInstance_args setProviderProjection(DiscoveryProviderProjection providerProjection) { this.providerProjection = providerProjection; return this; } public void unsetProviderProjection() { this.providerProjection = null; } /** Returns true if field providerProjection is set (has been assigned a value) and false otherwise */ public boolean isSetProviderProjection() { return this.providerProjection != null; } public void setProviderProjectionIsSet(boolean value) { if (!value) { this.providerProjection = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case PROVIDER_PROJECTION: if (value == null) { unsetProviderProjection(); } else { setProviderProjection((DiscoveryProviderProjection)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case PROVIDER_PROJECTION: return getProviderProjection(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case PROVIDER_PROJECTION: return isSetProviderProjection(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getInstance_args) return this.equals((getInstance_args)that); return false; } public boolean equals(getInstance_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_providerProjection = true && this.isSetProviderProjection(); boolean that_present_providerProjection = true && that.isSetProviderProjection(); if (this_present_providerProjection || that_present_providerProjection) { if (!(this_present_providerProjection && that_present_providerProjection)) return false; if (!this.providerProjection.equals(that.providerProjection)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getInstance_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetProviderProjection()).compareTo(other.isSetProviderProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProviderProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.providerProjection, other.providerProjection); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getInstance_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("providerProjection:"); if (this.providerProjection == null) { sb.append("null"); } else { sb.append(this.providerProjection); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (providerProjection != null) { providerProjection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getInstance_argsStandardSchemeFactory implements SchemeFactory { public getInstance_argsStandardScheme getScheme() { return new getInstance_argsStandardScheme(); } } private static class getInstance_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getInstance_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // PROVIDER_PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.providerProjection = new DiscoveryProviderProjection(); struct.providerProjection.read(iprot); struct.setProviderProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getInstance_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.providerProjection != null) { oprot.writeFieldBegin(PROVIDER_PROJECTION_FIELD_DESC); struct.providerProjection.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getInstance_argsTupleSchemeFactory implements SchemeFactory { public getInstance_argsTupleScheme getScheme() { return new getInstance_argsTupleScheme(); } } private static class getInstance_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getInstance_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetProviderProjection()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetProviderProjection()) { struct.providerProjection.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getInstance_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.providerProjection = new DiscoveryProviderProjection(); struct.providerProjection.read(iprot); struct.setProviderProjectionIsSet(true); } } } } public static class getInstance_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getInstance_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getInstance_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new getInstance_resultTupleSchemeFactory()); } public DiscoveryInstance success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryInstance.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getInstance_result.class, metaDataMap); } public getInstance_result() { } public getInstance_result( DiscoveryInstance success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public getInstance_result(getInstance_result other) { if (other.isSetSuccess()) { this.success = new DiscoveryInstance(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public getInstance_result deepCopy() { return new getInstance_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public DiscoveryInstance getSuccess() { return this.success; } public getInstance_result setSuccess(DiscoveryInstance success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public getInstance_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((DiscoveryInstance)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getInstance_result) return this.equals((getInstance_result)that); return false; } public boolean equals(getInstance_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getInstance_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getInstance_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getInstance_resultStandardSchemeFactory implements SchemeFactory { public getInstance_resultStandardScheme getScheme() { return new getInstance_resultStandardScheme(); } } private static class getInstance_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getInstance_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new DiscoveryInstance(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getInstance_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getInstance_resultTupleSchemeFactory implements SchemeFactory { public getInstance_resultTupleScheme getScheme() { return new getInstance_resultTupleScheme(); } } private static class getInstance_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getInstance_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getInstance_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new DiscoveryInstance(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class makeDiscoveryInstance_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("makeDiscoveryInstance_args"); private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField PAYLOAD_FIELD_DESC = new org.apache.thrift.protocol.TField("payload", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField PORT_FIELD_DESC = new org.apache.thrift.protocol.TField("port", org.apache.thrift.protocol.TType.I32, (short)3); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new makeDiscoveryInstance_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new makeDiscoveryInstance_argsTupleSchemeFactory()); } public String name; // required public ByteBuffer payload; // required public int port; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { NAME((short)1, "name"), PAYLOAD((short)2, "payload"), PORT((short)3, "port"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // NAME return NAME; case 2: // PAYLOAD return PAYLOAD; case 3: // PORT return PORT; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __PORT_ISSET_ID = 0; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.PAYLOAD, new org.apache.thrift.meta_data.FieldMetaData("payload", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true))); tmpMap.put(_Fields.PORT, new org.apache.thrift.meta_data.FieldMetaData("port", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(makeDiscoveryInstance_args.class, metaDataMap); } public makeDiscoveryInstance_args() { } public makeDiscoveryInstance_args( String name, ByteBuffer payload, int port) { this(); this.name = name; this.payload = payload; this.port = port; setPortIsSet(true); } /** * Performs a deep copy on other. */ public makeDiscoveryInstance_args(makeDiscoveryInstance_args other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetName()) { this.name = other.name; } if (other.isSetPayload()) { this.payload = org.apache.thrift.TBaseHelper.copyBinary(other.payload); ; } this.port = other.port; } public makeDiscoveryInstance_args deepCopy() { return new makeDiscoveryInstance_args(this); } @Override public void clear() { this.name = null; this.payload = null; setPortIsSet(false); this.port = 0; } public String getName() { return this.name; } public makeDiscoveryInstance_args setName(String name) { this.name = name; return this; } public void unsetName() { this.name = null; } /** Returns true if field name is set (has been assigned a value) and false otherwise */ public boolean isSetName() { return this.name != null; } public void setNameIsSet(boolean value) { if (!value) { this.name = null; } } public byte[] getPayload() { setPayload(org.apache.thrift.TBaseHelper.rightSize(payload)); return payload == null ? null : payload.array(); } public ByteBuffer bufferForPayload() { return payload; } public makeDiscoveryInstance_args setPayload(byte[] payload) { setPayload(payload == null ? (ByteBuffer)null : ByteBuffer.wrap(payload)); return this; } public makeDiscoveryInstance_args setPayload(ByteBuffer payload) { this.payload = payload; return this; } public void unsetPayload() { this.payload = null; } /** Returns true if field payload is set (has been assigned a value) and false otherwise */ public boolean isSetPayload() { return this.payload != null; } public void setPayloadIsSet(boolean value) { if (!value) { this.payload = null; } } public int getPort() { return this.port; } public makeDiscoveryInstance_args setPort(int port) { this.port = port; setPortIsSet(true); return this; } public void unsetPort() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __PORT_ISSET_ID); } /** Returns true if field port is set (has been assigned a value) and false otherwise */ public boolean isSetPort() { return EncodingUtils.testBit(__isset_bitfield, __PORT_ISSET_ID); } public void setPortIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __PORT_ISSET_ID, value); } public void setFieldValue(_Fields field, Object value) { switch (field) { case NAME: if (value == null) { unsetName(); } else { setName((String)value); } break; case PAYLOAD: if (value == null) { unsetPayload(); } else { setPayload((ByteBuffer)value); } break; case PORT: if (value == null) { unsetPort(); } else { setPort((Integer)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case NAME: return getName(); case PAYLOAD: return getPayload(); case PORT: return Integer.valueOf(getPort()); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case NAME: return isSetName(); case PAYLOAD: return isSetPayload(); case PORT: return isSetPort(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof makeDiscoveryInstance_args) return this.equals((makeDiscoveryInstance_args)that); return false; } public boolean equals(makeDiscoveryInstance_args that) { if (that == null) return false; boolean this_present_name = true && this.isSetName(); boolean that_present_name = true && that.isSetName(); if (this_present_name || that_present_name) { if (!(this_present_name && that_present_name)) return false; if (!this.name.equals(that.name)) return false; } boolean this_present_payload = true && this.isSetPayload(); boolean that_present_payload = true && that.isSetPayload(); if (this_present_payload || that_present_payload) { if (!(this_present_payload && that_present_payload)) return false; if (!this.payload.equals(that.payload)) return false; } boolean this_present_port = true; boolean that_present_port = true; if (this_present_port || that_present_port) { if (!(this_present_port && that_present_port)) return false; if (this.port != that.port) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(makeDiscoveryInstance_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetName()).compareTo(other.isSetName()); if (lastComparison != 0) { return lastComparison; } if (isSetName()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPayload()).compareTo(other.isSetPayload()); if (lastComparison != 0) { return lastComparison; } if (isSetPayload()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.payload, other.payload); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPort()).compareTo(other.isSetPort()); if (lastComparison != 0) { return lastComparison; } if (isSetPort()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.port, other.port); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("makeDiscoveryInstance_args("); boolean first = true; sb.append("name:"); if (this.name == null) { sb.append("null"); } else { sb.append(this.name); } first = false; if (!first) sb.append(", "); sb.append("payload:"); if (this.payload == null) { sb.append("null"); } else { org.apache.thrift.TBaseHelper.toString(this.payload, sb); } first = false; if (!first) sb.append(", "); sb.append("port:"); sb.append(this.port); first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class makeDiscoveryInstance_argsStandardSchemeFactory implements SchemeFactory { public makeDiscoveryInstance_argsStandardScheme getScheme() { return new makeDiscoveryInstance_argsStandardScheme(); } } private static class makeDiscoveryInstance_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, makeDiscoveryInstance_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.name = iprot.readString(); struct.setNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // PAYLOAD if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.payload = iprot.readBinary(); struct.setPayloadIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // PORT if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.port = iprot.readI32(); struct.setPortIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, makeDiscoveryInstance_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.name != null) { oprot.writeFieldBegin(NAME_FIELD_DESC); oprot.writeString(struct.name); oprot.writeFieldEnd(); } if (struct.payload != null) { oprot.writeFieldBegin(PAYLOAD_FIELD_DESC); oprot.writeBinary(struct.payload); oprot.writeFieldEnd(); } oprot.writeFieldBegin(PORT_FIELD_DESC); oprot.writeI32(struct.port); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class makeDiscoveryInstance_argsTupleSchemeFactory implements SchemeFactory { public makeDiscoveryInstance_argsTupleScheme getScheme() { return new makeDiscoveryInstance_argsTupleScheme(); } } private static class makeDiscoveryInstance_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, makeDiscoveryInstance_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetName()) { optionals.set(0); } if (struct.isSetPayload()) { optionals.set(1); } if (struct.isSetPort()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetName()) { oprot.writeString(struct.name); } if (struct.isSetPayload()) { oprot.writeBinary(struct.payload); } if (struct.isSetPort()) { oprot.writeI32(struct.port); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, makeDiscoveryInstance_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.name = iprot.readString(); struct.setNameIsSet(true); } if (incoming.get(1)) { struct.payload = iprot.readBinary(); struct.setPayloadIsSet(true); } if (incoming.get(2)) { struct.port = iprot.readI32(); struct.setPortIsSet(true); } } } } public static class makeDiscoveryInstance_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("makeDiscoveryInstance_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new makeDiscoveryInstance_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new makeDiscoveryInstance_resultTupleSchemeFactory()); } public DiscoveryInstance success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryInstance.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(makeDiscoveryInstance_result.class, metaDataMap); } public makeDiscoveryInstance_result() { } public makeDiscoveryInstance_result( DiscoveryInstance success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public makeDiscoveryInstance_result(makeDiscoveryInstance_result other) { if (other.isSetSuccess()) { this.success = new DiscoveryInstance(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public makeDiscoveryInstance_result deepCopy() { return new makeDiscoveryInstance_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public DiscoveryInstance getSuccess() { return this.success; } public makeDiscoveryInstance_result setSuccess(DiscoveryInstance success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public makeDiscoveryInstance_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((DiscoveryInstance)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof makeDiscoveryInstance_result) return this.equals((makeDiscoveryInstance_result)that); return false; } public boolean equals(makeDiscoveryInstance_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(makeDiscoveryInstance_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("makeDiscoveryInstance_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class makeDiscoveryInstance_resultStandardSchemeFactory implements SchemeFactory { public makeDiscoveryInstance_resultStandardScheme getScheme() { return new makeDiscoveryInstance_resultStandardScheme(); } } private static class makeDiscoveryInstance_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, makeDiscoveryInstance_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new DiscoveryInstance(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, makeDiscoveryInstance_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class makeDiscoveryInstance_resultTupleSchemeFactory implements SchemeFactory { public makeDiscoveryInstance_resultTupleScheme getScheme() { return new makeDiscoveryInstance_resultTupleScheme(); } } private static class makeDiscoveryInstance_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, makeDiscoveryInstance_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, makeDiscoveryInstance_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new DiscoveryInstance(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class noteError_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("noteError_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField PROVIDER_PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("providerProjection", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final org.apache.thrift.protocol.TField INSTANCE_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("instanceId", org.apache.thrift.protocol.TType.STRING, (short)3); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new noteError_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new noteError_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public DiscoveryProviderProjection providerProjection; // required public String instanceId; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), PROVIDER_PROJECTION((short)2, "providerProjection"), INSTANCE_ID((short)3, "instanceId"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // PROVIDER_PROJECTION return PROVIDER_PROJECTION; case 3: // INSTANCE_ID return INSTANCE_ID; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.PROVIDER_PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("providerProjection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryProviderProjection.class))); tmpMap.put(_Fields.INSTANCE_ID, new org.apache.thrift.meta_data.FieldMetaData("instanceId", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(noteError_args.class, metaDataMap); } public noteError_args() { } public noteError_args( CuratorProjection projection, DiscoveryProviderProjection providerProjection, String instanceId) { this(); this.projection = projection; this.providerProjection = providerProjection; this.instanceId = instanceId; } /** * Performs a deep copy on other. */ public noteError_args(noteError_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetProviderProjection()) { this.providerProjection = new DiscoveryProviderProjection(other.providerProjection); } if (other.isSetInstanceId()) { this.instanceId = other.instanceId; } } public noteError_args deepCopy() { return new noteError_args(this); } @Override public void clear() { this.projection = null; this.providerProjection = null; this.instanceId = null; } public CuratorProjection getProjection() { return this.projection; } public noteError_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public DiscoveryProviderProjection getProviderProjection() { return this.providerProjection; } public noteError_args setProviderProjection(DiscoveryProviderProjection providerProjection) { this.providerProjection = providerProjection; return this; } public void unsetProviderProjection() { this.providerProjection = null; } /** Returns true if field providerProjection is set (has been assigned a value) and false otherwise */ public boolean isSetProviderProjection() { return this.providerProjection != null; } public void setProviderProjectionIsSet(boolean value) { if (!value) { this.providerProjection = null; } } public String getInstanceId() { return this.instanceId; } public noteError_args setInstanceId(String instanceId) { this.instanceId = instanceId; return this; } public void unsetInstanceId() { this.instanceId = null; } /** Returns true if field instanceId is set (has been assigned a value) and false otherwise */ public boolean isSetInstanceId() { return this.instanceId != null; } public void setInstanceIdIsSet(boolean value) { if (!value) { this.instanceId = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case PROVIDER_PROJECTION: if (value == null) { unsetProviderProjection(); } else { setProviderProjection((DiscoveryProviderProjection)value); } break; case INSTANCE_ID: if (value == null) { unsetInstanceId(); } else { setInstanceId((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case PROVIDER_PROJECTION: return getProviderProjection(); case INSTANCE_ID: return getInstanceId(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case PROVIDER_PROJECTION: return isSetProviderProjection(); case INSTANCE_ID: return isSetInstanceId(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof noteError_args) return this.equals((noteError_args)that); return false; } public boolean equals(noteError_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_providerProjection = true && this.isSetProviderProjection(); boolean that_present_providerProjection = true && that.isSetProviderProjection(); if (this_present_providerProjection || that_present_providerProjection) { if (!(this_present_providerProjection && that_present_providerProjection)) return false; if (!this.providerProjection.equals(that.providerProjection)) return false; } boolean this_present_instanceId = true && this.isSetInstanceId(); boolean that_present_instanceId = true && that.isSetInstanceId(); if (this_present_instanceId || that_present_instanceId) { if (!(this_present_instanceId && that_present_instanceId)) return false; if (!this.instanceId.equals(that.instanceId)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(noteError_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetProviderProjection()).compareTo(other.isSetProviderProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProviderProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.providerProjection, other.providerProjection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetInstanceId()).compareTo(other.isSetInstanceId()); if (lastComparison != 0) { return lastComparison; } if (isSetInstanceId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.instanceId, other.instanceId); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("noteError_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("providerProjection:"); if (this.providerProjection == null) { sb.append("null"); } else { sb.append(this.providerProjection); } first = false; if (!first) sb.append(", "); sb.append("instanceId:"); if (this.instanceId == null) { sb.append("null"); } else { sb.append(this.instanceId); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (providerProjection != null) { providerProjection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class noteError_argsStandardSchemeFactory implements SchemeFactory { public noteError_argsStandardScheme getScheme() { return new noteError_argsStandardScheme(); } } private static class noteError_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, noteError_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // PROVIDER_PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.providerProjection = new DiscoveryProviderProjection(); struct.providerProjection.read(iprot); struct.setProviderProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // INSTANCE_ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.instanceId = iprot.readString(); struct.setInstanceIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, noteError_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.providerProjection != null) { oprot.writeFieldBegin(PROVIDER_PROJECTION_FIELD_DESC); struct.providerProjection.write(oprot); oprot.writeFieldEnd(); } if (struct.instanceId != null) { oprot.writeFieldBegin(INSTANCE_ID_FIELD_DESC); oprot.writeString(struct.instanceId); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class noteError_argsTupleSchemeFactory implements SchemeFactory { public noteError_argsTupleScheme getScheme() { return new noteError_argsTupleScheme(); } } private static class noteError_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, noteError_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetProviderProjection()) { optionals.set(1); } if (struct.isSetInstanceId()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetProviderProjection()) { struct.providerProjection.write(oprot); } if (struct.isSetInstanceId()) { oprot.writeString(struct.instanceId); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, noteError_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.providerProjection = new DiscoveryProviderProjection(); struct.providerProjection.read(iprot); struct.setProviderProjectionIsSet(true); } if (incoming.get(2)) { struct.instanceId = iprot.readString(); struct.setInstanceIdIsSet(true); } } } } public static class noteError_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("noteError_result"); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new noteError_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new noteError_resultTupleSchemeFactory()); } public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(noteError_result.class, metaDataMap); } public noteError_result() { } public noteError_result( CuratorException ex1) { this(); this.ex1 = ex1; } /** * Performs a deep copy on other. */ public noteError_result(noteError_result other) { if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public noteError_result deepCopy() { return new noteError_result(this); } @Override public void clear() { this.ex1 = null; } public CuratorException getEx1() { return this.ex1; } public noteError_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof noteError_result) return this.equals((noteError_result)that); return false; } public boolean equals(noteError_result that) { if (that == null) return false; boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(noteError_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("noteError_result("); boolean first = true; sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class noteError_resultStandardSchemeFactory implements SchemeFactory { public noteError_resultStandardScheme getScheme() { return new noteError_resultStandardScheme(); } } private static class noteError_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, noteError_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, noteError_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class noteError_resultTupleSchemeFactory implements SchemeFactory { public noteError_resultTupleScheme getScheme() { return new noteError_resultTupleScheme(); } } private static class noteError_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, noteError_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetEx1()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, noteError_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class startDiscovery_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("startDiscovery_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField BASE_PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("basePath", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField YOUR_INSTANCE_FIELD_DESC = new org.apache.thrift.protocol.TField("yourInstance", org.apache.thrift.protocol.TType.STRUCT, (short)3); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new startDiscovery_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new startDiscovery_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public String basePath; // required public DiscoveryInstance yourInstance; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), BASE_PATH((short)2, "basePath"), YOUR_INSTANCE((short)3, "yourInstance"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // BASE_PATH return BASE_PATH; case 3: // YOUR_INSTANCE return YOUR_INSTANCE; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.BASE_PATH, new org.apache.thrift.meta_data.FieldMetaData("basePath", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.YOUR_INSTANCE, new org.apache.thrift.meta_data.FieldMetaData("yourInstance", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryInstance.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(startDiscovery_args.class, metaDataMap); } public startDiscovery_args() { } public startDiscovery_args( CuratorProjection projection, String basePath, DiscoveryInstance yourInstance) { this(); this.projection = projection; this.basePath = basePath; this.yourInstance = yourInstance; } /** * Performs a deep copy on other. */ public startDiscovery_args(startDiscovery_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetBasePath()) { this.basePath = other.basePath; } if (other.isSetYourInstance()) { this.yourInstance = new DiscoveryInstance(other.yourInstance); } } public startDiscovery_args deepCopy() { return new startDiscovery_args(this); } @Override public void clear() { this.projection = null; this.basePath = null; this.yourInstance = null; } public CuratorProjection getProjection() { return this.projection; } public startDiscovery_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public String getBasePath() { return this.basePath; } public startDiscovery_args setBasePath(String basePath) { this.basePath = basePath; return this; } public void unsetBasePath() { this.basePath = null; } /** Returns true if field basePath is set (has been assigned a value) and false otherwise */ public boolean isSetBasePath() { return this.basePath != null; } public void setBasePathIsSet(boolean value) { if (!value) { this.basePath = null; } } public DiscoveryInstance getYourInstance() { return this.yourInstance; } public startDiscovery_args setYourInstance(DiscoveryInstance yourInstance) { this.yourInstance = yourInstance; return this; } public void unsetYourInstance() { this.yourInstance = null; } /** Returns true if field yourInstance is set (has been assigned a value) and false otherwise */ public boolean isSetYourInstance() { return this.yourInstance != null; } public void setYourInstanceIsSet(boolean value) { if (!value) { this.yourInstance = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case BASE_PATH: if (value == null) { unsetBasePath(); } else { setBasePath((String)value); } break; case YOUR_INSTANCE: if (value == null) { unsetYourInstance(); } else { setYourInstance((DiscoveryInstance)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case BASE_PATH: return getBasePath(); case YOUR_INSTANCE: return getYourInstance(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case BASE_PATH: return isSetBasePath(); case YOUR_INSTANCE: return isSetYourInstance(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof startDiscovery_args) return this.equals((startDiscovery_args)that); return false; } public boolean equals(startDiscovery_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_basePath = true && this.isSetBasePath(); boolean that_present_basePath = true && that.isSetBasePath(); if (this_present_basePath || that_present_basePath) { if (!(this_present_basePath && that_present_basePath)) return false; if (!this.basePath.equals(that.basePath)) return false; } boolean this_present_yourInstance = true && this.isSetYourInstance(); boolean that_present_yourInstance = true && that.isSetYourInstance(); if (this_present_yourInstance || that_present_yourInstance) { if (!(this_present_yourInstance && that_present_yourInstance)) return false; if (!this.yourInstance.equals(that.yourInstance)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(startDiscovery_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetBasePath()).compareTo(other.isSetBasePath()); if (lastComparison != 0) { return lastComparison; } if (isSetBasePath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.basePath, other.basePath); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetYourInstance()).compareTo(other.isSetYourInstance()); if (lastComparison != 0) { return lastComparison; } if (isSetYourInstance()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.yourInstance, other.yourInstance); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("startDiscovery_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("basePath:"); if (this.basePath == null) { sb.append("null"); } else { sb.append(this.basePath); } first = false; if (!first) sb.append(", "); sb.append("yourInstance:"); if (this.yourInstance == null) { sb.append("null"); } else { sb.append(this.yourInstance); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (yourInstance != null) { yourInstance.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class startDiscovery_argsStandardSchemeFactory implements SchemeFactory { public startDiscovery_argsStandardScheme getScheme() { return new startDiscovery_argsStandardScheme(); } } private static class startDiscovery_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, startDiscovery_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // BASE_PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.basePath = iprot.readString(); struct.setBasePathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // YOUR_INSTANCE if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.yourInstance = new DiscoveryInstance(); struct.yourInstance.read(iprot); struct.setYourInstanceIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, startDiscovery_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.basePath != null) { oprot.writeFieldBegin(BASE_PATH_FIELD_DESC); oprot.writeString(struct.basePath); oprot.writeFieldEnd(); } if (struct.yourInstance != null) { oprot.writeFieldBegin(YOUR_INSTANCE_FIELD_DESC); struct.yourInstance.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class startDiscovery_argsTupleSchemeFactory implements SchemeFactory { public startDiscovery_argsTupleScheme getScheme() { return new startDiscovery_argsTupleScheme(); } } private static class startDiscovery_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, startDiscovery_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetBasePath()) { optionals.set(1); } if (struct.isSetYourInstance()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetBasePath()) { oprot.writeString(struct.basePath); } if (struct.isSetYourInstance()) { struct.yourInstance.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, startDiscovery_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.basePath = iprot.readString(); struct.setBasePathIsSet(true); } if (incoming.get(2)) { struct.yourInstance = new DiscoveryInstance(); struct.yourInstance.read(iprot); struct.setYourInstanceIsSet(true); } } } } public static class startDiscovery_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("startDiscovery_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new startDiscovery_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new startDiscovery_resultTupleSchemeFactory()); } public DiscoveryProjection success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryProjection.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(startDiscovery_result.class, metaDataMap); } public startDiscovery_result() { } public startDiscovery_result( DiscoveryProjection success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public startDiscovery_result(startDiscovery_result other) { if (other.isSetSuccess()) { this.success = new DiscoveryProjection(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public startDiscovery_result deepCopy() { return new startDiscovery_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public DiscoveryProjection getSuccess() { return this.success; } public startDiscovery_result setSuccess(DiscoveryProjection success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public startDiscovery_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((DiscoveryProjection)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof startDiscovery_result) return this.equals((startDiscovery_result)that); return false; } public boolean equals(startDiscovery_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(startDiscovery_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("startDiscovery_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class startDiscovery_resultStandardSchemeFactory implements SchemeFactory { public startDiscovery_resultStandardScheme getScheme() { return new startDiscovery_resultStandardScheme(); } } private static class startDiscovery_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, startDiscovery_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new DiscoveryProjection(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, startDiscovery_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class startDiscovery_resultTupleSchemeFactory implements SchemeFactory { public startDiscovery_resultTupleScheme getScheme() { return new startDiscovery_resultTupleScheme(); } } private static class startDiscovery_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, startDiscovery_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, startDiscovery_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new DiscoveryProjection(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class startProvider_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("startProvider_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField DISCOVERY_PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("discoveryProjection", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final org.apache.thrift.protocol.TField SERVICE_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("serviceName", org.apache.thrift.protocol.TType.STRING, (short)3); private static final org.apache.thrift.protocol.TField PROVIDER_STRATEGY_FIELD_DESC = new org.apache.thrift.protocol.TField("providerStrategy", org.apache.thrift.protocol.TType.I32, (short)4); private static final org.apache.thrift.protocol.TField DOWN_TIMEOUT_MS_FIELD_DESC = new org.apache.thrift.protocol.TField("downTimeoutMs", org.apache.thrift.protocol.TType.I32, (short)5); private static final org.apache.thrift.protocol.TField DOWN_ERROR_THRESHOLD_FIELD_DESC = new org.apache.thrift.protocol.TField("downErrorThreshold", org.apache.thrift.protocol.TType.I32, (short)6); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new startProvider_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new startProvider_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public DiscoveryProjection discoveryProjection; // required public String serviceName; // required /** * * @see ProviderStrategyType */ public ProviderStrategyType providerStrategy; // required public int downTimeoutMs; // required public int downErrorThreshold; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), DISCOVERY_PROJECTION((short)2, "discoveryProjection"), SERVICE_NAME((short)3, "serviceName"), /** * * @see ProviderStrategyType */ PROVIDER_STRATEGY((short)4, "providerStrategy"), DOWN_TIMEOUT_MS((short)5, "downTimeoutMs"), DOWN_ERROR_THRESHOLD((short)6, "downErrorThreshold"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // DISCOVERY_PROJECTION return DISCOVERY_PROJECTION; case 3: // SERVICE_NAME return SERVICE_NAME; case 4: // PROVIDER_STRATEGY return PROVIDER_STRATEGY; case 5: // DOWN_TIMEOUT_MS return DOWN_TIMEOUT_MS; case 6: // DOWN_ERROR_THRESHOLD return DOWN_ERROR_THRESHOLD; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __DOWNTIMEOUTMS_ISSET_ID = 0; private static final int __DOWNERRORTHRESHOLD_ISSET_ID = 1; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.DISCOVERY_PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("discoveryProjection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryProjection.class))); tmpMap.put(_Fields.SERVICE_NAME, new org.apache.thrift.meta_data.FieldMetaData("serviceName", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.PROVIDER_STRATEGY, new org.apache.thrift.meta_data.FieldMetaData("providerStrategy", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, ProviderStrategyType.class))); tmpMap.put(_Fields.DOWN_TIMEOUT_MS, new org.apache.thrift.meta_data.FieldMetaData("downTimeoutMs", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.DOWN_ERROR_THRESHOLD, new org.apache.thrift.meta_data.FieldMetaData("downErrorThreshold", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(startProvider_args.class, metaDataMap); } public startProvider_args() { } public startProvider_args( CuratorProjection projection, DiscoveryProjection discoveryProjection, String serviceName, ProviderStrategyType providerStrategy, int downTimeoutMs, int downErrorThreshold) { this(); this.projection = projection; this.discoveryProjection = discoveryProjection; this.serviceName = serviceName; this.providerStrategy = providerStrategy; this.downTimeoutMs = downTimeoutMs; setDownTimeoutMsIsSet(true); this.downErrorThreshold = downErrorThreshold; setDownErrorThresholdIsSet(true); } /** * Performs a deep copy on other. */ public startProvider_args(startProvider_args other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetDiscoveryProjection()) { this.discoveryProjection = new DiscoveryProjection(other.discoveryProjection); } if (other.isSetServiceName()) { this.serviceName = other.serviceName; } if (other.isSetProviderStrategy()) { this.providerStrategy = other.providerStrategy; } this.downTimeoutMs = other.downTimeoutMs; this.downErrorThreshold = other.downErrorThreshold; } public startProvider_args deepCopy() { return new startProvider_args(this); } @Override public void clear() { this.projection = null; this.discoveryProjection = null; this.serviceName = null; this.providerStrategy = null; setDownTimeoutMsIsSet(false); this.downTimeoutMs = 0; setDownErrorThresholdIsSet(false); this.downErrorThreshold = 0; } public CuratorProjection getProjection() { return this.projection; } public startProvider_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public DiscoveryProjection getDiscoveryProjection() { return this.discoveryProjection; } public startProvider_args setDiscoveryProjection(DiscoveryProjection discoveryProjection) { this.discoveryProjection = discoveryProjection; return this; } public void unsetDiscoveryProjection() { this.discoveryProjection = null; } /** Returns true if field discoveryProjection is set (has been assigned a value) and false otherwise */ public boolean isSetDiscoveryProjection() { return this.discoveryProjection != null; } public void setDiscoveryProjectionIsSet(boolean value) { if (!value) { this.discoveryProjection = null; } } public String getServiceName() { return this.serviceName; } public startProvider_args setServiceName(String serviceName) { this.serviceName = serviceName; return this; } public void unsetServiceName() { this.serviceName = null; } /** Returns true if field serviceName is set (has been assigned a value) and false otherwise */ public boolean isSetServiceName() { return this.serviceName != null; } public void setServiceNameIsSet(boolean value) { if (!value) { this.serviceName = null; } } /** * * @see ProviderStrategyType */ public ProviderStrategyType getProviderStrategy() { return this.providerStrategy; } /** * * @see ProviderStrategyType */ public startProvider_args setProviderStrategy(ProviderStrategyType providerStrategy) { this.providerStrategy = providerStrategy; return this; } public void unsetProviderStrategy() { this.providerStrategy = null; } /** Returns true if field providerStrategy is set (has been assigned a value) and false otherwise */ public boolean isSetProviderStrategy() { return this.providerStrategy != null; } public void setProviderStrategyIsSet(boolean value) { if (!value) { this.providerStrategy = null; } } public int getDownTimeoutMs() { return this.downTimeoutMs; } public startProvider_args setDownTimeoutMs(int downTimeoutMs) { this.downTimeoutMs = downTimeoutMs; setDownTimeoutMsIsSet(true); return this; } public void unsetDownTimeoutMs() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __DOWNTIMEOUTMS_ISSET_ID); } /** Returns true if field downTimeoutMs is set (has been assigned a value) and false otherwise */ public boolean isSetDownTimeoutMs() { return EncodingUtils.testBit(__isset_bitfield, __DOWNTIMEOUTMS_ISSET_ID); } public void setDownTimeoutMsIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __DOWNTIMEOUTMS_ISSET_ID, value); } public int getDownErrorThreshold() { return this.downErrorThreshold; } public startProvider_args setDownErrorThreshold(int downErrorThreshold) { this.downErrorThreshold = downErrorThreshold; setDownErrorThresholdIsSet(true); return this; } public void unsetDownErrorThreshold() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __DOWNERRORTHRESHOLD_ISSET_ID); } /** Returns true if field downErrorThreshold is set (has been assigned a value) and false otherwise */ public boolean isSetDownErrorThreshold() { return EncodingUtils.testBit(__isset_bitfield, __DOWNERRORTHRESHOLD_ISSET_ID); } public void setDownErrorThresholdIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __DOWNERRORTHRESHOLD_ISSET_ID, value); } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case DISCOVERY_PROJECTION: if (value == null) { unsetDiscoveryProjection(); } else { setDiscoveryProjection((DiscoveryProjection)value); } break; case SERVICE_NAME: if (value == null) { unsetServiceName(); } else { setServiceName((String)value); } break; case PROVIDER_STRATEGY: if (value == null) { unsetProviderStrategy(); } else { setProviderStrategy((ProviderStrategyType)value); } break; case DOWN_TIMEOUT_MS: if (value == null) { unsetDownTimeoutMs(); } else { setDownTimeoutMs((Integer)value); } break; case DOWN_ERROR_THRESHOLD: if (value == null) { unsetDownErrorThreshold(); } else { setDownErrorThreshold((Integer)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case DISCOVERY_PROJECTION: return getDiscoveryProjection(); case SERVICE_NAME: return getServiceName(); case PROVIDER_STRATEGY: return getProviderStrategy(); case DOWN_TIMEOUT_MS: return Integer.valueOf(getDownTimeoutMs()); case DOWN_ERROR_THRESHOLD: return Integer.valueOf(getDownErrorThreshold()); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case DISCOVERY_PROJECTION: return isSetDiscoveryProjection(); case SERVICE_NAME: return isSetServiceName(); case PROVIDER_STRATEGY: return isSetProviderStrategy(); case DOWN_TIMEOUT_MS: return isSetDownTimeoutMs(); case DOWN_ERROR_THRESHOLD: return isSetDownErrorThreshold(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof startProvider_args) return this.equals((startProvider_args)that); return false; } public boolean equals(startProvider_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_discoveryProjection = true && this.isSetDiscoveryProjection(); boolean that_present_discoveryProjection = true && that.isSetDiscoveryProjection(); if (this_present_discoveryProjection || that_present_discoveryProjection) { if (!(this_present_discoveryProjection && that_present_discoveryProjection)) return false; if (!this.discoveryProjection.equals(that.discoveryProjection)) return false; } boolean this_present_serviceName = true && this.isSetServiceName(); boolean that_present_serviceName = true && that.isSetServiceName(); if (this_present_serviceName || that_present_serviceName) { if (!(this_present_serviceName && that_present_serviceName)) return false; if (!this.serviceName.equals(that.serviceName)) return false; } boolean this_present_providerStrategy = true && this.isSetProviderStrategy(); boolean that_present_providerStrategy = true && that.isSetProviderStrategy(); if (this_present_providerStrategy || that_present_providerStrategy) { if (!(this_present_providerStrategy && that_present_providerStrategy)) return false; if (!this.providerStrategy.equals(that.providerStrategy)) return false; } boolean this_present_downTimeoutMs = true; boolean that_present_downTimeoutMs = true; if (this_present_downTimeoutMs || that_present_downTimeoutMs) { if (!(this_present_downTimeoutMs && that_present_downTimeoutMs)) return false; if (this.downTimeoutMs != that.downTimeoutMs) return false; } boolean this_present_downErrorThreshold = true; boolean that_present_downErrorThreshold = true; if (this_present_downErrorThreshold || that_present_downErrorThreshold) { if (!(this_present_downErrorThreshold && that_present_downErrorThreshold)) return false; if (this.downErrorThreshold != that.downErrorThreshold) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(startProvider_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetDiscoveryProjection()).compareTo(other.isSetDiscoveryProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetDiscoveryProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.discoveryProjection, other.discoveryProjection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetServiceName()).compareTo(other.isSetServiceName()); if (lastComparison != 0) { return lastComparison; } if (isSetServiceName()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.serviceName, other.serviceName); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetProviderStrategy()).compareTo(other.isSetProviderStrategy()); if (lastComparison != 0) { return lastComparison; } if (isSetProviderStrategy()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.providerStrategy, other.providerStrategy); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetDownTimeoutMs()).compareTo(other.isSetDownTimeoutMs()); if (lastComparison != 0) { return lastComparison; } if (isSetDownTimeoutMs()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.downTimeoutMs, other.downTimeoutMs); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetDownErrorThreshold()).compareTo(other.isSetDownErrorThreshold()); if (lastComparison != 0) { return lastComparison; } if (isSetDownErrorThreshold()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.downErrorThreshold, other.downErrorThreshold); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("startProvider_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("discoveryProjection:"); if (this.discoveryProjection == null) { sb.append("null"); } else { sb.append(this.discoveryProjection); } first = false; if (!first) sb.append(", "); sb.append("serviceName:"); if (this.serviceName == null) { sb.append("null"); } else { sb.append(this.serviceName); } first = false; if (!first) sb.append(", "); sb.append("providerStrategy:"); if (this.providerStrategy == null) { sb.append("null"); } else { sb.append(this.providerStrategy); } first = false; if (!first) sb.append(", "); sb.append("downTimeoutMs:"); sb.append(this.downTimeoutMs); first = false; if (!first) sb.append(", "); sb.append("downErrorThreshold:"); sb.append(this.downErrorThreshold); first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (discoveryProjection != null) { discoveryProjection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class startProvider_argsStandardSchemeFactory implements SchemeFactory { public startProvider_argsStandardScheme getScheme() { return new startProvider_argsStandardScheme(); } } private static class startProvider_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, startProvider_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // DISCOVERY_PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.discoveryProjection = new DiscoveryProjection(); struct.discoveryProjection.read(iprot); struct.setDiscoveryProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // SERVICE_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.serviceName = iprot.readString(); struct.setServiceNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // PROVIDER_STRATEGY if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.providerStrategy = ProviderStrategyType.findByValue(iprot.readI32()); struct.setProviderStrategyIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // DOWN_TIMEOUT_MS if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.downTimeoutMs = iprot.readI32(); struct.setDownTimeoutMsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // DOWN_ERROR_THRESHOLD if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.downErrorThreshold = iprot.readI32(); struct.setDownErrorThresholdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, startProvider_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.discoveryProjection != null) { oprot.writeFieldBegin(DISCOVERY_PROJECTION_FIELD_DESC); struct.discoveryProjection.write(oprot); oprot.writeFieldEnd(); } if (struct.serviceName != null) { oprot.writeFieldBegin(SERVICE_NAME_FIELD_DESC); oprot.writeString(struct.serviceName); oprot.writeFieldEnd(); } if (struct.providerStrategy != null) { oprot.writeFieldBegin(PROVIDER_STRATEGY_FIELD_DESC); oprot.writeI32(struct.providerStrategy.getValue()); oprot.writeFieldEnd(); } oprot.writeFieldBegin(DOWN_TIMEOUT_MS_FIELD_DESC); oprot.writeI32(struct.downTimeoutMs); oprot.writeFieldEnd(); oprot.writeFieldBegin(DOWN_ERROR_THRESHOLD_FIELD_DESC); oprot.writeI32(struct.downErrorThreshold); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class startProvider_argsTupleSchemeFactory implements SchemeFactory { public startProvider_argsTupleScheme getScheme() { return new startProvider_argsTupleScheme(); } } private static class startProvider_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, startProvider_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetDiscoveryProjection()) { optionals.set(1); } if (struct.isSetServiceName()) { optionals.set(2); } if (struct.isSetProviderStrategy()) { optionals.set(3); } if (struct.isSetDownTimeoutMs()) { optionals.set(4); } if (struct.isSetDownErrorThreshold()) { optionals.set(5); } oprot.writeBitSet(optionals, 6); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetDiscoveryProjection()) { struct.discoveryProjection.write(oprot); } if (struct.isSetServiceName()) { oprot.writeString(struct.serviceName); } if (struct.isSetProviderStrategy()) { oprot.writeI32(struct.providerStrategy.getValue()); } if (struct.isSetDownTimeoutMs()) { oprot.writeI32(struct.downTimeoutMs); } if (struct.isSetDownErrorThreshold()) { oprot.writeI32(struct.downErrorThreshold); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, startProvider_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(6); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.discoveryProjection = new DiscoveryProjection(); struct.discoveryProjection.read(iprot); struct.setDiscoveryProjectionIsSet(true); } if (incoming.get(2)) { struct.serviceName = iprot.readString(); struct.setServiceNameIsSet(true); } if (incoming.get(3)) { struct.providerStrategy = ProviderStrategyType.findByValue(iprot.readI32()); struct.setProviderStrategyIsSet(true); } if (incoming.get(4)) { struct.downTimeoutMs = iprot.readI32(); struct.setDownTimeoutMsIsSet(true); } if (incoming.get(5)) { struct.downErrorThreshold = iprot.readI32(); struct.setDownErrorThresholdIsSet(true); } } } } public static class startProvider_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("startProvider_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new startProvider_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new startProvider_resultTupleSchemeFactory()); } public DiscoveryProviderProjection success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryProviderProjection.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(startProvider_result.class, metaDataMap); } public startProvider_result() { } public startProvider_result( DiscoveryProviderProjection success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public startProvider_result(startProvider_result other) { if (other.isSetSuccess()) { this.success = new DiscoveryProviderProjection(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public startProvider_result deepCopy() { return new startProvider_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public DiscoveryProviderProjection getSuccess() { return this.success; } public startProvider_result setSuccess(DiscoveryProviderProjection success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public startProvider_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((DiscoveryProviderProjection)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof startProvider_result) return this.equals((startProvider_result)that); return false; } public boolean equals(startProvider_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(startProvider_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("startProvider_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class startProvider_resultStandardSchemeFactory implements SchemeFactory { public startProvider_resultStandardScheme getScheme() { return new startProvider_resultStandardScheme(); } } private static class startProvider_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, startProvider_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new DiscoveryProviderProjection(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, startProvider_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class startProvider_resultTupleSchemeFactory implements SchemeFactory { public startProvider_resultTupleScheme getScheme() { return new startProvider_resultTupleScheme(); } } private static class startProvider_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, startProvider_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, startProvider_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new DiscoveryProviderProjection(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } } DiscoveryServiceLowLevel.java000066400000000000000000007430341245521677600364760ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DiscoveryServiceLowLevel { public interface Iface { public DiscoveryInstance queryForInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, String name, String id) throws CuratorException, org.apache.thrift.TException; public List queryForInstances(CuratorProjection projection, DiscoveryProjection discoveryProjection, String name) throws CuratorException, org.apache.thrift.TException; public List queryForNames(CuratorProjection projection, DiscoveryProjection discoveryProjection) throws CuratorException, org.apache.thrift.TException; public void registerInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance) throws CuratorException, org.apache.thrift.TException; public void unregisterInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance) throws CuratorException, org.apache.thrift.TException; public void updateInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance) throws CuratorException, org.apache.thrift.TException; } public interface AsyncIface { public void queryForInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, String name, String id, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void queryForInstances(CuratorProjection projection, DiscoveryProjection discoveryProjection, String name, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void queryForNames(CuratorProjection projection, DiscoveryProjection discoveryProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void registerInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void unregisterInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void updateInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; } public static class Client extends org.apache.thrift.TServiceClient implements Iface { public static class Factory implements org.apache.thrift.TServiceClientFactory { public Factory() {} public Client getClient(org.apache.thrift.protocol.TProtocol prot) { return new Client(prot); } public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { return new Client(iprot, oprot); } } public Client(org.apache.thrift.protocol.TProtocol prot) { super(prot, prot); } public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { super(iprot, oprot); } public DiscoveryInstance queryForInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, String name, String id) throws CuratorException, org.apache.thrift.TException { send_queryForInstance(projection, discoveryProjection, name, id); return recv_queryForInstance(); } public void send_queryForInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, String name, String id) throws org.apache.thrift.TException { queryForInstance_args args = new queryForInstance_args(); args.setProjection(projection); args.setDiscoveryProjection(discoveryProjection); args.setName(name); args.setId(id); sendBase("queryForInstance", args); } public DiscoveryInstance recv_queryForInstance() throws CuratorException, org.apache.thrift.TException { queryForInstance_result result = new queryForInstance_result(); receiveBase(result, "queryForInstance"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "queryForInstance failed: unknown result"); } public List queryForInstances(CuratorProjection projection, DiscoveryProjection discoveryProjection, String name) throws CuratorException, org.apache.thrift.TException { send_queryForInstances(projection, discoveryProjection, name); return recv_queryForInstances(); } public void send_queryForInstances(CuratorProjection projection, DiscoveryProjection discoveryProjection, String name) throws org.apache.thrift.TException { queryForInstances_args args = new queryForInstances_args(); args.setProjection(projection); args.setDiscoveryProjection(discoveryProjection); args.setName(name); sendBase("queryForInstances", args); } public List recv_queryForInstances() throws CuratorException, org.apache.thrift.TException { queryForInstances_result result = new queryForInstances_result(); receiveBase(result, "queryForInstances"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "queryForInstances failed: unknown result"); } public List queryForNames(CuratorProjection projection, DiscoveryProjection discoveryProjection) throws CuratorException, org.apache.thrift.TException { send_queryForNames(projection, discoveryProjection); return recv_queryForNames(); } public void send_queryForNames(CuratorProjection projection, DiscoveryProjection discoveryProjection) throws org.apache.thrift.TException { queryForNames_args args = new queryForNames_args(); args.setProjection(projection); args.setDiscoveryProjection(discoveryProjection); sendBase("queryForNames", args); } public List recv_queryForNames() throws CuratorException, org.apache.thrift.TException { queryForNames_result result = new queryForNames_result(); receiveBase(result, "queryForNames"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "queryForNames failed: unknown result"); } public void registerInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance) throws CuratorException, org.apache.thrift.TException { send_registerInstance(projection, discoveryProjection, instance); recv_registerInstance(); } public void send_registerInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance) throws org.apache.thrift.TException { registerInstance_args args = new registerInstance_args(); args.setProjection(projection); args.setDiscoveryProjection(discoveryProjection); args.setInstance(instance); sendBase("registerInstance", args); } public void recv_registerInstance() throws CuratorException, org.apache.thrift.TException { registerInstance_result result = new registerInstance_result(); receiveBase(result, "registerInstance"); if (result.ex1 != null) { throw result.ex1; } return; } public void unregisterInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance) throws CuratorException, org.apache.thrift.TException { send_unregisterInstance(projection, discoveryProjection, instance); recv_unregisterInstance(); } public void send_unregisterInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance) throws org.apache.thrift.TException { unregisterInstance_args args = new unregisterInstance_args(); args.setProjection(projection); args.setDiscoveryProjection(discoveryProjection); args.setInstance(instance); sendBase("unregisterInstance", args); } public void recv_unregisterInstance() throws CuratorException, org.apache.thrift.TException { unregisterInstance_result result = new unregisterInstance_result(); receiveBase(result, "unregisterInstance"); if (result.ex1 != null) { throw result.ex1; } return; } public void updateInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance) throws CuratorException, org.apache.thrift.TException { send_updateInstance(projection, discoveryProjection, instance); recv_updateInstance(); } public void send_updateInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance) throws org.apache.thrift.TException { updateInstance_args args = new updateInstance_args(); args.setProjection(projection); args.setDiscoveryProjection(discoveryProjection); args.setInstance(instance); sendBase("updateInstance", args); } public void recv_updateInstance() throws CuratorException, org.apache.thrift.TException { updateInstance_result result = new updateInstance_result(); receiveBase(result, "updateInstance"); if (result.ex1 != null) { throw result.ex1; } return; } } public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface { public static class Factory implements org.apache.thrift.async.TAsyncClientFactory { private org.apache.thrift.async.TAsyncClientManager clientManager; private org.apache.thrift.protocol.TProtocolFactory protocolFactory; public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) { this.clientManager = clientManager; this.protocolFactory = protocolFactory; } public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) { return new AsyncClient(protocolFactory, clientManager, transport); } } public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) { super(protocolFactory, clientManager, transport); } public void queryForInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, String name, String id, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); queryForInstance_call method_call = new queryForInstance_call(projection, discoveryProjection, name, id, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class queryForInstance_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private DiscoveryProjection discoveryProjection; private String name; private String id; public queryForInstance_call(CuratorProjection projection, DiscoveryProjection discoveryProjection, String name, String id, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.discoveryProjection = discoveryProjection; this.name = name; this.id = id; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("queryForInstance", org.apache.thrift.protocol.TMessageType.CALL, 0)); queryForInstance_args args = new queryForInstance_args(); args.setProjection(projection); args.setDiscoveryProjection(discoveryProjection); args.setName(name); args.setId(id); args.write(prot); prot.writeMessageEnd(); } public DiscoveryInstance getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_queryForInstance(); } } public void queryForInstances(CuratorProjection projection, DiscoveryProjection discoveryProjection, String name, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); queryForInstances_call method_call = new queryForInstances_call(projection, discoveryProjection, name, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class queryForInstances_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private DiscoveryProjection discoveryProjection; private String name; public queryForInstances_call(CuratorProjection projection, DiscoveryProjection discoveryProjection, String name, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.discoveryProjection = discoveryProjection; this.name = name; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("queryForInstances", org.apache.thrift.protocol.TMessageType.CALL, 0)); queryForInstances_args args = new queryForInstances_args(); args.setProjection(projection); args.setDiscoveryProjection(discoveryProjection); args.setName(name); args.write(prot); prot.writeMessageEnd(); } public List getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_queryForInstances(); } } public void queryForNames(CuratorProjection projection, DiscoveryProjection discoveryProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); queryForNames_call method_call = new queryForNames_call(projection, discoveryProjection, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class queryForNames_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private DiscoveryProjection discoveryProjection; public queryForNames_call(CuratorProjection projection, DiscoveryProjection discoveryProjection, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.discoveryProjection = discoveryProjection; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("queryForNames", org.apache.thrift.protocol.TMessageType.CALL, 0)); queryForNames_args args = new queryForNames_args(); args.setProjection(projection); args.setDiscoveryProjection(discoveryProjection); args.write(prot); prot.writeMessageEnd(); } public List getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_queryForNames(); } } public void registerInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); registerInstance_call method_call = new registerInstance_call(projection, discoveryProjection, instance, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class registerInstance_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private DiscoveryProjection discoveryProjection; private DiscoveryInstance instance; public registerInstance_call(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.discoveryProjection = discoveryProjection; this.instance = instance; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("registerInstance", org.apache.thrift.protocol.TMessageType.CALL, 0)); registerInstance_args args = new registerInstance_args(); args.setProjection(projection); args.setDiscoveryProjection(discoveryProjection); args.setInstance(instance); args.write(prot); prot.writeMessageEnd(); } public void getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); (new Client(prot)).recv_registerInstance(); } } public void unregisterInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); unregisterInstance_call method_call = new unregisterInstance_call(projection, discoveryProjection, instance, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class unregisterInstance_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private DiscoveryProjection discoveryProjection; private DiscoveryInstance instance; public unregisterInstance_call(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.discoveryProjection = discoveryProjection; this.instance = instance; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("unregisterInstance", org.apache.thrift.protocol.TMessageType.CALL, 0)); unregisterInstance_args args = new unregisterInstance_args(); args.setProjection(projection); args.setDiscoveryProjection(discoveryProjection); args.setInstance(instance); args.write(prot); prot.writeMessageEnd(); } public void getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); (new Client(prot)).recv_unregisterInstance(); } } public void updateInstance(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); updateInstance_call method_call = new updateInstance_call(projection, discoveryProjection, instance, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class updateInstance_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; private DiscoveryProjection discoveryProjection; private DiscoveryInstance instance; public updateInstance_call(CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; this.discoveryProjection = discoveryProjection; this.instance = instance; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("updateInstance", org.apache.thrift.protocol.TMessageType.CALL, 0)); updateInstance_args args = new updateInstance_args(); args.setProjection(projection); args.setDiscoveryProjection(discoveryProjection); args.setInstance(instance); args.write(prot); prot.writeMessageEnd(); } public void getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); (new Client(prot)).recv_updateInstance(); } } } public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName()); public Processor(I iface) { super(iface, getProcessMap(new HashMap>())); } protected Processor(I iface, Map> processMap) { super(iface, getProcessMap(processMap)); } private static Map> getProcessMap(Map> processMap) { processMap.put("queryForInstance", new queryForInstance()); processMap.put("queryForInstances", new queryForInstances()); processMap.put("queryForNames", new queryForNames()); processMap.put("registerInstance", new registerInstance()); processMap.put("unregisterInstance", new unregisterInstance()); processMap.put("updateInstance", new updateInstance()); return processMap; } public static class queryForInstance extends org.apache.thrift.ProcessFunction { public queryForInstance() { super("queryForInstance"); } public queryForInstance_args getEmptyArgsInstance() { return new queryForInstance_args(); } protected boolean isOneway() { return false; } public queryForInstance_result getResult(I iface, queryForInstance_args args) throws org.apache.thrift.TException { queryForInstance_result result = new queryForInstance_result(); try { result.success = iface.queryForInstance(args.projection, args.discoveryProjection, args.name, args.id); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class queryForInstances extends org.apache.thrift.ProcessFunction { public queryForInstances() { super("queryForInstances"); } public queryForInstances_args getEmptyArgsInstance() { return new queryForInstances_args(); } protected boolean isOneway() { return false; } public queryForInstances_result getResult(I iface, queryForInstances_args args) throws org.apache.thrift.TException { queryForInstances_result result = new queryForInstances_result(); try { result.success = iface.queryForInstances(args.projection, args.discoveryProjection, args.name); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class queryForNames extends org.apache.thrift.ProcessFunction { public queryForNames() { super("queryForNames"); } public queryForNames_args getEmptyArgsInstance() { return new queryForNames_args(); } protected boolean isOneway() { return false; } public queryForNames_result getResult(I iface, queryForNames_args args) throws org.apache.thrift.TException { queryForNames_result result = new queryForNames_result(); try { result.success = iface.queryForNames(args.projection, args.discoveryProjection); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class registerInstance extends org.apache.thrift.ProcessFunction { public registerInstance() { super("registerInstance"); } public registerInstance_args getEmptyArgsInstance() { return new registerInstance_args(); } protected boolean isOneway() { return false; } public registerInstance_result getResult(I iface, registerInstance_args args) throws org.apache.thrift.TException { registerInstance_result result = new registerInstance_result(); try { iface.registerInstance(args.projection, args.discoveryProjection, args.instance); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class unregisterInstance extends org.apache.thrift.ProcessFunction { public unregisterInstance() { super("unregisterInstance"); } public unregisterInstance_args getEmptyArgsInstance() { return new unregisterInstance_args(); } protected boolean isOneway() { return false; } public unregisterInstance_result getResult(I iface, unregisterInstance_args args) throws org.apache.thrift.TException { unregisterInstance_result result = new unregisterInstance_result(); try { iface.unregisterInstance(args.projection, args.discoveryProjection, args.instance); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } public static class updateInstance extends org.apache.thrift.ProcessFunction { public updateInstance() { super("updateInstance"); } public updateInstance_args getEmptyArgsInstance() { return new updateInstance_args(); } protected boolean isOneway() { return false; } public updateInstance_result getResult(I iface, updateInstance_args args) throws org.apache.thrift.TException { updateInstance_result result = new updateInstance_result(); try { iface.updateInstance(args.projection, args.discoveryProjection, args.instance); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } } public static class AsyncProcessor extends org.apache.thrift.TBaseAsyncProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName()); public AsyncProcessor(I iface) { super(iface, getProcessMap(new HashMap>())); } protected AsyncProcessor(I iface, Map> processMap) { super(iface, getProcessMap(processMap)); } private static Map> getProcessMap(Map> processMap) { processMap.put("queryForInstance", new queryForInstance()); processMap.put("queryForInstances", new queryForInstances()); processMap.put("queryForNames", new queryForNames()); processMap.put("registerInstance", new registerInstance()); processMap.put("unregisterInstance", new unregisterInstance()); processMap.put("updateInstance", new updateInstance()); return processMap; } public static class queryForInstance extends org.apache.thrift.AsyncProcessFunction { public queryForInstance() { super("queryForInstance"); } public queryForInstance_args getEmptyArgsInstance() { return new queryForInstance_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(DiscoveryInstance o) { queryForInstance_result result = new queryForInstance_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; queryForInstance_result result = new queryForInstance_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, queryForInstance_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.queryForInstance(args.projection, args.discoveryProjection, args.name, args.id,resultHandler); } } public static class queryForInstances extends org.apache.thrift.AsyncProcessFunction> { public queryForInstances() { super("queryForInstances"); } public queryForInstances_args getEmptyArgsInstance() { return new queryForInstances_args(); } public AsyncMethodCallback> getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback>() { public void onComplete(List o) { queryForInstances_result result = new queryForInstances_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; queryForInstances_result result = new queryForInstances_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, queryForInstances_args args, org.apache.thrift.async.AsyncMethodCallback> resultHandler) throws TException { iface.queryForInstances(args.projection, args.discoveryProjection, args.name,resultHandler); } } public static class queryForNames extends org.apache.thrift.AsyncProcessFunction> { public queryForNames() { super("queryForNames"); } public queryForNames_args getEmptyArgsInstance() { return new queryForNames_args(); } public AsyncMethodCallback> getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback>() { public void onComplete(List o) { queryForNames_result result = new queryForNames_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; queryForNames_result result = new queryForNames_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, queryForNames_args args, org.apache.thrift.async.AsyncMethodCallback> resultHandler) throws TException { iface.queryForNames(args.projection, args.discoveryProjection,resultHandler); } } public static class registerInstance extends org.apache.thrift.AsyncProcessFunction { public registerInstance() { super("registerInstance"); } public registerInstance_args getEmptyArgsInstance() { return new registerInstance_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(Void o) { registerInstance_result result = new registerInstance_result(); try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; registerInstance_result result = new registerInstance_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, registerInstance_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.registerInstance(args.projection, args.discoveryProjection, args.instance,resultHandler); } } public static class unregisterInstance extends org.apache.thrift.AsyncProcessFunction { public unregisterInstance() { super("unregisterInstance"); } public unregisterInstance_args getEmptyArgsInstance() { return new unregisterInstance_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(Void o) { unregisterInstance_result result = new unregisterInstance_result(); try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; unregisterInstance_result result = new unregisterInstance_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, unregisterInstance_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.unregisterInstance(args.projection, args.discoveryProjection, args.instance,resultHandler); } } public static class updateInstance extends org.apache.thrift.AsyncProcessFunction { public updateInstance() { super("updateInstance"); } public updateInstance_args getEmptyArgsInstance() { return new updateInstance_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(Void o) { updateInstance_result result = new updateInstance_result(); try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; updateInstance_result result = new updateInstance_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, updateInstance_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.updateInstance(args.projection, args.discoveryProjection, args.instance,resultHandler); } } } public static class queryForInstance_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("queryForInstance_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField DISCOVERY_PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("discoveryProjection", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)3); private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.STRING, (short)4); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new queryForInstance_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new queryForInstance_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public DiscoveryProjection discoveryProjection; // required public String name; // required public String id; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), DISCOVERY_PROJECTION((short)2, "discoveryProjection"), NAME((short)3, "name"), ID((short)4, "id"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // DISCOVERY_PROJECTION return DISCOVERY_PROJECTION; case 3: // NAME return NAME; case 4: // ID return ID; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.DISCOVERY_PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("discoveryProjection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryProjection.class))); tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(queryForInstance_args.class, metaDataMap); } public queryForInstance_args() { } public queryForInstance_args( CuratorProjection projection, DiscoveryProjection discoveryProjection, String name, String id) { this(); this.projection = projection; this.discoveryProjection = discoveryProjection; this.name = name; this.id = id; } /** * Performs a deep copy on other. */ public queryForInstance_args(queryForInstance_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetDiscoveryProjection()) { this.discoveryProjection = new DiscoveryProjection(other.discoveryProjection); } if (other.isSetName()) { this.name = other.name; } if (other.isSetId()) { this.id = other.id; } } public queryForInstance_args deepCopy() { return new queryForInstance_args(this); } @Override public void clear() { this.projection = null; this.discoveryProjection = null; this.name = null; this.id = null; } public CuratorProjection getProjection() { return this.projection; } public queryForInstance_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public DiscoveryProjection getDiscoveryProjection() { return this.discoveryProjection; } public queryForInstance_args setDiscoveryProjection(DiscoveryProjection discoveryProjection) { this.discoveryProjection = discoveryProjection; return this; } public void unsetDiscoveryProjection() { this.discoveryProjection = null; } /** Returns true if field discoveryProjection is set (has been assigned a value) and false otherwise */ public boolean isSetDiscoveryProjection() { return this.discoveryProjection != null; } public void setDiscoveryProjectionIsSet(boolean value) { if (!value) { this.discoveryProjection = null; } } public String getName() { return this.name; } public queryForInstance_args setName(String name) { this.name = name; return this; } public void unsetName() { this.name = null; } /** Returns true if field name is set (has been assigned a value) and false otherwise */ public boolean isSetName() { return this.name != null; } public void setNameIsSet(boolean value) { if (!value) { this.name = null; } } public String getId() { return this.id; } public queryForInstance_args setId(String id) { this.id = id; return this; } public void unsetId() { this.id = null; } /** Returns true if field id is set (has been assigned a value) and false otherwise */ public boolean isSetId() { return this.id != null; } public void setIdIsSet(boolean value) { if (!value) { this.id = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case DISCOVERY_PROJECTION: if (value == null) { unsetDiscoveryProjection(); } else { setDiscoveryProjection((DiscoveryProjection)value); } break; case NAME: if (value == null) { unsetName(); } else { setName((String)value); } break; case ID: if (value == null) { unsetId(); } else { setId((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case DISCOVERY_PROJECTION: return getDiscoveryProjection(); case NAME: return getName(); case ID: return getId(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case DISCOVERY_PROJECTION: return isSetDiscoveryProjection(); case NAME: return isSetName(); case ID: return isSetId(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof queryForInstance_args) return this.equals((queryForInstance_args)that); return false; } public boolean equals(queryForInstance_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_discoveryProjection = true && this.isSetDiscoveryProjection(); boolean that_present_discoveryProjection = true && that.isSetDiscoveryProjection(); if (this_present_discoveryProjection || that_present_discoveryProjection) { if (!(this_present_discoveryProjection && that_present_discoveryProjection)) return false; if (!this.discoveryProjection.equals(that.discoveryProjection)) return false; } boolean this_present_name = true && this.isSetName(); boolean that_present_name = true && that.isSetName(); if (this_present_name || that_present_name) { if (!(this_present_name && that_present_name)) return false; if (!this.name.equals(that.name)) return false; } boolean this_present_id = true && this.isSetId(); boolean that_present_id = true && that.isSetId(); if (this_present_id || that_present_id) { if (!(this_present_id && that_present_id)) return false; if (!this.id.equals(that.id)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(queryForInstance_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetDiscoveryProjection()).compareTo(other.isSetDiscoveryProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetDiscoveryProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.discoveryProjection, other.discoveryProjection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetName()).compareTo(other.isSetName()); if (lastComparison != 0) { return lastComparison; } if (isSetName()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); if (lastComparison != 0) { return lastComparison; } if (isSetId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("queryForInstance_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("discoveryProjection:"); if (this.discoveryProjection == null) { sb.append("null"); } else { sb.append(this.discoveryProjection); } first = false; if (!first) sb.append(", "); sb.append("name:"); if (this.name == null) { sb.append("null"); } else { sb.append(this.name); } first = false; if (!first) sb.append(", "); sb.append("id:"); if (this.id == null) { sb.append("null"); } else { sb.append(this.id); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (discoveryProjection != null) { discoveryProjection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class queryForInstance_argsStandardSchemeFactory implements SchemeFactory { public queryForInstance_argsStandardScheme getScheme() { return new queryForInstance_argsStandardScheme(); } } private static class queryForInstance_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, queryForInstance_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // DISCOVERY_PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.discoveryProjection = new DiscoveryProjection(); struct.discoveryProjection.read(iprot); struct.setDiscoveryProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.name = iprot.readString(); struct.setNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.id = iprot.readString(); struct.setIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, queryForInstance_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.discoveryProjection != null) { oprot.writeFieldBegin(DISCOVERY_PROJECTION_FIELD_DESC); struct.discoveryProjection.write(oprot); oprot.writeFieldEnd(); } if (struct.name != null) { oprot.writeFieldBegin(NAME_FIELD_DESC); oprot.writeString(struct.name); oprot.writeFieldEnd(); } if (struct.id != null) { oprot.writeFieldBegin(ID_FIELD_DESC); oprot.writeString(struct.id); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class queryForInstance_argsTupleSchemeFactory implements SchemeFactory { public queryForInstance_argsTupleScheme getScheme() { return new queryForInstance_argsTupleScheme(); } } private static class queryForInstance_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, queryForInstance_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetDiscoveryProjection()) { optionals.set(1); } if (struct.isSetName()) { optionals.set(2); } if (struct.isSetId()) { optionals.set(3); } oprot.writeBitSet(optionals, 4); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetDiscoveryProjection()) { struct.discoveryProjection.write(oprot); } if (struct.isSetName()) { oprot.writeString(struct.name); } if (struct.isSetId()) { oprot.writeString(struct.id); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, queryForInstance_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(4); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.discoveryProjection = new DiscoveryProjection(); struct.discoveryProjection.read(iprot); struct.setDiscoveryProjectionIsSet(true); } if (incoming.get(2)) { struct.name = iprot.readString(); struct.setNameIsSet(true); } if (incoming.get(3)) { struct.id = iprot.readString(); struct.setIdIsSet(true); } } } } public static class queryForInstance_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("queryForInstance_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new queryForInstance_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new queryForInstance_resultTupleSchemeFactory()); } public DiscoveryInstance success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryInstance.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(queryForInstance_result.class, metaDataMap); } public queryForInstance_result() { } public queryForInstance_result( DiscoveryInstance success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public queryForInstance_result(queryForInstance_result other) { if (other.isSetSuccess()) { this.success = new DiscoveryInstance(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public queryForInstance_result deepCopy() { return new queryForInstance_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public DiscoveryInstance getSuccess() { return this.success; } public queryForInstance_result setSuccess(DiscoveryInstance success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public queryForInstance_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((DiscoveryInstance)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof queryForInstance_result) return this.equals((queryForInstance_result)that); return false; } public boolean equals(queryForInstance_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(queryForInstance_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("queryForInstance_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class queryForInstance_resultStandardSchemeFactory implements SchemeFactory { public queryForInstance_resultStandardScheme getScheme() { return new queryForInstance_resultStandardScheme(); } } private static class queryForInstance_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, queryForInstance_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new DiscoveryInstance(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, queryForInstance_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class queryForInstance_resultTupleSchemeFactory implements SchemeFactory { public queryForInstance_resultTupleScheme getScheme() { return new queryForInstance_resultTupleScheme(); } } private static class queryForInstance_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, queryForInstance_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, queryForInstance_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new DiscoveryInstance(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class queryForInstances_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("queryForInstances_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField DISCOVERY_PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("discoveryProjection", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)3); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new queryForInstances_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new queryForInstances_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public DiscoveryProjection discoveryProjection; // required public String name; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), DISCOVERY_PROJECTION((short)2, "discoveryProjection"), NAME((short)3, "name"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // DISCOVERY_PROJECTION return DISCOVERY_PROJECTION; case 3: // NAME return NAME; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.DISCOVERY_PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("discoveryProjection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryProjection.class))); tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(queryForInstances_args.class, metaDataMap); } public queryForInstances_args() { } public queryForInstances_args( CuratorProjection projection, DiscoveryProjection discoveryProjection, String name) { this(); this.projection = projection; this.discoveryProjection = discoveryProjection; this.name = name; } /** * Performs a deep copy on other. */ public queryForInstances_args(queryForInstances_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetDiscoveryProjection()) { this.discoveryProjection = new DiscoveryProjection(other.discoveryProjection); } if (other.isSetName()) { this.name = other.name; } } public queryForInstances_args deepCopy() { return new queryForInstances_args(this); } @Override public void clear() { this.projection = null; this.discoveryProjection = null; this.name = null; } public CuratorProjection getProjection() { return this.projection; } public queryForInstances_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public DiscoveryProjection getDiscoveryProjection() { return this.discoveryProjection; } public queryForInstances_args setDiscoveryProjection(DiscoveryProjection discoveryProjection) { this.discoveryProjection = discoveryProjection; return this; } public void unsetDiscoveryProjection() { this.discoveryProjection = null; } /** Returns true if field discoveryProjection is set (has been assigned a value) and false otherwise */ public boolean isSetDiscoveryProjection() { return this.discoveryProjection != null; } public void setDiscoveryProjectionIsSet(boolean value) { if (!value) { this.discoveryProjection = null; } } public String getName() { return this.name; } public queryForInstances_args setName(String name) { this.name = name; return this; } public void unsetName() { this.name = null; } /** Returns true if field name is set (has been assigned a value) and false otherwise */ public boolean isSetName() { return this.name != null; } public void setNameIsSet(boolean value) { if (!value) { this.name = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case DISCOVERY_PROJECTION: if (value == null) { unsetDiscoveryProjection(); } else { setDiscoveryProjection((DiscoveryProjection)value); } break; case NAME: if (value == null) { unsetName(); } else { setName((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case DISCOVERY_PROJECTION: return getDiscoveryProjection(); case NAME: return getName(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case DISCOVERY_PROJECTION: return isSetDiscoveryProjection(); case NAME: return isSetName(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof queryForInstances_args) return this.equals((queryForInstances_args)that); return false; } public boolean equals(queryForInstances_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_discoveryProjection = true && this.isSetDiscoveryProjection(); boolean that_present_discoveryProjection = true && that.isSetDiscoveryProjection(); if (this_present_discoveryProjection || that_present_discoveryProjection) { if (!(this_present_discoveryProjection && that_present_discoveryProjection)) return false; if (!this.discoveryProjection.equals(that.discoveryProjection)) return false; } boolean this_present_name = true && this.isSetName(); boolean that_present_name = true && that.isSetName(); if (this_present_name || that_present_name) { if (!(this_present_name && that_present_name)) return false; if (!this.name.equals(that.name)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(queryForInstances_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetDiscoveryProjection()).compareTo(other.isSetDiscoveryProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetDiscoveryProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.discoveryProjection, other.discoveryProjection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetName()).compareTo(other.isSetName()); if (lastComparison != 0) { return lastComparison; } if (isSetName()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("queryForInstances_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("discoveryProjection:"); if (this.discoveryProjection == null) { sb.append("null"); } else { sb.append(this.discoveryProjection); } first = false; if (!first) sb.append(", "); sb.append("name:"); if (this.name == null) { sb.append("null"); } else { sb.append(this.name); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (discoveryProjection != null) { discoveryProjection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class queryForInstances_argsStandardSchemeFactory implements SchemeFactory { public queryForInstances_argsStandardScheme getScheme() { return new queryForInstances_argsStandardScheme(); } } private static class queryForInstances_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, queryForInstances_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // DISCOVERY_PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.discoveryProjection = new DiscoveryProjection(); struct.discoveryProjection.read(iprot); struct.setDiscoveryProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.name = iprot.readString(); struct.setNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, queryForInstances_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.discoveryProjection != null) { oprot.writeFieldBegin(DISCOVERY_PROJECTION_FIELD_DESC); struct.discoveryProjection.write(oprot); oprot.writeFieldEnd(); } if (struct.name != null) { oprot.writeFieldBegin(NAME_FIELD_DESC); oprot.writeString(struct.name); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class queryForInstances_argsTupleSchemeFactory implements SchemeFactory { public queryForInstances_argsTupleScheme getScheme() { return new queryForInstances_argsTupleScheme(); } } private static class queryForInstances_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, queryForInstances_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetDiscoveryProjection()) { optionals.set(1); } if (struct.isSetName()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetDiscoveryProjection()) { struct.discoveryProjection.write(oprot); } if (struct.isSetName()) { oprot.writeString(struct.name); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, queryForInstances_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.discoveryProjection = new DiscoveryProjection(); struct.discoveryProjection.read(iprot); struct.setDiscoveryProjectionIsSet(true); } if (incoming.get(2)) { struct.name = iprot.readString(); struct.setNameIsSet(true); } } } } public static class queryForInstances_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("queryForInstances_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.LIST, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new queryForInstances_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new queryForInstances_resultTupleSchemeFactory()); } public List success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryInstance.class)))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(queryForInstances_result.class, metaDataMap); } public queryForInstances_result() { } public queryForInstances_result( List success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public queryForInstances_result(queryForInstances_result other) { if (other.isSetSuccess()) { List __this__success = new ArrayList(other.success.size()); for (DiscoveryInstance other_element : other.success) { __this__success.add(new DiscoveryInstance(other_element)); } this.success = __this__success; } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public queryForInstances_result deepCopy() { return new queryForInstances_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public int getSuccessSize() { return (this.success == null) ? 0 : this.success.size(); } public java.util.Iterator getSuccessIterator() { return (this.success == null) ? null : this.success.iterator(); } public void addToSuccess(DiscoveryInstance elem) { if (this.success == null) { this.success = new ArrayList(); } this.success.add(elem); } public List getSuccess() { return this.success; } public queryForInstances_result setSuccess(List success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public queryForInstances_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((List)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof queryForInstances_result) return this.equals((queryForInstances_result)that); return false; } public boolean equals(queryForInstances_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(queryForInstances_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("queryForInstances_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class queryForInstances_resultStandardSchemeFactory implements SchemeFactory { public queryForInstances_resultStandardScheme getScheme() { return new queryForInstances_resultStandardScheme(); } } private static class queryForInstances_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, queryForInstances_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list56 = iprot.readListBegin(); struct.success = new ArrayList(_list56.size); for (int _i57 = 0; _i57 < _list56.size; ++_i57) { DiscoveryInstance _elem58; _elem58 = new DiscoveryInstance(); _elem58.read(iprot); struct.success.add(_elem58); } iprot.readListEnd(); } struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, queryForInstances_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.success.size())); for (DiscoveryInstance _iter59 : struct.success) { _iter59.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class queryForInstances_resultTupleSchemeFactory implements SchemeFactory { public queryForInstances_resultTupleScheme getScheme() { return new queryForInstances_resultTupleScheme(); } } private static class queryForInstances_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, queryForInstances_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { { oprot.writeI32(struct.success.size()); for (DiscoveryInstance _iter60 : struct.success) { _iter60.write(oprot); } } } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, queryForInstances_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { { org.apache.thrift.protocol.TList _list61 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.success = new ArrayList(_list61.size); for (int _i62 = 0; _i62 < _list61.size; ++_i62) { DiscoveryInstance _elem63; _elem63 = new DiscoveryInstance(); _elem63.read(iprot); struct.success.add(_elem63); } } struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class queryForNames_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("queryForNames_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField DISCOVERY_PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("discoveryProjection", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new queryForNames_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new queryForNames_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public DiscoveryProjection discoveryProjection; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), DISCOVERY_PROJECTION((short)2, "discoveryProjection"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // DISCOVERY_PROJECTION return DISCOVERY_PROJECTION; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.DISCOVERY_PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("discoveryProjection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryProjection.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(queryForNames_args.class, metaDataMap); } public queryForNames_args() { } public queryForNames_args( CuratorProjection projection, DiscoveryProjection discoveryProjection) { this(); this.projection = projection; this.discoveryProjection = discoveryProjection; } /** * Performs a deep copy on other. */ public queryForNames_args(queryForNames_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetDiscoveryProjection()) { this.discoveryProjection = new DiscoveryProjection(other.discoveryProjection); } } public queryForNames_args deepCopy() { return new queryForNames_args(this); } @Override public void clear() { this.projection = null; this.discoveryProjection = null; } public CuratorProjection getProjection() { return this.projection; } public queryForNames_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public DiscoveryProjection getDiscoveryProjection() { return this.discoveryProjection; } public queryForNames_args setDiscoveryProjection(DiscoveryProjection discoveryProjection) { this.discoveryProjection = discoveryProjection; return this; } public void unsetDiscoveryProjection() { this.discoveryProjection = null; } /** Returns true if field discoveryProjection is set (has been assigned a value) and false otherwise */ public boolean isSetDiscoveryProjection() { return this.discoveryProjection != null; } public void setDiscoveryProjectionIsSet(boolean value) { if (!value) { this.discoveryProjection = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case DISCOVERY_PROJECTION: if (value == null) { unsetDiscoveryProjection(); } else { setDiscoveryProjection((DiscoveryProjection)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case DISCOVERY_PROJECTION: return getDiscoveryProjection(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case DISCOVERY_PROJECTION: return isSetDiscoveryProjection(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof queryForNames_args) return this.equals((queryForNames_args)that); return false; } public boolean equals(queryForNames_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_discoveryProjection = true && this.isSetDiscoveryProjection(); boolean that_present_discoveryProjection = true && that.isSetDiscoveryProjection(); if (this_present_discoveryProjection || that_present_discoveryProjection) { if (!(this_present_discoveryProjection && that_present_discoveryProjection)) return false; if (!this.discoveryProjection.equals(that.discoveryProjection)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(queryForNames_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetDiscoveryProjection()).compareTo(other.isSetDiscoveryProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetDiscoveryProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.discoveryProjection, other.discoveryProjection); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("queryForNames_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("discoveryProjection:"); if (this.discoveryProjection == null) { sb.append("null"); } else { sb.append(this.discoveryProjection); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (discoveryProjection != null) { discoveryProjection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class queryForNames_argsStandardSchemeFactory implements SchemeFactory { public queryForNames_argsStandardScheme getScheme() { return new queryForNames_argsStandardScheme(); } } private static class queryForNames_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, queryForNames_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // DISCOVERY_PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.discoveryProjection = new DiscoveryProjection(); struct.discoveryProjection.read(iprot); struct.setDiscoveryProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, queryForNames_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.discoveryProjection != null) { oprot.writeFieldBegin(DISCOVERY_PROJECTION_FIELD_DESC); struct.discoveryProjection.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class queryForNames_argsTupleSchemeFactory implements SchemeFactory { public queryForNames_argsTupleScheme getScheme() { return new queryForNames_argsTupleScheme(); } } private static class queryForNames_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, queryForNames_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetDiscoveryProjection()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetDiscoveryProjection()) { struct.discoveryProjection.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, queryForNames_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.discoveryProjection = new DiscoveryProjection(); struct.discoveryProjection.read(iprot); struct.setDiscoveryProjectionIsSet(true); } } } } public static class queryForNames_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("queryForNames_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.LIST, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new queryForNames_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new queryForNames_resultTupleSchemeFactory()); } public List success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(queryForNames_result.class, metaDataMap); } public queryForNames_result() { } public queryForNames_result( List success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public queryForNames_result(queryForNames_result other) { if (other.isSetSuccess()) { List __this__success = new ArrayList(other.success); this.success = __this__success; } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public queryForNames_result deepCopy() { return new queryForNames_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public int getSuccessSize() { return (this.success == null) ? 0 : this.success.size(); } public java.util.Iterator getSuccessIterator() { return (this.success == null) ? null : this.success.iterator(); } public void addToSuccess(String elem) { if (this.success == null) { this.success = new ArrayList(); } this.success.add(elem); } public List getSuccess() { return this.success; } public queryForNames_result setSuccess(List success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public queryForNames_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((List)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof queryForNames_result) return this.equals((queryForNames_result)that); return false; } public boolean equals(queryForNames_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(queryForNames_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("queryForNames_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class queryForNames_resultStandardSchemeFactory implements SchemeFactory { public queryForNames_resultStandardScheme getScheme() { return new queryForNames_resultStandardScheme(); } } private static class queryForNames_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, queryForNames_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list64 = iprot.readListBegin(); struct.success = new ArrayList(_list64.size); for (int _i65 = 0; _i65 < _list64.size; ++_i65) { String _elem66; _elem66 = iprot.readString(); struct.success.add(_elem66); } iprot.readListEnd(); } struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, queryForNames_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, struct.success.size())); for (String _iter67 : struct.success) { oprot.writeString(_iter67); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class queryForNames_resultTupleSchemeFactory implements SchemeFactory { public queryForNames_resultTupleScheme getScheme() { return new queryForNames_resultTupleScheme(); } } private static class queryForNames_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, queryForNames_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { { oprot.writeI32(struct.success.size()); for (String _iter68 : struct.success) { oprot.writeString(_iter68); } } } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, queryForNames_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { { org.apache.thrift.protocol.TList _list69 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, iprot.readI32()); struct.success = new ArrayList(_list69.size); for (int _i70 = 0; _i70 < _list69.size; ++_i70) { String _elem71; _elem71 = iprot.readString(); struct.success.add(_elem71); } } struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class registerInstance_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("registerInstance_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField DISCOVERY_PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("discoveryProjection", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final org.apache.thrift.protocol.TField INSTANCE_FIELD_DESC = new org.apache.thrift.protocol.TField("instance", org.apache.thrift.protocol.TType.STRUCT, (short)3); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new registerInstance_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new registerInstance_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public DiscoveryProjection discoveryProjection; // required public DiscoveryInstance instance; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), DISCOVERY_PROJECTION((short)2, "discoveryProjection"), INSTANCE((short)3, "instance"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // DISCOVERY_PROJECTION return DISCOVERY_PROJECTION; case 3: // INSTANCE return INSTANCE; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.DISCOVERY_PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("discoveryProjection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryProjection.class))); tmpMap.put(_Fields.INSTANCE, new org.apache.thrift.meta_data.FieldMetaData("instance", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryInstance.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(registerInstance_args.class, metaDataMap); } public registerInstance_args() { } public registerInstance_args( CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance) { this(); this.projection = projection; this.discoveryProjection = discoveryProjection; this.instance = instance; } /** * Performs a deep copy on other. */ public registerInstance_args(registerInstance_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetDiscoveryProjection()) { this.discoveryProjection = new DiscoveryProjection(other.discoveryProjection); } if (other.isSetInstance()) { this.instance = new DiscoveryInstance(other.instance); } } public registerInstance_args deepCopy() { return new registerInstance_args(this); } @Override public void clear() { this.projection = null; this.discoveryProjection = null; this.instance = null; } public CuratorProjection getProjection() { return this.projection; } public registerInstance_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public DiscoveryProjection getDiscoveryProjection() { return this.discoveryProjection; } public registerInstance_args setDiscoveryProjection(DiscoveryProjection discoveryProjection) { this.discoveryProjection = discoveryProjection; return this; } public void unsetDiscoveryProjection() { this.discoveryProjection = null; } /** Returns true if field discoveryProjection is set (has been assigned a value) and false otherwise */ public boolean isSetDiscoveryProjection() { return this.discoveryProjection != null; } public void setDiscoveryProjectionIsSet(boolean value) { if (!value) { this.discoveryProjection = null; } } public DiscoveryInstance getInstance() { return this.instance; } public registerInstance_args setInstance(DiscoveryInstance instance) { this.instance = instance; return this; } public void unsetInstance() { this.instance = null; } /** Returns true if field instance is set (has been assigned a value) and false otherwise */ public boolean isSetInstance() { return this.instance != null; } public void setInstanceIsSet(boolean value) { if (!value) { this.instance = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case DISCOVERY_PROJECTION: if (value == null) { unsetDiscoveryProjection(); } else { setDiscoveryProjection((DiscoveryProjection)value); } break; case INSTANCE: if (value == null) { unsetInstance(); } else { setInstance((DiscoveryInstance)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case DISCOVERY_PROJECTION: return getDiscoveryProjection(); case INSTANCE: return getInstance(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case DISCOVERY_PROJECTION: return isSetDiscoveryProjection(); case INSTANCE: return isSetInstance(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof registerInstance_args) return this.equals((registerInstance_args)that); return false; } public boolean equals(registerInstance_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_discoveryProjection = true && this.isSetDiscoveryProjection(); boolean that_present_discoveryProjection = true && that.isSetDiscoveryProjection(); if (this_present_discoveryProjection || that_present_discoveryProjection) { if (!(this_present_discoveryProjection && that_present_discoveryProjection)) return false; if (!this.discoveryProjection.equals(that.discoveryProjection)) return false; } boolean this_present_instance = true && this.isSetInstance(); boolean that_present_instance = true && that.isSetInstance(); if (this_present_instance || that_present_instance) { if (!(this_present_instance && that_present_instance)) return false; if (!this.instance.equals(that.instance)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(registerInstance_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetDiscoveryProjection()).compareTo(other.isSetDiscoveryProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetDiscoveryProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.discoveryProjection, other.discoveryProjection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetInstance()).compareTo(other.isSetInstance()); if (lastComparison != 0) { return lastComparison; } if (isSetInstance()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.instance, other.instance); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("registerInstance_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("discoveryProjection:"); if (this.discoveryProjection == null) { sb.append("null"); } else { sb.append(this.discoveryProjection); } first = false; if (!first) sb.append(", "); sb.append("instance:"); if (this.instance == null) { sb.append("null"); } else { sb.append(this.instance); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (discoveryProjection != null) { discoveryProjection.validate(); } if (instance != null) { instance.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class registerInstance_argsStandardSchemeFactory implements SchemeFactory { public registerInstance_argsStandardScheme getScheme() { return new registerInstance_argsStandardScheme(); } } private static class registerInstance_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, registerInstance_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // DISCOVERY_PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.discoveryProjection = new DiscoveryProjection(); struct.discoveryProjection.read(iprot); struct.setDiscoveryProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // INSTANCE if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.instance = new DiscoveryInstance(); struct.instance.read(iprot); struct.setInstanceIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, registerInstance_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.discoveryProjection != null) { oprot.writeFieldBegin(DISCOVERY_PROJECTION_FIELD_DESC); struct.discoveryProjection.write(oprot); oprot.writeFieldEnd(); } if (struct.instance != null) { oprot.writeFieldBegin(INSTANCE_FIELD_DESC); struct.instance.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class registerInstance_argsTupleSchemeFactory implements SchemeFactory { public registerInstance_argsTupleScheme getScheme() { return new registerInstance_argsTupleScheme(); } } private static class registerInstance_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, registerInstance_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetDiscoveryProjection()) { optionals.set(1); } if (struct.isSetInstance()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetDiscoveryProjection()) { struct.discoveryProjection.write(oprot); } if (struct.isSetInstance()) { struct.instance.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, registerInstance_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.discoveryProjection = new DiscoveryProjection(); struct.discoveryProjection.read(iprot); struct.setDiscoveryProjectionIsSet(true); } if (incoming.get(2)) { struct.instance = new DiscoveryInstance(); struct.instance.read(iprot); struct.setInstanceIsSet(true); } } } } public static class registerInstance_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("registerInstance_result"); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new registerInstance_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new registerInstance_resultTupleSchemeFactory()); } public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(registerInstance_result.class, metaDataMap); } public registerInstance_result() { } public registerInstance_result( CuratorException ex1) { this(); this.ex1 = ex1; } /** * Performs a deep copy on other. */ public registerInstance_result(registerInstance_result other) { if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public registerInstance_result deepCopy() { return new registerInstance_result(this); } @Override public void clear() { this.ex1 = null; } public CuratorException getEx1() { return this.ex1; } public registerInstance_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof registerInstance_result) return this.equals((registerInstance_result)that); return false; } public boolean equals(registerInstance_result that) { if (that == null) return false; boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(registerInstance_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("registerInstance_result("); boolean first = true; sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class registerInstance_resultStandardSchemeFactory implements SchemeFactory { public registerInstance_resultStandardScheme getScheme() { return new registerInstance_resultStandardScheme(); } } private static class registerInstance_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, registerInstance_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, registerInstance_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class registerInstance_resultTupleSchemeFactory implements SchemeFactory { public registerInstance_resultTupleScheme getScheme() { return new registerInstance_resultTupleScheme(); } } private static class registerInstance_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, registerInstance_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetEx1()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, registerInstance_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class unregisterInstance_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("unregisterInstance_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField DISCOVERY_PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("discoveryProjection", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final org.apache.thrift.protocol.TField INSTANCE_FIELD_DESC = new org.apache.thrift.protocol.TField("instance", org.apache.thrift.protocol.TType.STRUCT, (short)3); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new unregisterInstance_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new unregisterInstance_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public DiscoveryProjection discoveryProjection; // required public DiscoveryInstance instance; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), DISCOVERY_PROJECTION((short)2, "discoveryProjection"), INSTANCE((short)3, "instance"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // DISCOVERY_PROJECTION return DISCOVERY_PROJECTION; case 3: // INSTANCE return INSTANCE; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.DISCOVERY_PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("discoveryProjection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryProjection.class))); tmpMap.put(_Fields.INSTANCE, new org.apache.thrift.meta_data.FieldMetaData("instance", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryInstance.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(unregisterInstance_args.class, metaDataMap); } public unregisterInstance_args() { } public unregisterInstance_args( CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance) { this(); this.projection = projection; this.discoveryProjection = discoveryProjection; this.instance = instance; } /** * Performs a deep copy on other. */ public unregisterInstance_args(unregisterInstance_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetDiscoveryProjection()) { this.discoveryProjection = new DiscoveryProjection(other.discoveryProjection); } if (other.isSetInstance()) { this.instance = new DiscoveryInstance(other.instance); } } public unregisterInstance_args deepCopy() { return new unregisterInstance_args(this); } @Override public void clear() { this.projection = null; this.discoveryProjection = null; this.instance = null; } public CuratorProjection getProjection() { return this.projection; } public unregisterInstance_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public DiscoveryProjection getDiscoveryProjection() { return this.discoveryProjection; } public unregisterInstance_args setDiscoveryProjection(DiscoveryProjection discoveryProjection) { this.discoveryProjection = discoveryProjection; return this; } public void unsetDiscoveryProjection() { this.discoveryProjection = null; } /** Returns true if field discoveryProjection is set (has been assigned a value) and false otherwise */ public boolean isSetDiscoveryProjection() { return this.discoveryProjection != null; } public void setDiscoveryProjectionIsSet(boolean value) { if (!value) { this.discoveryProjection = null; } } public DiscoveryInstance getInstance() { return this.instance; } public unregisterInstance_args setInstance(DiscoveryInstance instance) { this.instance = instance; return this; } public void unsetInstance() { this.instance = null; } /** Returns true if field instance is set (has been assigned a value) and false otherwise */ public boolean isSetInstance() { return this.instance != null; } public void setInstanceIsSet(boolean value) { if (!value) { this.instance = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case DISCOVERY_PROJECTION: if (value == null) { unsetDiscoveryProjection(); } else { setDiscoveryProjection((DiscoveryProjection)value); } break; case INSTANCE: if (value == null) { unsetInstance(); } else { setInstance((DiscoveryInstance)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case DISCOVERY_PROJECTION: return getDiscoveryProjection(); case INSTANCE: return getInstance(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case DISCOVERY_PROJECTION: return isSetDiscoveryProjection(); case INSTANCE: return isSetInstance(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof unregisterInstance_args) return this.equals((unregisterInstance_args)that); return false; } public boolean equals(unregisterInstance_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_discoveryProjection = true && this.isSetDiscoveryProjection(); boolean that_present_discoveryProjection = true && that.isSetDiscoveryProjection(); if (this_present_discoveryProjection || that_present_discoveryProjection) { if (!(this_present_discoveryProjection && that_present_discoveryProjection)) return false; if (!this.discoveryProjection.equals(that.discoveryProjection)) return false; } boolean this_present_instance = true && this.isSetInstance(); boolean that_present_instance = true && that.isSetInstance(); if (this_present_instance || that_present_instance) { if (!(this_present_instance && that_present_instance)) return false; if (!this.instance.equals(that.instance)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(unregisterInstance_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetDiscoveryProjection()).compareTo(other.isSetDiscoveryProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetDiscoveryProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.discoveryProjection, other.discoveryProjection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetInstance()).compareTo(other.isSetInstance()); if (lastComparison != 0) { return lastComparison; } if (isSetInstance()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.instance, other.instance); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("unregisterInstance_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("discoveryProjection:"); if (this.discoveryProjection == null) { sb.append("null"); } else { sb.append(this.discoveryProjection); } first = false; if (!first) sb.append(", "); sb.append("instance:"); if (this.instance == null) { sb.append("null"); } else { sb.append(this.instance); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (discoveryProjection != null) { discoveryProjection.validate(); } if (instance != null) { instance.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class unregisterInstance_argsStandardSchemeFactory implements SchemeFactory { public unregisterInstance_argsStandardScheme getScheme() { return new unregisterInstance_argsStandardScheme(); } } private static class unregisterInstance_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, unregisterInstance_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // DISCOVERY_PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.discoveryProjection = new DiscoveryProjection(); struct.discoveryProjection.read(iprot); struct.setDiscoveryProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // INSTANCE if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.instance = new DiscoveryInstance(); struct.instance.read(iprot); struct.setInstanceIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, unregisterInstance_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.discoveryProjection != null) { oprot.writeFieldBegin(DISCOVERY_PROJECTION_FIELD_DESC); struct.discoveryProjection.write(oprot); oprot.writeFieldEnd(); } if (struct.instance != null) { oprot.writeFieldBegin(INSTANCE_FIELD_DESC); struct.instance.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class unregisterInstance_argsTupleSchemeFactory implements SchemeFactory { public unregisterInstance_argsTupleScheme getScheme() { return new unregisterInstance_argsTupleScheme(); } } private static class unregisterInstance_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, unregisterInstance_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetDiscoveryProjection()) { optionals.set(1); } if (struct.isSetInstance()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetDiscoveryProjection()) { struct.discoveryProjection.write(oprot); } if (struct.isSetInstance()) { struct.instance.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, unregisterInstance_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.discoveryProjection = new DiscoveryProjection(); struct.discoveryProjection.read(iprot); struct.setDiscoveryProjectionIsSet(true); } if (incoming.get(2)) { struct.instance = new DiscoveryInstance(); struct.instance.read(iprot); struct.setInstanceIsSet(true); } } } } public static class unregisterInstance_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("unregisterInstance_result"); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new unregisterInstance_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new unregisterInstance_resultTupleSchemeFactory()); } public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(unregisterInstance_result.class, metaDataMap); } public unregisterInstance_result() { } public unregisterInstance_result( CuratorException ex1) { this(); this.ex1 = ex1; } /** * Performs a deep copy on other. */ public unregisterInstance_result(unregisterInstance_result other) { if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public unregisterInstance_result deepCopy() { return new unregisterInstance_result(this); } @Override public void clear() { this.ex1 = null; } public CuratorException getEx1() { return this.ex1; } public unregisterInstance_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof unregisterInstance_result) return this.equals((unregisterInstance_result)that); return false; } public boolean equals(unregisterInstance_result that) { if (that == null) return false; boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(unregisterInstance_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("unregisterInstance_result("); boolean first = true; sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class unregisterInstance_resultStandardSchemeFactory implements SchemeFactory { public unregisterInstance_resultStandardScheme getScheme() { return new unregisterInstance_resultStandardScheme(); } } private static class unregisterInstance_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, unregisterInstance_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, unregisterInstance_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class unregisterInstance_resultTupleSchemeFactory implements SchemeFactory { public unregisterInstance_resultTupleScheme getScheme() { return new unregisterInstance_resultTupleScheme(); } } private static class unregisterInstance_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, unregisterInstance_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetEx1()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, unregisterInstance_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } public static class updateInstance_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("updateInstance_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField DISCOVERY_PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("discoveryProjection", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final org.apache.thrift.protocol.TField INSTANCE_FIELD_DESC = new org.apache.thrift.protocol.TField("instance", org.apache.thrift.protocol.TType.STRUCT, (short)3); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new updateInstance_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new updateInstance_argsTupleSchemeFactory()); } public CuratorProjection projection; // required public DiscoveryProjection discoveryProjection; // required public DiscoveryInstance instance; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), DISCOVERY_PROJECTION((short)2, "discoveryProjection"), INSTANCE((short)3, "instance"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // DISCOVERY_PROJECTION return DISCOVERY_PROJECTION; case 3: // INSTANCE return INSTANCE; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); tmpMap.put(_Fields.DISCOVERY_PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("discoveryProjection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryProjection.class))); tmpMap.put(_Fields.INSTANCE, new org.apache.thrift.meta_data.FieldMetaData("instance", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DiscoveryInstance.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(updateInstance_args.class, metaDataMap); } public updateInstance_args() { } public updateInstance_args( CuratorProjection projection, DiscoveryProjection discoveryProjection, DiscoveryInstance instance) { this(); this.projection = projection; this.discoveryProjection = discoveryProjection; this.instance = instance; } /** * Performs a deep copy on other. */ public updateInstance_args(updateInstance_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } if (other.isSetDiscoveryProjection()) { this.discoveryProjection = new DiscoveryProjection(other.discoveryProjection); } if (other.isSetInstance()) { this.instance = new DiscoveryInstance(other.instance); } } public updateInstance_args deepCopy() { return new updateInstance_args(this); } @Override public void clear() { this.projection = null; this.discoveryProjection = null; this.instance = null; } public CuratorProjection getProjection() { return this.projection; } public updateInstance_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public DiscoveryProjection getDiscoveryProjection() { return this.discoveryProjection; } public updateInstance_args setDiscoveryProjection(DiscoveryProjection discoveryProjection) { this.discoveryProjection = discoveryProjection; return this; } public void unsetDiscoveryProjection() { this.discoveryProjection = null; } /** Returns true if field discoveryProjection is set (has been assigned a value) and false otherwise */ public boolean isSetDiscoveryProjection() { return this.discoveryProjection != null; } public void setDiscoveryProjectionIsSet(boolean value) { if (!value) { this.discoveryProjection = null; } } public DiscoveryInstance getInstance() { return this.instance; } public updateInstance_args setInstance(DiscoveryInstance instance) { this.instance = instance; return this; } public void unsetInstance() { this.instance = null; } /** Returns true if field instance is set (has been assigned a value) and false otherwise */ public boolean isSetInstance() { return this.instance != null; } public void setInstanceIsSet(boolean value) { if (!value) { this.instance = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; case DISCOVERY_PROJECTION: if (value == null) { unsetDiscoveryProjection(); } else { setDiscoveryProjection((DiscoveryProjection)value); } break; case INSTANCE: if (value == null) { unsetInstance(); } else { setInstance((DiscoveryInstance)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case DISCOVERY_PROJECTION: return getDiscoveryProjection(); case INSTANCE: return getInstance(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case DISCOVERY_PROJECTION: return isSetDiscoveryProjection(); case INSTANCE: return isSetInstance(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof updateInstance_args) return this.equals((updateInstance_args)that); return false; } public boolean equals(updateInstance_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_discoveryProjection = true && this.isSetDiscoveryProjection(); boolean that_present_discoveryProjection = true && that.isSetDiscoveryProjection(); if (this_present_discoveryProjection || that_present_discoveryProjection) { if (!(this_present_discoveryProjection && that_present_discoveryProjection)) return false; if (!this.discoveryProjection.equals(that.discoveryProjection)) return false; } boolean this_present_instance = true && this.isSetInstance(); boolean that_present_instance = true && that.isSetInstance(); if (this_present_instance || that_present_instance) { if (!(this_present_instance && that_present_instance)) return false; if (!this.instance.equals(that.instance)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(updateInstance_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetDiscoveryProjection()).compareTo(other.isSetDiscoveryProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetDiscoveryProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.discoveryProjection, other.discoveryProjection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetInstance()).compareTo(other.isSetInstance()); if (lastComparison != 0) { return lastComparison; } if (isSetInstance()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.instance, other.instance); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("updateInstance_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("discoveryProjection:"); if (this.discoveryProjection == null) { sb.append("null"); } else { sb.append(this.discoveryProjection); } first = false; if (!first) sb.append(", "); sb.append("instance:"); if (this.instance == null) { sb.append("null"); } else { sb.append(this.instance); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } if (discoveryProjection != null) { discoveryProjection.validate(); } if (instance != null) { instance.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class updateInstance_argsStandardSchemeFactory implements SchemeFactory { public updateInstance_argsStandardScheme getScheme() { return new updateInstance_argsStandardScheme(); } } private static class updateInstance_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, updateInstance_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // DISCOVERY_PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.discoveryProjection = new DiscoveryProjection(); struct.discoveryProjection.read(iprot); struct.setDiscoveryProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // INSTANCE if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.instance = new DiscoveryInstance(); struct.instance.read(iprot); struct.setInstanceIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, updateInstance_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } if (struct.discoveryProjection != null) { oprot.writeFieldBegin(DISCOVERY_PROJECTION_FIELD_DESC); struct.discoveryProjection.write(oprot); oprot.writeFieldEnd(); } if (struct.instance != null) { oprot.writeFieldBegin(INSTANCE_FIELD_DESC); struct.instance.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class updateInstance_argsTupleSchemeFactory implements SchemeFactory { public updateInstance_argsTupleScheme getScheme() { return new updateInstance_argsTupleScheme(); } } private static class updateInstance_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, updateInstance_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetDiscoveryProjection()) { optionals.set(1); } if (struct.isSetInstance()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetDiscoveryProjection()) { struct.discoveryProjection.write(oprot); } if (struct.isSetInstance()) { struct.instance.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, updateInstance_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.discoveryProjection = new DiscoveryProjection(); struct.discoveryProjection.read(iprot); struct.setDiscoveryProjectionIsSet(true); } if (incoming.get(2)) { struct.instance = new DiscoveryInstance(); struct.instance.read(iprot); struct.setInstanceIsSet(true); } } } } public static class updateInstance_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("updateInstance_result"); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new updateInstance_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new updateInstance_resultTupleSchemeFactory()); } public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(updateInstance_result.class, metaDataMap); } public updateInstance_result() { } public updateInstance_result( CuratorException ex1) { this(); this.ex1 = ex1; } /** * Performs a deep copy on other. */ public updateInstance_result(updateInstance_result other) { if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public updateInstance_result deepCopy() { return new updateInstance_result(this); } @Override public void clear() { this.ex1 = null; } public CuratorException getEx1() { return this.ex1; } public updateInstance_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof updateInstance_result) return this.equals((updateInstance_result)that); return false; } public boolean equals(updateInstance_result that) { if (that == null) return false; boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(updateInstance_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("updateInstance_result("); boolean first = true; sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class updateInstance_resultStandardSchemeFactory implements SchemeFactory { public updateInstance_resultStandardScheme getScheme() { return new updateInstance_resultStandardScheme(); } } private static class updateInstance_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, updateInstance_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, updateInstance_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class updateInstance_resultTupleSchemeFactory implements SchemeFactory { public updateInstance_resultTupleScheme getScheme() { return new updateInstance_resultTupleScheme(); } } private static class updateInstance_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, updateInstance_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetEx1()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, updateInstance_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } } EventService.java000066400000000000000000001110341245521677600341230ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class EventService { public interface Iface { public CuratorEvent getNextEvent(CuratorProjection projection) throws CuratorException, org.apache.thrift.TException; } public interface AsyncIface { public void getNextEvent(CuratorProjection projection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; } public static class Client extends org.apache.thrift.TServiceClient implements Iface { public static class Factory implements org.apache.thrift.TServiceClientFactory { public Factory() {} public Client getClient(org.apache.thrift.protocol.TProtocol prot) { return new Client(prot); } public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { return new Client(iprot, oprot); } } public Client(org.apache.thrift.protocol.TProtocol prot) { super(prot, prot); } public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { super(iprot, oprot); } public CuratorEvent getNextEvent(CuratorProjection projection) throws CuratorException, org.apache.thrift.TException { send_getNextEvent(projection); return recv_getNextEvent(); } public void send_getNextEvent(CuratorProjection projection) throws org.apache.thrift.TException { getNextEvent_args args = new getNextEvent_args(); args.setProjection(projection); sendBase("getNextEvent", args); } public CuratorEvent recv_getNextEvent() throws CuratorException, org.apache.thrift.TException { getNextEvent_result result = new getNextEvent_result(); receiveBase(result, "getNextEvent"); if (result.isSetSuccess()) { return result.success; } if (result.ex1 != null) { throw result.ex1; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getNextEvent failed: unknown result"); } } public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface { public static class Factory implements org.apache.thrift.async.TAsyncClientFactory { private org.apache.thrift.async.TAsyncClientManager clientManager; private org.apache.thrift.protocol.TProtocolFactory protocolFactory; public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) { this.clientManager = clientManager; this.protocolFactory = protocolFactory; } public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) { return new AsyncClient(protocolFactory, clientManager, transport); } } public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) { super(protocolFactory, clientManager, transport); } public void getNextEvent(CuratorProjection projection, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); getNextEvent_call method_call = new getNextEvent_call(projection, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class getNextEvent_call extends org.apache.thrift.async.TAsyncMethodCall { private CuratorProjection projection; public getNextEvent_call(CuratorProjection projection, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.projection = projection; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getNextEvent", org.apache.thrift.protocol.TMessageType.CALL, 0)); getNextEvent_args args = new getNextEvent_args(); args.setProjection(projection); args.write(prot); prot.writeMessageEnd(); } public CuratorEvent getResult() throws CuratorException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_getNextEvent(); } } } public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName()); public Processor(I iface) { super(iface, getProcessMap(new HashMap>())); } protected Processor(I iface, Map> processMap) { super(iface, getProcessMap(processMap)); } private static Map> getProcessMap(Map> processMap) { processMap.put("getNextEvent", new getNextEvent()); return processMap; } public static class getNextEvent extends org.apache.thrift.ProcessFunction { public getNextEvent() { super("getNextEvent"); } public getNextEvent_args getEmptyArgsInstance() { return new getNextEvent_args(); } protected boolean isOneway() { return false; } public getNextEvent_result getResult(I iface, getNextEvent_args args) throws org.apache.thrift.TException { getNextEvent_result result = new getNextEvent_result(); try { result.success = iface.getNextEvent(args.projection); } catch (CuratorException ex1) { result.ex1 = ex1; } return result; } } } public static class AsyncProcessor extends org.apache.thrift.TBaseAsyncProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName()); public AsyncProcessor(I iface) { super(iface, getProcessMap(new HashMap>())); } protected AsyncProcessor(I iface, Map> processMap) { super(iface, getProcessMap(processMap)); } private static Map> getProcessMap(Map> processMap) { processMap.put("getNextEvent", new getNextEvent()); return processMap; } public static class getNextEvent extends org.apache.thrift.AsyncProcessFunction { public getNextEvent() { super("getNextEvent"); } public getNextEvent_args getEmptyArgsInstance() { return new getNextEvent_args(); } public AsyncMethodCallback getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback() { public void onComplete(CuratorEvent o) { getNextEvent_result result = new getNextEvent_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; getNextEvent_result result = new getNextEvent_result(); if (e instanceof CuratorException) { result.ex1 = (CuratorException) e; result.setEx1IsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, getNextEvent_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws TException { iface.getNextEvent(args.projection,resultHandler); } } } public static class getNextEvent_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getNextEvent_args"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getNextEvent_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new getNextEvent_argsTupleSchemeFactory()); } public CuratorProjection projection; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorProjection.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getNextEvent_args.class, metaDataMap); } public getNextEvent_args() { } public getNextEvent_args( CuratorProjection projection) { this(); this.projection = projection; } /** * Performs a deep copy on other. */ public getNextEvent_args(getNextEvent_args other) { if (other.isSetProjection()) { this.projection = new CuratorProjection(other.projection); } } public getNextEvent_args deepCopy() { return new getNextEvent_args(this); } @Override public void clear() { this.projection = null; } public CuratorProjection getProjection() { return this.projection; } public getNextEvent_args setProjection(CuratorProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((CuratorProjection)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getNextEvent_args) return this.equals((getNextEvent_args)that); return false; } public boolean equals(getNextEvent_args that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getNextEvent_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getNextEvent_args("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getNextEvent_argsStandardSchemeFactory implements SchemeFactory { public getNextEvent_argsStandardScheme getScheme() { return new getNextEvent_argsStandardScheme(); } } private static class getNextEvent_argsStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getNextEvent_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getNextEvent_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getNextEvent_argsTupleSchemeFactory implements SchemeFactory { public getNextEvent_argsTupleScheme getScheme() { return new getNextEvent_argsTupleScheme(); } } private static class getNextEvent_argsTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getNextEvent_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetProjection()) { struct.projection.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getNextEvent_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.projection = new CuratorProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } } } } public static class getNextEvent_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getNextEvent_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getNextEvent_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new getNextEvent_resultTupleSchemeFactory()); } public CuratorEvent success; // required public CuratorException ex1; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), EX1((short)1, "ex1"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // EX1 return EX1; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CuratorEvent.class))); tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getNextEvent_result.class, metaDataMap); } public getNextEvent_result() { } public getNextEvent_result( CuratorEvent success, CuratorException ex1) { this(); this.success = success; this.ex1 = ex1; } /** * Performs a deep copy on other. */ public getNextEvent_result(getNextEvent_result other) { if (other.isSetSuccess()) { this.success = new CuratorEvent(other.success); } if (other.isSetEx1()) { this.ex1 = new CuratorException(other.ex1); } } public getNextEvent_result deepCopy() { return new getNextEvent_result(this); } @Override public void clear() { this.success = null; this.ex1 = null; } public CuratorEvent getSuccess() { return this.success; } public getNextEvent_result setSuccess(CuratorEvent success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public CuratorException getEx1() { return this.ex1; } public getNextEvent_result setEx1(CuratorException ex1) { this.ex1 = ex1; return this; } public void unsetEx1() { this.ex1 = null; } /** Returns true if field ex1 is set (has been assigned a value) and false otherwise */ public boolean isSetEx1() { return this.ex1 != null; } public void setEx1IsSet(boolean value) { if (!value) { this.ex1 = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((CuratorEvent)value); } break; case EX1: if (value == null) { unsetEx1(); } else { setEx1((CuratorException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case EX1: return getEx1(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case EX1: return isSetEx1(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getNextEvent_result) return this.equals((getNextEvent_result)that); return false; } public boolean equals(getNextEvent_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_ex1 = true && this.isSetEx1(); boolean that_present_ex1 = true && that.isSetEx1(); if (this_present_ex1 || that_present_ex1) { if (!(this_present_ex1 && that_present_ex1)) return false; if (!this.ex1.equals(that.ex1)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(getNextEvent_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1()); if (lastComparison != 0) { return lastComparison; } if (isSetEx1()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getNextEvent_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("ex1:"); if (this.ex1 == null) { sb.append("null"); } else { sb.append(this.ex1); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getNextEvent_resultStandardSchemeFactory implements SchemeFactory { public getNextEvent_resultStandardScheme getScheme() { return new getNextEvent_resultStandardScheme(); } } private static class getNextEvent_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getNextEvent_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new CuratorEvent(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // EX1 if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getNextEvent_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.ex1 != null) { oprot.writeFieldBegin(EX1_FIELD_DESC); struct.ex1.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getNextEvent_resultTupleSchemeFactory implements SchemeFactory { public getNextEvent_resultTupleScheme getScheme() { return new getNextEvent_resultTupleScheme(); } } private static class getNextEvent_resultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getNextEvent_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetEx1()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetEx1()) { struct.ex1.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getNextEvent_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new CuratorEvent(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.ex1 = new CuratorException(); struct.ex1.read(iprot); struct.setEx1IsSet(true); } } } } } curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/EventType.java000066400000000000000000000021311245521677600335200ustar00rootroot00000000000000/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import java.util.Map; import java.util.HashMap; import org.apache.thrift.TEnum; public enum EventType implements org.apache.thrift.TEnum { None(0), NodeCreated(1), NodeDeleted(2), NodeDataChanged(3), NodeChildrenChanged(4); private final int value; private EventType(int value) { this.value = value; } /** * Get the integer value of this enum value, as defined in the Thrift IDL. */ public int getValue() { return value; } /** * Find a the enum type by its integer value, as defined in the Thrift IDL. * @return null if the value is not found. */ public static EventType findByValue(int value) { switch (value) { case 0: return None; case 1: return NodeCreated; case 2: return NodeDeleted; case 3: return NodeDataChanged; case 4: return NodeChildrenChanged; default: return null; } } } ExceptionType.java000066400000000000000000000017111245521677600343210ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import java.util.Map; import java.util.HashMap; import org.apache.thrift.TEnum; public enum ExceptionType implements org.apache.thrift.TEnum { GENERAL(0), ZOOKEEPER(1), NODE(2); private final int value; private ExceptionType(int value) { this.value = value; } /** * Get the integer value of this enum value, as defined in the Thrift IDL. */ public int getValue() { return value; } /** * Find a the enum type by its integer value, as defined in the Thrift IDL. * @return null if the value is not found. */ public static ExceptionType findByValue(int value) { switch (value) { case 0: return GENERAL; case 1: return ZOOKEEPER; case 2: return NODE; default: return null; } } } ExistsSpec.java000066400000000000000000000431431245521677600336200ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ExistsSpec implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ExistsSpec"); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField WATCHED_FIELD_DESC = new org.apache.thrift.protocol.TField("watched", org.apache.thrift.protocol.TType.BOOL, (short)2); private static final org.apache.thrift.protocol.TField ASYNC_CONTEXT_FIELD_DESC = new org.apache.thrift.protocol.TField("asyncContext", org.apache.thrift.protocol.TType.STRING, (short)3); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new ExistsSpecStandardSchemeFactory()); schemes.put(TupleScheme.class, new ExistsSpecTupleSchemeFactory()); } public String path; // required public boolean watched; // required public String asyncContext; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PATH((short)1, "path"), WATCHED((short)2, "watched"), ASYNC_CONTEXT((short)3, "asyncContext"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PATH return PATH; case 2: // WATCHED return WATCHED; case 3: // ASYNC_CONTEXT return ASYNC_CONTEXT; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __WATCHED_ISSET_ID = 0; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.WATCHED, new org.apache.thrift.meta_data.FieldMetaData("watched", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.ASYNC_CONTEXT, new org.apache.thrift.meta_data.FieldMetaData("asyncContext", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ExistsSpec.class, metaDataMap); } public ExistsSpec() { } public ExistsSpec( String path, boolean watched, String asyncContext) { this(); this.path = path; this.watched = watched; setWatchedIsSet(true); this.asyncContext = asyncContext; } /** * Performs a deep copy on other. */ public ExistsSpec(ExistsSpec other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetPath()) { this.path = other.path; } this.watched = other.watched; if (other.isSetAsyncContext()) { this.asyncContext = other.asyncContext; } } public ExistsSpec deepCopy() { return new ExistsSpec(this); } @Override public void clear() { this.path = null; setWatchedIsSet(false); this.watched = false; this.asyncContext = null; } public String getPath() { return this.path; } public ExistsSpec setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public boolean isWatched() { return this.watched; } public ExistsSpec setWatched(boolean watched) { this.watched = watched; setWatchedIsSet(true); return this; } public void unsetWatched() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __WATCHED_ISSET_ID); } /** Returns true if field watched is set (has been assigned a value) and false otherwise */ public boolean isSetWatched() { return EncodingUtils.testBit(__isset_bitfield, __WATCHED_ISSET_ID); } public void setWatchedIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __WATCHED_ISSET_ID, value); } public String getAsyncContext() { return this.asyncContext; } public ExistsSpec setAsyncContext(String asyncContext) { this.asyncContext = asyncContext; return this; } public void unsetAsyncContext() { this.asyncContext = null; } /** Returns true if field asyncContext is set (has been assigned a value) and false otherwise */ public boolean isSetAsyncContext() { return this.asyncContext != null; } public void setAsyncContextIsSet(boolean value) { if (!value) { this.asyncContext = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; case WATCHED: if (value == null) { unsetWatched(); } else { setWatched((Boolean)value); } break; case ASYNC_CONTEXT: if (value == null) { unsetAsyncContext(); } else { setAsyncContext((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PATH: return getPath(); case WATCHED: return Boolean.valueOf(isWatched()); case ASYNC_CONTEXT: return getAsyncContext(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PATH: return isSetPath(); case WATCHED: return isSetWatched(); case ASYNC_CONTEXT: return isSetAsyncContext(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof ExistsSpec) return this.equals((ExistsSpec)that); return false; } public boolean equals(ExistsSpec that) { if (that == null) return false; boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } boolean this_present_watched = true; boolean that_present_watched = true; if (this_present_watched || that_present_watched) { if (!(this_present_watched && that_present_watched)) return false; if (this.watched != that.watched) return false; } boolean this_present_asyncContext = true && this.isSetAsyncContext(); boolean that_present_asyncContext = true && that.isSetAsyncContext(); if (this_present_asyncContext || that_present_asyncContext) { if (!(this_present_asyncContext && that_present_asyncContext)) return false; if (!this.asyncContext.equals(that.asyncContext)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(ExistsSpec other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetWatched()).compareTo(other.isSetWatched()); if (lastComparison != 0) { return lastComparison; } if (isSetWatched()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.watched, other.watched); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetAsyncContext()).compareTo(other.isSetAsyncContext()); if (lastComparison != 0) { return lastComparison; } if (isSetAsyncContext()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.asyncContext, other.asyncContext); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("ExistsSpec("); boolean first = true; sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; if (!first) sb.append(", "); sb.append("watched:"); sb.append(this.watched); first = false; if (!first) sb.append(", "); sb.append("asyncContext:"); if (this.asyncContext == null) { sb.append("null"); } else { sb.append(this.asyncContext); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class ExistsSpecStandardSchemeFactory implements SchemeFactory { public ExistsSpecStandardScheme getScheme() { return new ExistsSpecStandardScheme(); } } private static class ExistsSpecStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, ExistsSpec struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // WATCHED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.watched = iprot.readBool(); struct.setWatchedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // ASYNC_CONTEXT if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.asyncContext = iprot.readString(); struct.setAsyncContextIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, ExistsSpec struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } oprot.writeFieldBegin(WATCHED_FIELD_DESC); oprot.writeBool(struct.watched); oprot.writeFieldEnd(); if (struct.asyncContext != null) { oprot.writeFieldBegin(ASYNC_CONTEXT_FIELD_DESC); oprot.writeString(struct.asyncContext); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class ExistsSpecTupleSchemeFactory implements SchemeFactory { public ExistsSpecTupleScheme getScheme() { return new ExistsSpecTupleScheme(); } } private static class ExistsSpecTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, ExistsSpec struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetPath()) { optionals.set(0); } if (struct.isSetWatched()) { optionals.set(1); } if (struct.isSetAsyncContext()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetPath()) { oprot.writeString(struct.path); } if (struct.isSetWatched()) { oprot.writeBool(struct.watched); } if (struct.isSetAsyncContext()) { oprot.writeString(struct.asyncContext); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, ExistsSpec struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } if (incoming.get(1)) { struct.watched = iprot.readBool(); struct.setWatchedIsSet(true); } if (incoming.get(2)) { struct.asyncContext = iprot.readString(); struct.setAsyncContextIsSet(true); } } } } GetChildrenSpec.java000066400000000000000000000434271245521677600345360ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GetChildrenSpec implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("GetChildrenSpec"); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField WATCHED_FIELD_DESC = new org.apache.thrift.protocol.TField("watched", org.apache.thrift.protocol.TType.BOOL, (short)2); private static final org.apache.thrift.protocol.TField ASYNC_CONTEXT_FIELD_DESC = new org.apache.thrift.protocol.TField("asyncContext", org.apache.thrift.protocol.TType.STRING, (short)3); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new GetChildrenSpecStandardSchemeFactory()); schemes.put(TupleScheme.class, new GetChildrenSpecTupleSchemeFactory()); } public String path; // required public boolean watched; // required public String asyncContext; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PATH((short)1, "path"), WATCHED((short)2, "watched"), ASYNC_CONTEXT((short)3, "asyncContext"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PATH return PATH; case 2: // WATCHED return WATCHED; case 3: // ASYNC_CONTEXT return ASYNC_CONTEXT; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __WATCHED_ISSET_ID = 0; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.WATCHED, new org.apache.thrift.meta_data.FieldMetaData("watched", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.ASYNC_CONTEXT, new org.apache.thrift.meta_data.FieldMetaData("asyncContext", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(GetChildrenSpec.class, metaDataMap); } public GetChildrenSpec() { } public GetChildrenSpec( String path, boolean watched, String asyncContext) { this(); this.path = path; this.watched = watched; setWatchedIsSet(true); this.asyncContext = asyncContext; } /** * Performs a deep copy on other. */ public GetChildrenSpec(GetChildrenSpec other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetPath()) { this.path = other.path; } this.watched = other.watched; if (other.isSetAsyncContext()) { this.asyncContext = other.asyncContext; } } public GetChildrenSpec deepCopy() { return new GetChildrenSpec(this); } @Override public void clear() { this.path = null; setWatchedIsSet(false); this.watched = false; this.asyncContext = null; } public String getPath() { return this.path; } public GetChildrenSpec setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public boolean isWatched() { return this.watched; } public GetChildrenSpec setWatched(boolean watched) { this.watched = watched; setWatchedIsSet(true); return this; } public void unsetWatched() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __WATCHED_ISSET_ID); } /** Returns true if field watched is set (has been assigned a value) and false otherwise */ public boolean isSetWatched() { return EncodingUtils.testBit(__isset_bitfield, __WATCHED_ISSET_ID); } public void setWatchedIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __WATCHED_ISSET_ID, value); } public String getAsyncContext() { return this.asyncContext; } public GetChildrenSpec setAsyncContext(String asyncContext) { this.asyncContext = asyncContext; return this; } public void unsetAsyncContext() { this.asyncContext = null; } /** Returns true if field asyncContext is set (has been assigned a value) and false otherwise */ public boolean isSetAsyncContext() { return this.asyncContext != null; } public void setAsyncContextIsSet(boolean value) { if (!value) { this.asyncContext = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; case WATCHED: if (value == null) { unsetWatched(); } else { setWatched((Boolean)value); } break; case ASYNC_CONTEXT: if (value == null) { unsetAsyncContext(); } else { setAsyncContext((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PATH: return getPath(); case WATCHED: return Boolean.valueOf(isWatched()); case ASYNC_CONTEXT: return getAsyncContext(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PATH: return isSetPath(); case WATCHED: return isSetWatched(); case ASYNC_CONTEXT: return isSetAsyncContext(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof GetChildrenSpec) return this.equals((GetChildrenSpec)that); return false; } public boolean equals(GetChildrenSpec that) { if (that == null) return false; boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } boolean this_present_watched = true; boolean that_present_watched = true; if (this_present_watched || that_present_watched) { if (!(this_present_watched && that_present_watched)) return false; if (this.watched != that.watched) return false; } boolean this_present_asyncContext = true && this.isSetAsyncContext(); boolean that_present_asyncContext = true && that.isSetAsyncContext(); if (this_present_asyncContext || that_present_asyncContext) { if (!(this_present_asyncContext && that_present_asyncContext)) return false; if (!this.asyncContext.equals(that.asyncContext)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(GetChildrenSpec other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetWatched()).compareTo(other.isSetWatched()); if (lastComparison != 0) { return lastComparison; } if (isSetWatched()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.watched, other.watched); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetAsyncContext()).compareTo(other.isSetAsyncContext()); if (lastComparison != 0) { return lastComparison; } if (isSetAsyncContext()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.asyncContext, other.asyncContext); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("GetChildrenSpec("); boolean first = true; sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; if (!first) sb.append(", "); sb.append("watched:"); sb.append(this.watched); first = false; if (!first) sb.append(", "); sb.append("asyncContext:"); if (this.asyncContext == null) { sb.append("null"); } else { sb.append(this.asyncContext); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class GetChildrenSpecStandardSchemeFactory implements SchemeFactory { public GetChildrenSpecStandardScheme getScheme() { return new GetChildrenSpecStandardScheme(); } } private static class GetChildrenSpecStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, GetChildrenSpec struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // WATCHED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.watched = iprot.readBool(); struct.setWatchedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // ASYNC_CONTEXT if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.asyncContext = iprot.readString(); struct.setAsyncContextIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, GetChildrenSpec struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } oprot.writeFieldBegin(WATCHED_FIELD_DESC); oprot.writeBool(struct.watched); oprot.writeFieldEnd(); if (struct.asyncContext != null) { oprot.writeFieldBegin(ASYNC_CONTEXT_FIELD_DESC); oprot.writeString(struct.asyncContext); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class GetChildrenSpecTupleSchemeFactory implements SchemeFactory { public GetChildrenSpecTupleScheme getScheme() { return new GetChildrenSpecTupleScheme(); } } private static class GetChildrenSpecTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, GetChildrenSpec struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetPath()) { optionals.set(0); } if (struct.isSetWatched()) { optionals.set(1); } if (struct.isSetAsyncContext()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetPath()) { oprot.writeString(struct.path); } if (struct.isSetWatched()) { oprot.writeBool(struct.watched); } if (struct.isSetAsyncContext()) { oprot.writeString(struct.asyncContext); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, GetChildrenSpec struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } if (incoming.get(1)) { struct.watched = iprot.readBool(); struct.setWatchedIsSet(true); } if (incoming.get(2)) { struct.asyncContext = iprot.readString(); struct.setAsyncContextIsSet(true); } } } } GetDataSpec.java000066400000000000000000000520111245521677600336440ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GetDataSpec implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("GetDataSpec"); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField WATCHED_FIELD_DESC = new org.apache.thrift.protocol.TField("watched", org.apache.thrift.protocol.TType.BOOL, (short)2); private static final org.apache.thrift.protocol.TField ASYNC_CONTEXT_FIELD_DESC = new org.apache.thrift.protocol.TField("asyncContext", org.apache.thrift.protocol.TType.STRING, (short)3); private static final org.apache.thrift.protocol.TField DECOMPRESSED_FIELD_DESC = new org.apache.thrift.protocol.TField("decompressed", org.apache.thrift.protocol.TType.BOOL, (short)4); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new GetDataSpecStandardSchemeFactory()); schemes.put(TupleScheme.class, new GetDataSpecTupleSchemeFactory()); } public String path; // required public boolean watched; // required public String asyncContext; // required public boolean decompressed; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PATH((short)1, "path"), WATCHED((short)2, "watched"), ASYNC_CONTEXT((short)3, "asyncContext"), DECOMPRESSED((short)4, "decompressed"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PATH return PATH; case 2: // WATCHED return WATCHED; case 3: // ASYNC_CONTEXT return ASYNC_CONTEXT; case 4: // DECOMPRESSED return DECOMPRESSED; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __WATCHED_ISSET_ID = 0; private static final int __DECOMPRESSED_ISSET_ID = 1; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.WATCHED, new org.apache.thrift.meta_data.FieldMetaData("watched", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.ASYNC_CONTEXT, new org.apache.thrift.meta_data.FieldMetaData("asyncContext", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.DECOMPRESSED, new org.apache.thrift.meta_data.FieldMetaData("decompressed", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(GetDataSpec.class, metaDataMap); } public GetDataSpec() { } public GetDataSpec( String path, boolean watched, String asyncContext, boolean decompressed) { this(); this.path = path; this.watched = watched; setWatchedIsSet(true); this.asyncContext = asyncContext; this.decompressed = decompressed; setDecompressedIsSet(true); } /** * Performs a deep copy on other. */ public GetDataSpec(GetDataSpec other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetPath()) { this.path = other.path; } this.watched = other.watched; if (other.isSetAsyncContext()) { this.asyncContext = other.asyncContext; } this.decompressed = other.decompressed; } public GetDataSpec deepCopy() { return new GetDataSpec(this); } @Override public void clear() { this.path = null; setWatchedIsSet(false); this.watched = false; this.asyncContext = null; setDecompressedIsSet(false); this.decompressed = false; } public String getPath() { return this.path; } public GetDataSpec setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public boolean isWatched() { return this.watched; } public GetDataSpec setWatched(boolean watched) { this.watched = watched; setWatchedIsSet(true); return this; } public void unsetWatched() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __WATCHED_ISSET_ID); } /** Returns true if field watched is set (has been assigned a value) and false otherwise */ public boolean isSetWatched() { return EncodingUtils.testBit(__isset_bitfield, __WATCHED_ISSET_ID); } public void setWatchedIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __WATCHED_ISSET_ID, value); } public String getAsyncContext() { return this.asyncContext; } public GetDataSpec setAsyncContext(String asyncContext) { this.asyncContext = asyncContext; return this; } public void unsetAsyncContext() { this.asyncContext = null; } /** Returns true if field asyncContext is set (has been assigned a value) and false otherwise */ public boolean isSetAsyncContext() { return this.asyncContext != null; } public void setAsyncContextIsSet(boolean value) { if (!value) { this.asyncContext = null; } } public boolean isDecompressed() { return this.decompressed; } public GetDataSpec setDecompressed(boolean decompressed) { this.decompressed = decompressed; setDecompressedIsSet(true); return this; } public void unsetDecompressed() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __DECOMPRESSED_ISSET_ID); } /** Returns true if field decompressed is set (has been assigned a value) and false otherwise */ public boolean isSetDecompressed() { return EncodingUtils.testBit(__isset_bitfield, __DECOMPRESSED_ISSET_ID); } public void setDecompressedIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __DECOMPRESSED_ISSET_ID, value); } public void setFieldValue(_Fields field, Object value) { switch (field) { case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; case WATCHED: if (value == null) { unsetWatched(); } else { setWatched((Boolean)value); } break; case ASYNC_CONTEXT: if (value == null) { unsetAsyncContext(); } else { setAsyncContext((String)value); } break; case DECOMPRESSED: if (value == null) { unsetDecompressed(); } else { setDecompressed((Boolean)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PATH: return getPath(); case WATCHED: return Boolean.valueOf(isWatched()); case ASYNC_CONTEXT: return getAsyncContext(); case DECOMPRESSED: return Boolean.valueOf(isDecompressed()); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PATH: return isSetPath(); case WATCHED: return isSetWatched(); case ASYNC_CONTEXT: return isSetAsyncContext(); case DECOMPRESSED: return isSetDecompressed(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof GetDataSpec) return this.equals((GetDataSpec)that); return false; } public boolean equals(GetDataSpec that) { if (that == null) return false; boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } boolean this_present_watched = true; boolean that_present_watched = true; if (this_present_watched || that_present_watched) { if (!(this_present_watched && that_present_watched)) return false; if (this.watched != that.watched) return false; } boolean this_present_asyncContext = true && this.isSetAsyncContext(); boolean that_present_asyncContext = true && that.isSetAsyncContext(); if (this_present_asyncContext || that_present_asyncContext) { if (!(this_present_asyncContext && that_present_asyncContext)) return false; if (!this.asyncContext.equals(that.asyncContext)) return false; } boolean this_present_decompressed = true; boolean that_present_decompressed = true; if (this_present_decompressed || that_present_decompressed) { if (!(this_present_decompressed && that_present_decompressed)) return false; if (this.decompressed != that.decompressed) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(GetDataSpec other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetWatched()).compareTo(other.isSetWatched()); if (lastComparison != 0) { return lastComparison; } if (isSetWatched()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.watched, other.watched); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetAsyncContext()).compareTo(other.isSetAsyncContext()); if (lastComparison != 0) { return lastComparison; } if (isSetAsyncContext()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.asyncContext, other.asyncContext); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetDecompressed()).compareTo(other.isSetDecompressed()); if (lastComparison != 0) { return lastComparison; } if (isSetDecompressed()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.decompressed, other.decompressed); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("GetDataSpec("); boolean first = true; sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; if (!first) sb.append(", "); sb.append("watched:"); sb.append(this.watched); first = false; if (!first) sb.append(", "); sb.append("asyncContext:"); if (this.asyncContext == null) { sb.append("null"); } else { sb.append(this.asyncContext); } first = false; if (!first) sb.append(", "); sb.append("decompressed:"); sb.append(this.decompressed); first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class GetDataSpecStandardSchemeFactory implements SchemeFactory { public GetDataSpecStandardScheme getScheme() { return new GetDataSpecStandardScheme(); } } private static class GetDataSpecStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, GetDataSpec struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // WATCHED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.watched = iprot.readBool(); struct.setWatchedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // ASYNC_CONTEXT if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.asyncContext = iprot.readString(); struct.setAsyncContextIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // DECOMPRESSED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.decompressed = iprot.readBool(); struct.setDecompressedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, GetDataSpec struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } oprot.writeFieldBegin(WATCHED_FIELD_DESC); oprot.writeBool(struct.watched); oprot.writeFieldEnd(); if (struct.asyncContext != null) { oprot.writeFieldBegin(ASYNC_CONTEXT_FIELD_DESC); oprot.writeString(struct.asyncContext); oprot.writeFieldEnd(); } oprot.writeFieldBegin(DECOMPRESSED_FIELD_DESC); oprot.writeBool(struct.decompressed); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class GetDataSpecTupleSchemeFactory implements SchemeFactory { public GetDataSpecTupleScheme getScheme() { return new GetDataSpecTupleScheme(); } } private static class GetDataSpecTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, GetDataSpec struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetPath()) { optionals.set(0); } if (struct.isSetWatched()) { optionals.set(1); } if (struct.isSetAsyncContext()) { optionals.set(2); } if (struct.isSetDecompressed()) { optionals.set(3); } oprot.writeBitSet(optionals, 4); if (struct.isSetPath()) { oprot.writeString(struct.path); } if (struct.isSetWatched()) { oprot.writeBool(struct.watched); } if (struct.isSetAsyncContext()) { oprot.writeString(struct.asyncContext); } if (struct.isSetDecompressed()) { oprot.writeBool(struct.decompressed); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, GetDataSpec struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(4); if (incoming.get(0)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } if (incoming.get(1)) { struct.watched = iprot.readBool(); struct.setWatchedIsSet(true); } if (incoming.get(2)) { struct.asyncContext = iprot.readString(); struct.setAsyncContextIsSet(true); } if (incoming.get(3)) { struct.decompressed = iprot.readBool(); struct.setDecompressedIsSet(true); } } } } curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/Id.java000066400000000000000000000330031245521677600321330ustar00rootroot00000000000000/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Id implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("Id"); private static final org.apache.thrift.protocol.TField SCHEME_FIELD_DESC = new org.apache.thrift.protocol.TField("scheme", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.STRING, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new IdStandardSchemeFactory()); schemes.put(TupleScheme.class, new IdTupleSchemeFactory()); } public String scheme; // required public String id; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SCHEME((short)1, "scheme"), ID((short)2, "id"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // SCHEME return SCHEME; case 2: // ID return ID; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SCHEME, new org.apache.thrift.meta_data.FieldMetaData("scheme", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(Id.class, metaDataMap); } public Id() { } public Id( String scheme, String id) { this(); this.scheme = scheme; this.id = id; } /** * Performs a deep copy on other. */ public Id(Id other) { if (other.isSetScheme()) { this.scheme = other.scheme; } if (other.isSetId()) { this.id = other.id; } } public Id deepCopy() { return new Id(this); } @Override public void clear() { this.scheme = null; this.id = null; } public String getScheme() { return this.scheme; } public Id setScheme(String scheme) { this.scheme = scheme; return this; } public void unsetScheme() { this.scheme = null; } /** Returns true if field scheme is set (has been assigned a value) and false otherwise */ public boolean isSetScheme() { return this.scheme != null; } public void setSchemeIsSet(boolean value) { if (!value) { this.scheme = null; } } public String getId() { return this.id; } public Id setId(String id) { this.id = id; return this; } public void unsetId() { this.id = null; } /** Returns true if field id is set (has been assigned a value) and false otherwise */ public boolean isSetId() { return this.id != null; } public void setIdIsSet(boolean value) { if (!value) { this.id = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SCHEME: if (value == null) { unsetScheme(); } else { setScheme((String)value); } break; case ID: if (value == null) { unsetId(); } else { setId((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SCHEME: return getScheme(); case ID: return getId(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SCHEME: return isSetScheme(); case ID: return isSetId(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof Id) return this.equals((Id)that); return false; } public boolean equals(Id that) { if (that == null) return false; boolean this_present_scheme = true && this.isSetScheme(); boolean that_present_scheme = true && that.isSetScheme(); if (this_present_scheme || that_present_scheme) { if (!(this_present_scheme && that_present_scheme)) return false; if (!this.scheme.equals(that.scheme)) return false; } boolean this_present_id = true && this.isSetId(); boolean that_present_id = true && that.isSetId(); if (this_present_id || that_present_id) { if (!(this_present_id && that_present_id)) return false; if (!this.id.equals(that.id)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(Id other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetScheme()).compareTo(other.isSetScheme()); if (lastComparison != 0) { return lastComparison; } if (isSetScheme()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.scheme, other.scheme); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); if (lastComparison != 0) { return lastComparison; } if (isSetId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("Id("); boolean first = true; sb.append("scheme:"); if (this.scheme == null) { sb.append("null"); } else { sb.append(this.scheme); } first = false; if (!first) sb.append(", "); sb.append("id:"); if (this.id == null) { sb.append("null"); } else { sb.append(this.id); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class IdStandardSchemeFactory implements SchemeFactory { public IdStandardScheme getScheme() { return new IdStandardScheme(); } } private static class IdStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, Id struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // SCHEME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.scheme = iprot.readString(); struct.setSchemeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.id = iprot.readString(); struct.setIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, Id struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.scheme != null) { oprot.writeFieldBegin(SCHEME_FIELD_DESC); oprot.writeString(struct.scheme); oprot.writeFieldEnd(); } if (struct.id != null) { oprot.writeFieldBegin(ID_FIELD_DESC); oprot.writeString(struct.id); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class IdTupleSchemeFactory implements SchemeFactory { public IdTupleScheme getScheme() { return new IdTupleScheme(); } } private static class IdTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, Id struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetScheme()) { optionals.set(0); } if (struct.isSetId()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetScheme()) { oprot.writeString(struct.scheme); } if (struct.isSetId()) { oprot.writeString(struct.id); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, Id struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.scheme = iprot.readString(); struct.setSchemeIsSet(true); } if (incoming.get(1)) { struct.id = iprot.readString(); struct.setIdIsSet(true); } } } } KeeperState.java000066400000000000000000000024351245521677600337410ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import java.util.Map; import java.util.HashMap; import org.apache.thrift.TEnum; public enum KeeperState implements org.apache.thrift.TEnum { Unknown(0), Disconnected(1), NoSyncConnected(2), SyncConnected(3), AuthFailed(4), ConnectedReadOnly(5), SaslAuthenticated(6), Expired(7); private final int value; private KeeperState(int value) { this.value = value; } /** * Get the integer value of this enum value, as defined in the Thrift IDL. */ public int getValue() { return value; } /** * Find a the enum type by its integer value, as defined in the Thrift IDL. * @return null if the value is not found. */ public static KeeperState findByValue(int value) { switch (value) { case 0: return Unknown; case 1: return Disconnected; case 2: return NoSyncConnected; case 3: return SyncConnected; case 4: return AuthFailed; case 5: return ConnectedReadOnly; case 6: return SaslAuthenticated; case 7: return Expired; default: return null; } } } LeaderEvent.java000066400000000000000000000434221245521677600337240ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LeaderEvent implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("LeaderEvent"); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField PARTICIPANT_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("participantId", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField IS_LEADER_FIELD_DESC = new org.apache.thrift.protocol.TField("isLeader", org.apache.thrift.protocol.TType.BOOL, (short)3); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new LeaderEventStandardSchemeFactory()); schemes.put(TupleScheme.class, new LeaderEventTupleSchemeFactory()); } public String path; // required public String participantId; // required public boolean isLeader; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PATH((short)1, "path"), PARTICIPANT_ID((short)2, "participantId"), IS_LEADER((short)3, "isLeader"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PATH return PATH; case 2: // PARTICIPANT_ID return PARTICIPANT_ID; case 3: // IS_LEADER return IS_LEADER; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __ISLEADER_ISSET_ID = 0; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.PARTICIPANT_ID, new org.apache.thrift.meta_data.FieldMetaData("participantId", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.IS_LEADER, new org.apache.thrift.meta_data.FieldMetaData("isLeader", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(LeaderEvent.class, metaDataMap); } public LeaderEvent() { } public LeaderEvent( String path, String participantId, boolean isLeader) { this(); this.path = path; this.participantId = participantId; this.isLeader = isLeader; setIsLeaderIsSet(true); } /** * Performs a deep copy on other. */ public LeaderEvent(LeaderEvent other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetPath()) { this.path = other.path; } if (other.isSetParticipantId()) { this.participantId = other.participantId; } this.isLeader = other.isLeader; } public LeaderEvent deepCopy() { return new LeaderEvent(this); } @Override public void clear() { this.path = null; this.participantId = null; setIsLeaderIsSet(false); this.isLeader = false; } public String getPath() { return this.path; } public LeaderEvent setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public String getParticipantId() { return this.participantId; } public LeaderEvent setParticipantId(String participantId) { this.participantId = participantId; return this; } public void unsetParticipantId() { this.participantId = null; } /** Returns true if field participantId is set (has been assigned a value) and false otherwise */ public boolean isSetParticipantId() { return this.participantId != null; } public void setParticipantIdIsSet(boolean value) { if (!value) { this.participantId = null; } } public boolean isIsLeader() { return this.isLeader; } public LeaderEvent setIsLeader(boolean isLeader) { this.isLeader = isLeader; setIsLeaderIsSet(true); return this; } public void unsetIsLeader() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __ISLEADER_ISSET_ID); } /** Returns true if field isLeader is set (has been assigned a value) and false otherwise */ public boolean isSetIsLeader() { return EncodingUtils.testBit(__isset_bitfield, __ISLEADER_ISSET_ID); } public void setIsLeaderIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __ISLEADER_ISSET_ID, value); } public void setFieldValue(_Fields field, Object value) { switch (field) { case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; case PARTICIPANT_ID: if (value == null) { unsetParticipantId(); } else { setParticipantId((String)value); } break; case IS_LEADER: if (value == null) { unsetIsLeader(); } else { setIsLeader((Boolean)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PATH: return getPath(); case PARTICIPANT_ID: return getParticipantId(); case IS_LEADER: return Boolean.valueOf(isIsLeader()); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PATH: return isSetPath(); case PARTICIPANT_ID: return isSetParticipantId(); case IS_LEADER: return isSetIsLeader(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof LeaderEvent) return this.equals((LeaderEvent)that); return false; } public boolean equals(LeaderEvent that) { if (that == null) return false; boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } boolean this_present_participantId = true && this.isSetParticipantId(); boolean that_present_participantId = true && that.isSetParticipantId(); if (this_present_participantId || that_present_participantId) { if (!(this_present_participantId && that_present_participantId)) return false; if (!this.participantId.equals(that.participantId)) return false; } boolean this_present_isLeader = true; boolean that_present_isLeader = true; if (this_present_isLeader || that_present_isLeader) { if (!(this_present_isLeader && that_present_isLeader)) return false; if (this.isLeader != that.isLeader) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(LeaderEvent other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetParticipantId()).compareTo(other.isSetParticipantId()); if (lastComparison != 0) { return lastComparison; } if (isSetParticipantId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.participantId, other.participantId); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetIsLeader()).compareTo(other.isSetIsLeader()); if (lastComparison != 0) { return lastComparison; } if (isSetIsLeader()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.isLeader, other.isLeader); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("LeaderEvent("); boolean first = true; sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; if (!first) sb.append(", "); sb.append("participantId:"); if (this.participantId == null) { sb.append("null"); } else { sb.append(this.participantId); } first = false; if (!first) sb.append(", "); sb.append("isLeader:"); sb.append(this.isLeader); first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class LeaderEventStandardSchemeFactory implements SchemeFactory { public LeaderEventStandardScheme getScheme() { return new LeaderEventStandardScheme(); } } private static class LeaderEventStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, LeaderEvent struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // PARTICIPANT_ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.participantId = iprot.readString(); struct.setParticipantIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // IS_LEADER if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isLeader = iprot.readBool(); struct.setIsLeaderIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, LeaderEvent struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } if (struct.participantId != null) { oprot.writeFieldBegin(PARTICIPANT_ID_FIELD_DESC); oprot.writeString(struct.participantId); oprot.writeFieldEnd(); } oprot.writeFieldBegin(IS_LEADER_FIELD_DESC); oprot.writeBool(struct.isLeader); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class LeaderEventTupleSchemeFactory implements SchemeFactory { public LeaderEventTupleScheme getScheme() { return new LeaderEventTupleScheme(); } } private static class LeaderEventTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, LeaderEvent struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetPath()) { optionals.set(0); } if (struct.isSetParticipantId()) { optionals.set(1); } if (struct.isSetIsLeader()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetPath()) { oprot.writeString(struct.path); } if (struct.isSetParticipantId()) { oprot.writeString(struct.participantId); } if (struct.isSetIsLeader()) { oprot.writeBool(struct.isLeader); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, LeaderEvent struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } if (incoming.get(1)) { struct.participantId = iprot.readString(); struct.setParticipantIdIsSet(true); } if (incoming.get(2)) { struct.isLeader = iprot.readBool(); struct.setIsLeaderIsSet(true); } } } } LeaderProjection.java000066400000000000000000000260411245521677600347550ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LeaderProjection implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("LeaderProjection"); private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.STRING, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new LeaderProjectionStandardSchemeFactory()); schemes.put(TupleScheme.class, new LeaderProjectionTupleSchemeFactory()); } public String id; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ID((short)1, "id"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // ID return ID; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(LeaderProjection.class, metaDataMap); } public LeaderProjection() { } public LeaderProjection( String id) { this(); this.id = id; } /** * Performs a deep copy on other. */ public LeaderProjection(LeaderProjection other) { if (other.isSetId()) { this.id = other.id; } } public LeaderProjection deepCopy() { return new LeaderProjection(this); } @Override public void clear() { this.id = null; } public String getId() { return this.id; } public LeaderProjection setId(String id) { this.id = id; return this; } public void unsetId() { this.id = null; } /** Returns true if field id is set (has been assigned a value) and false otherwise */ public boolean isSetId() { return this.id != null; } public void setIdIsSet(boolean value) { if (!value) { this.id = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case ID: if (value == null) { unsetId(); } else { setId((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case ID: return getId(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case ID: return isSetId(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof LeaderProjection) return this.equals((LeaderProjection)that); return false; } public boolean equals(LeaderProjection that) { if (that == null) return false; boolean this_present_id = true && this.isSetId(); boolean that_present_id = true && that.isSetId(); if (this_present_id || that_present_id) { if (!(this_present_id && that_present_id)) return false; if (!this.id.equals(that.id)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(LeaderProjection other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); if (lastComparison != 0) { return lastComparison; } if (isSetId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("LeaderProjection("); boolean first = true; sb.append("id:"); if (this.id == null) { sb.append("null"); } else { sb.append(this.id); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class LeaderProjectionStandardSchemeFactory implements SchemeFactory { public LeaderProjectionStandardScheme getScheme() { return new LeaderProjectionStandardScheme(); } } private static class LeaderProjectionStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, LeaderProjection struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.id = iprot.readString(); struct.setIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, LeaderProjection struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.id != null) { oprot.writeFieldBegin(ID_FIELD_DESC); oprot.writeString(struct.id); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class LeaderProjectionTupleSchemeFactory implements SchemeFactory { public LeaderProjectionTupleScheme getScheme() { return new LeaderProjectionTupleScheme(); } } private static class LeaderProjectionTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, LeaderProjection struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetId()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetId()) { oprot.writeString(struct.id); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, LeaderProjection struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.id = iprot.readString(); struct.setIdIsSet(true); } } } } LeaderResult.java000066400000000000000000000360201245521677600341150ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LeaderResult implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("LeaderResult"); private static final org.apache.thrift.protocol.TField PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("projection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField IS_LEADER_FIELD_DESC = new org.apache.thrift.protocol.TField("isLeader", org.apache.thrift.protocol.TType.BOOL, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new LeaderResultStandardSchemeFactory()); schemes.put(TupleScheme.class, new LeaderResultTupleSchemeFactory()); } public LeaderProjection projection; // required public boolean isLeader; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PROJECTION((short)1, "projection"), IS_LEADER((short)2, "isLeader"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PROJECTION return PROJECTION; case 2: // IS_LEADER return IS_LEADER; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __ISLEADER_ISSET_ID = 0; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("projection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, LeaderProjection.class))); tmpMap.put(_Fields.IS_LEADER, new org.apache.thrift.meta_data.FieldMetaData("isLeader", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(LeaderResult.class, metaDataMap); } public LeaderResult() { } public LeaderResult( LeaderProjection projection, boolean isLeader) { this(); this.projection = projection; this.isLeader = isLeader; setIsLeaderIsSet(true); } /** * Performs a deep copy on other. */ public LeaderResult(LeaderResult other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetProjection()) { this.projection = new LeaderProjection(other.projection); } this.isLeader = other.isLeader; } public LeaderResult deepCopy() { return new LeaderResult(this); } @Override public void clear() { this.projection = null; setIsLeaderIsSet(false); this.isLeader = false; } public LeaderProjection getProjection() { return this.projection; } public LeaderResult setProjection(LeaderProjection projection) { this.projection = projection; return this; } public void unsetProjection() { this.projection = null; } /** Returns true if field projection is set (has been assigned a value) and false otherwise */ public boolean isSetProjection() { return this.projection != null; } public void setProjectionIsSet(boolean value) { if (!value) { this.projection = null; } } public boolean isIsLeader() { return this.isLeader; } public LeaderResult setIsLeader(boolean isLeader) { this.isLeader = isLeader; setIsLeaderIsSet(true); return this; } public void unsetIsLeader() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __ISLEADER_ISSET_ID); } /** Returns true if field isLeader is set (has been assigned a value) and false otherwise */ public boolean isSetIsLeader() { return EncodingUtils.testBit(__isset_bitfield, __ISLEADER_ISSET_ID); } public void setIsLeaderIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __ISLEADER_ISSET_ID, value); } public void setFieldValue(_Fields field, Object value) { switch (field) { case PROJECTION: if (value == null) { unsetProjection(); } else { setProjection((LeaderProjection)value); } break; case IS_LEADER: if (value == null) { unsetIsLeader(); } else { setIsLeader((Boolean)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PROJECTION: return getProjection(); case IS_LEADER: return Boolean.valueOf(isIsLeader()); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PROJECTION: return isSetProjection(); case IS_LEADER: return isSetIsLeader(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof LeaderResult) return this.equals((LeaderResult)that); return false; } public boolean equals(LeaderResult that) { if (that == null) return false; boolean this_present_projection = true && this.isSetProjection(); boolean that_present_projection = true && that.isSetProjection(); if (this_present_projection || that_present_projection) { if (!(this_present_projection && that_present_projection)) return false; if (!this.projection.equals(that.projection)) return false; } boolean this_present_isLeader = true; boolean that_present_isLeader = true; if (this_present_isLeader || that_present_isLeader) { if (!(this_present_isLeader && that_present_isLeader)) return false; if (this.isLeader != that.isLeader) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(LeaderResult other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetProjection()).compareTo(other.isSetProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.projection, other.projection); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetIsLeader()).compareTo(other.isSetIsLeader()); if (lastComparison != 0) { return lastComparison; } if (isSetIsLeader()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.isLeader, other.isLeader); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("LeaderResult("); boolean first = true; sb.append("projection:"); if (this.projection == null) { sb.append("null"); } else { sb.append(this.projection); } first = false; if (!first) sb.append(", "); sb.append("isLeader:"); sb.append(this.isLeader); first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (projection != null) { projection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class LeaderResultStandardSchemeFactory implements SchemeFactory { public LeaderResultStandardScheme getScheme() { return new LeaderResultStandardScheme(); } } private static class LeaderResultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, LeaderResult struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.projection = new LeaderProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // IS_LEADER if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isLeader = iprot.readBool(); struct.setIsLeaderIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, LeaderResult struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.projection != null) { oprot.writeFieldBegin(PROJECTION_FIELD_DESC); struct.projection.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldBegin(IS_LEADER_FIELD_DESC); oprot.writeBool(struct.isLeader); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class LeaderResultTupleSchemeFactory implements SchemeFactory { public LeaderResultTupleScheme getScheme() { return new LeaderResultTupleScheme(); } } private static class LeaderResultTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, LeaderResult struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetProjection()) { optionals.set(0); } if (struct.isSetIsLeader()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetProjection()) { struct.projection.write(oprot); } if (struct.isSetIsLeader()) { oprot.writeBool(struct.isLeader); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, LeaderResult struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.projection = new LeaderProjection(); struct.projection.read(iprot); struct.setProjectionIsSet(true); } if (incoming.get(1)) { struct.isLeader = iprot.readBool(); struct.setIsLeaderIsSet(true); } } } } LeaseProjection.java000066400000000000000000000257771245521677600346310ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LeaseProjection implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("LeaseProjection"); private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.STRING, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new LeaseProjectionStandardSchemeFactory()); schemes.put(TupleScheme.class, new LeaseProjectionTupleSchemeFactory()); } public String id; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ID((short)1, "id"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // ID return ID; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(LeaseProjection.class, metaDataMap); } public LeaseProjection() { } public LeaseProjection( String id) { this(); this.id = id; } /** * Performs a deep copy on other. */ public LeaseProjection(LeaseProjection other) { if (other.isSetId()) { this.id = other.id; } } public LeaseProjection deepCopy() { return new LeaseProjection(this); } @Override public void clear() { this.id = null; } public String getId() { return this.id; } public LeaseProjection setId(String id) { this.id = id; return this; } public void unsetId() { this.id = null; } /** Returns true if field id is set (has been assigned a value) and false otherwise */ public boolean isSetId() { return this.id != null; } public void setIdIsSet(boolean value) { if (!value) { this.id = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case ID: if (value == null) { unsetId(); } else { setId((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case ID: return getId(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case ID: return isSetId(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof LeaseProjection) return this.equals((LeaseProjection)that); return false; } public boolean equals(LeaseProjection that) { if (that == null) return false; boolean this_present_id = true && this.isSetId(); boolean that_present_id = true && that.isSetId(); if (this_present_id || that_present_id) { if (!(this_present_id && that_present_id)) return false; if (!this.id.equals(that.id)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(LeaseProjection other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); if (lastComparison != 0) { return lastComparison; } if (isSetId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("LeaseProjection("); boolean first = true; sb.append("id:"); if (this.id == null) { sb.append("null"); } else { sb.append(this.id); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class LeaseProjectionStandardSchemeFactory implements SchemeFactory { public LeaseProjectionStandardScheme getScheme() { return new LeaseProjectionStandardScheme(); } } private static class LeaseProjectionStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, LeaseProjection struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.id = iprot.readString(); struct.setIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, LeaseProjection struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.id != null) { oprot.writeFieldBegin(ID_FIELD_DESC); oprot.writeString(struct.id); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class LeaseProjectionTupleSchemeFactory implements SchemeFactory { public LeaseProjectionTupleScheme getScheme() { return new LeaseProjectionTupleScheme(); } } private static class LeaseProjectionTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, LeaseProjection struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetId()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetId()) { oprot.writeString(struct.id); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, LeaseProjection struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.id = iprot.readString(); struct.setIdIsSet(true); } } } } LockProjection.java000066400000000000000000000257351245521677600344620ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LockProjection implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("LockProjection"); private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.STRING, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new LockProjectionStandardSchemeFactory()); schemes.put(TupleScheme.class, new LockProjectionTupleSchemeFactory()); } public String id; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ID((short)1, "id"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // ID return ID; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(LockProjection.class, metaDataMap); } public LockProjection() { } public LockProjection( String id) { this(); this.id = id; } /** * Performs a deep copy on other. */ public LockProjection(LockProjection other) { if (other.isSetId()) { this.id = other.id; } } public LockProjection deepCopy() { return new LockProjection(this); } @Override public void clear() { this.id = null; } public String getId() { return this.id; } public LockProjection setId(String id) { this.id = id; return this; } public void unsetId() { this.id = null; } /** Returns true if field id is set (has been assigned a value) and false otherwise */ public boolean isSetId() { return this.id != null; } public void setIdIsSet(boolean value) { if (!value) { this.id = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case ID: if (value == null) { unsetId(); } else { setId((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case ID: return getId(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case ID: return isSetId(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof LockProjection) return this.equals((LockProjection)that); return false; } public boolean equals(LockProjection that) { if (that == null) return false; boolean this_present_id = true && this.isSetId(); boolean that_present_id = true && that.isSetId(); if (this_present_id || that_present_id) { if (!(this_present_id && that_present_id)) return false; if (!this.id.equals(that.id)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(LockProjection other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); if (lastComparison != 0) { return lastComparison; } if (isSetId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("LockProjection("); boolean first = true; sb.append("id:"); if (this.id == null) { sb.append("null"); } else { sb.append(this.id); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class LockProjectionStandardSchemeFactory implements SchemeFactory { public LockProjectionStandardScheme getScheme() { return new LockProjectionStandardScheme(); } } private static class LockProjectionStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, LockProjection struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.id = iprot.readString(); struct.setIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, LockProjection struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.id != null) { oprot.writeFieldBegin(ID_FIELD_DESC); oprot.writeString(struct.id); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class LockProjectionTupleSchemeFactory implements SchemeFactory { public LockProjectionTupleScheme getScheme() { return new LockProjectionTupleScheme(); } } private static class LockProjectionTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, LockProjection struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetId()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetId()) { oprot.writeString(struct.id); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, LockProjection struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.id = iprot.readString(); struct.setIdIsSet(true); } } } } NodeCacheProjection.java000066400000000000000000000262071245521677600353760ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NodeCacheProjection implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("NodeCacheProjection"); private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.STRING, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new NodeCacheProjectionStandardSchemeFactory()); schemes.put(TupleScheme.class, new NodeCacheProjectionTupleSchemeFactory()); } public String id; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ID((short)1, "id"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // ID return ID; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(NodeCacheProjection.class, metaDataMap); } public NodeCacheProjection() { } public NodeCacheProjection( String id) { this(); this.id = id; } /** * Performs a deep copy on other. */ public NodeCacheProjection(NodeCacheProjection other) { if (other.isSetId()) { this.id = other.id; } } public NodeCacheProjection deepCopy() { return new NodeCacheProjection(this); } @Override public void clear() { this.id = null; } public String getId() { return this.id; } public NodeCacheProjection setId(String id) { this.id = id; return this; } public void unsetId() { this.id = null; } /** Returns true if field id is set (has been assigned a value) and false otherwise */ public boolean isSetId() { return this.id != null; } public void setIdIsSet(boolean value) { if (!value) { this.id = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case ID: if (value == null) { unsetId(); } else { setId((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case ID: return getId(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case ID: return isSetId(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof NodeCacheProjection) return this.equals((NodeCacheProjection)that); return false; } public boolean equals(NodeCacheProjection that) { if (that == null) return false; boolean this_present_id = true && this.isSetId(); boolean that_present_id = true && that.isSetId(); if (this_present_id || that_present_id) { if (!(this_present_id && that_present_id)) return false; if (!this.id.equals(that.id)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(NodeCacheProjection other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); if (lastComparison != 0) { return lastComparison; } if (isSetId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("NodeCacheProjection("); boolean first = true; sb.append("id:"); if (this.id == null) { sb.append("null"); } else { sb.append(this.id); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class NodeCacheProjectionStandardSchemeFactory implements SchemeFactory { public NodeCacheProjectionStandardScheme getScheme() { return new NodeCacheProjectionStandardScheme(); } } private static class NodeCacheProjectionStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, NodeCacheProjection struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.id = iprot.readString(); struct.setIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, NodeCacheProjection struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.id != null) { oprot.writeFieldBegin(ID_FIELD_DESC); oprot.writeString(struct.id); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class NodeCacheProjectionTupleSchemeFactory implements SchemeFactory { public NodeCacheProjectionTupleScheme getScheme() { return new NodeCacheProjectionTupleScheme(); } } private static class NodeCacheProjectionTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, NodeCacheProjection struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetId()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetId()) { oprot.writeString(struct.id); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, NodeCacheProjection struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.id = iprot.readString(); struct.setIdIsSet(true); } } } } NodeExceptionType.java000066400000000000000000000020271245521677600351300ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import java.util.Map; import java.util.HashMap; import org.apache.thrift.TEnum; public enum NodeExceptionType implements org.apache.thrift.TEnum { NONODE(0), BADVERSION(1), NODEEXISTS(2), NOTEMPTY(3); private final int value; private NodeExceptionType(int value) { this.value = value; } /** * Get the integer value of this enum value, as defined in the Thrift IDL. */ public int getValue() { return value; } /** * Find a the enum type by its integer value, as defined in the Thrift IDL. * @return null if the value is not found. */ public static NodeExceptionType findByValue(int value) { switch (value) { case 0: return NONODE; case 1: return BADVERSION; case 2: return NODEEXISTS; case 3: return NOTEMPTY; default: return null; } } } OptionalChildrenList.java000066400000000000000000000324141245521677600356170ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OptionalChildrenList implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("OptionalChildrenList"); private static final org.apache.thrift.protocol.TField CHILDREN_FIELD_DESC = new org.apache.thrift.protocol.TField("children", org.apache.thrift.protocol.TType.LIST, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new OptionalChildrenListStandardSchemeFactory()); schemes.put(TupleScheme.class, new OptionalChildrenListTupleSchemeFactory()); } public List children; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { CHILDREN((short)1, "children"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // CHILDREN return CHILDREN; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.CHILDREN, new org.apache.thrift.meta_data.FieldMetaData("children", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(OptionalChildrenList.class, metaDataMap); } public OptionalChildrenList() { } public OptionalChildrenList( List children) { this(); this.children = children; } /** * Performs a deep copy on other. */ public OptionalChildrenList(OptionalChildrenList other) { if (other.isSetChildren()) { List __this__children = new ArrayList(other.children); this.children = __this__children; } } public OptionalChildrenList deepCopy() { return new OptionalChildrenList(this); } @Override public void clear() { this.children = null; } public int getChildrenSize() { return (this.children == null) ? 0 : this.children.size(); } public java.util.Iterator getChildrenIterator() { return (this.children == null) ? null : this.children.iterator(); } public void addToChildren(String elem) { if (this.children == null) { this.children = new ArrayList(); } this.children.add(elem); } public List getChildren() { return this.children; } public OptionalChildrenList setChildren(List children) { this.children = children; return this; } public void unsetChildren() { this.children = null; } /** Returns true if field children is set (has been assigned a value) and false otherwise */ public boolean isSetChildren() { return this.children != null; } public void setChildrenIsSet(boolean value) { if (!value) { this.children = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case CHILDREN: if (value == null) { unsetChildren(); } else { setChildren((List)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case CHILDREN: return getChildren(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case CHILDREN: return isSetChildren(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof OptionalChildrenList) return this.equals((OptionalChildrenList)that); return false; } public boolean equals(OptionalChildrenList that) { if (that == null) return false; boolean this_present_children = true && this.isSetChildren(); boolean that_present_children = true && that.isSetChildren(); if (this_present_children || that_present_children) { if (!(this_present_children && that_present_children)) return false; if (!this.children.equals(that.children)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(OptionalChildrenList other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetChildren()).compareTo(other.isSetChildren()); if (lastComparison != 0) { return lastComparison; } if (isSetChildren()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.children, other.children); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("OptionalChildrenList("); boolean first = true; sb.append("children:"); if (this.children == null) { sb.append("null"); } else { sb.append(this.children); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class OptionalChildrenListStandardSchemeFactory implements SchemeFactory { public OptionalChildrenListStandardScheme getScheme() { return new OptionalChildrenListStandardScheme(); } } private static class OptionalChildrenListStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, OptionalChildrenList struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // CHILDREN if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list0 = iprot.readListBegin(); struct.children = new ArrayList(_list0.size); for (int _i1 = 0; _i1 < _list0.size; ++_i1) { String _elem2; _elem2 = iprot.readString(); struct.children.add(_elem2); } iprot.readListEnd(); } struct.setChildrenIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, OptionalChildrenList struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.children != null) { oprot.writeFieldBegin(CHILDREN_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, struct.children.size())); for (String _iter3 : struct.children) { oprot.writeString(_iter3); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class OptionalChildrenListTupleSchemeFactory implements SchemeFactory { public OptionalChildrenListTupleScheme getScheme() { return new OptionalChildrenListTupleScheme(); } } private static class OptionalChildrenListTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, OptionalChildrenList struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetChildren()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetChildren()) { { oprot.writeI32(struct.children.size()); for (String _iter4 : struct.children) { oprot.writeString(_iter4); } } } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, OptionalChildrenList struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { { org.apache.thrift.protocol.TList _list5 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, iprot.readI32()); struct.children = new ArrayList(_list5.size); for (int _i6 = 0; _i6 < _list5.size; ++_i6) { String _elem7; _elem7 = iprot.readString(); struct.children.add(_elem7); } } struct.setChildrenIsSet(true); } } } } OptionalData.java000066400000000000000000000266401245521677600341100ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OptionalData implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("OptionalData"); private static final org.apache.thrift.protocol.TField DATA_FIELD_DESC = new org.apache.thrift.protocol.TField("data", org.apache.thrift.protocol.TType.STRING, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new OptionalDataStandardSchemeFactory()); schemes.put(TupleScheme.class, new OptionalDataTupleSchemeFactory()); } public ByteBuffer data; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { DATA((short)1, "data"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // DATA return DATA; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.DATA, new org.apache.thrift.meta_data.FieldMetaData("data", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(OptionalData.class, metaDataMap); } public OptionalData() { } public OptionalData( ByteBuffer data) { this(); this.data = data; } /** * Performs a deep copy on other. */ public OptionalData(OptionalData other) { if (other.isSetData()) { this.data = org.apache.thrift.TBaseHelper.copyBinary(other.data); ; } } public OptionalData deepCopy() { return new OptionalData(this); } @Override public void clear() { this.data = null; } public byte[] getData() { setData(org.apache.thrift.TBaseHelper.rightSize(data)); return data == null ? null : data.array(); } public ByteBuffer bufferForData() { return data; } public OptionalData setData(byte[] data) { setData(data == null ? (ByteBuffer)null : ByteBuffer.wrap(data)); return this; } public OptionalData setData(ByteBuffer data) { this.data = data; return this; } public void unsetData() { this.data = null; } /** Returns true if field data is set (has been assigned a value) and false otherwise */ public boolean isSetData() { return this.data != null; } public void setDataIsSet(boolean value) { if (!value) { this.data = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case DATA: if (value == null) { unsetData(); } else { setData((ByteBuffer)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case DATA: return getData(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case DATA: return isSetData(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof OptionalData) return this.equals((OptionalData)that); return false; } public boolean equals(OptionalData that) { if (that == null) return false; boolean this_present_data = true && this.isSetData(); boolean that_present_data = true && that.isSetData(); if (this_present_data || that_present_data) { if (!(this_present_data && that_present_data)) return false; if (!this.data.equals(that.data)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(OptionalData other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetData()).compareTo(other.isSetData()); if (lastComparison != 0) { return lastComparison; } if (isSetData()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.data, other.data); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("OptionalData("); boolean first = true; sb.append("data:"); if (this.data == null) { sb.append("null"); } else { org.apache.thrift.TBaseHelper.toString(this.data, sb); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class OptionalDataStandardSchemeFactory implements SchemeFactory { public OptionalDataStandardScheme getScheme() { return new OptionalDataStandardScheme(); } } private static class OptionalDataStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, OptionalData struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // DATA if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.data = iprot.readBinary(); struct.setDataIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, OptionalData struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.data != null) { oprot.writeFieldBegin(DATA_FIELD_DESC); oprot.writeBinary(struct.data); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class OptionalDataTupleSchemeFactory implements SchemeFactory { public OptionalDataTupleScheme getScheme() { return new OptionalDataTupleScheme(); } } private static class OptionalDataTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, OptionalData struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetData()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetData()) { oprot.writeBinary(struct.data); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, OptionalData struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.data = iprot.readBinary(); struct.setDataIsSet(true); } } } } OptionalLockProjection.java000066400000000000000000000303561245521677600361630ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OptionalLockProjection implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("OptionalLockProjection"); private static final org.apache.thrift.protocol.TField LOCK_PROJECTION_FIELD_DESC = new org.apache.thrift.protocol.TField("lockProjection", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new OptionalLockProjectionStandardSchemeFactory()); schemes.put(TupleScheme.class, new OptionalLockProjectionTupleSchemeFactory()); } public LockProjection lockProjection; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { LOCK_PROJECTION((short)1, "lockProjection"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // LOCK_PROJECTION return LOCK_PROJECTION; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.LOCK_PROJECTION, new org.apache.thrift.meta_data.FieldMetaData("lockProjection", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, LockProjection.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(OptionalLockProjection.class, metaDataMap); } public OptionalLockProjection() { } public OptionalLockProjection( LockProjection lockProjection) { this(); this.lockProjection = lockProjection; } /** * Performs a deep copy on other. */ public OptionalLockProjection(OptionalLockProjection other) { if (other.isSetLockProjection()) { this.lockProjection = new LockProjection(other.lockProjection); } } public OptionalLockProjection deepCopy() { return new OptionalLockProjection(this); } @Override public void clear() { this.lockProjection = null; } public LockProjection getLockProjection() { return this.lockProjection; } public OptionalLockProjection setLockProjection(LockProjection lockProjection) { this.lockProjection = lockProjection; return this; } public void unsetLockProjection() { this.lockProjection = null; } /** Returns true if field lockProjection is set (has been assigned a value) and false otherwise */ public boolean isSetLockProjection() { return this.lockProjection != null; } public void setLockProjectionIsSet(boolean value) { if (!value) { this.lockProjection = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case LOCK_PROJECTION: if (value == null) { unsetLockProjection(); } else { setLockProjection((LockProjection)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case LOCK_PROJECTION: return getLockProjection(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case LOCK_PROJECTION: return isSetLockProjection(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof OptionalLockProjection) return this.equals((OptionalLockProjection)that); return false; } public boolean equals(OptionalLockProjection that) { if (that == null) return false; boolean this_present_lockProjection = true && this.isSetLockProjection(); boolean that_present_lockProjection = true && that.isSetLockProjection(); if (this_present_lockProjection || that_present_lockProjection) { if (!(this_present_lockProjection && that_present_lockProjection)) return false; if (!this.lockProjection.equals(that.lockProjection)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(OptionalLockProjection other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetLockProjection()).compareTo(other.isSetLockProjection()); if (lastComparison != 0) { return lastComparison; } if (isSetLockProjection()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.lockProjection, other.lockProjection); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("OptionalLockProjection("); boolean first = true; sb.append("lockProjection:"); if (this.lockProjection == null) { sb.append("null"); } else { sb.append(this.lockProjection); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (lockProjection != null) { lockProjection.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class OptionalLockProjectionStandardSchemeFactory implements SchemeFactory { public OptionalLockProjectionStandardScheme getScheme() { return new OptionalLockProjectionStandardScheme(); } } private static class OptionalLockProjectionStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, OptionalLockProjection struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // LOCK_PROJECTION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.lockProjection = new LockProjection(); struct.lockProjection.read(iprot); struct.setLockProjectionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, OptionalLockProjection struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.lockProjection != null) { oprot.writeFieldBegin(LOCK_PROJECTION_FIELD_DESC); struct.lockProjection.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class OptionalLockProjectionTupleSchemeFactory implements SchemeFactory { public OptionalLockProjectionTupleScheme getScheme() { return new OptionalLockProjectionTupleScheme(); } } private static class OptionalLockProjectionTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, OptionalLockProjection struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetLockProjection()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetLockProjection()) { struct.lockProjection.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, OptionalLockProjection struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.lockProjection = new LockProjection(); struct.lockProjection.read(iprot); struct.setLockProjectionIsSet(true); } } } } OptionalPath.java000066400000000000000000000260331245521677600341270ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OptionalPath implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("OptionalPath"); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new OptionalPathStandardSchemeFactory()); schemes.put(TupleScheme.class, new OptionalPathTupleSchemeFactory()); } public String path; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PATH((short)1, "path"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PATH return PATH; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(OptionalPath.class, metaDataMap); } public OptionalPath() { } public OptionalPath( String path) { this(); this.path = path; } /** * Performs a deep copy on other. */ public OptionalPath(OptionalPath other) { if (other.isSetPath()) { this.path = other.path; } } public OptionalPath deepCopy() { return new OptionalPath(this); } @Override public void clear() { this.path = null; } public String getPath() { return this.path; } public OptionalPath setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PATH: return getPath(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PATH: return isSetPath(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof OptionalPath) return this.equals((OptionalPath)that); return false; } public boolean equals(OptionalPath that) { if (that == null) return false; boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(OptionalPath other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("OptionalPath("); boolean first = true; sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class OptionalPathStandardSchemeFactory implements SchemeFactory { public OptionalPathStandardScheme getScheme() { return new OptionalPathStandardScheme(); } } private static class OptionalPathStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, OptionalPath struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, OptionalPath struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class OptionalPathTupleSchemeFactory implements SchemeFactory { public OptionalPathTupleScheme getScheme() { return new OptionalPathTupleScheme(); } } private static class OptionalPathTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, OptionalPath struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetPath()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetPath()) { oprot.writeString(struct.path); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, OptionalPath struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } } } } OptionalStat.java000066400000000000000000000262041245521677600341460ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OptionalStat implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("OptionalStat"); private static final org.apache.thrift.protocol.TField STAT_FIELD_DESC = new org.apache.thrift.protocol.TField("stat", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new OptionalStatStandardSchemeFactory()); schemes.put(TupleScheme.class, new OptionalStatTupleSchemeFactory()); } public Stat stat; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { STAT((short)1, "stat"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // STAT return STAT; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.STAT, new org.apache.thrift.meta_data.FieldMetaData("stat", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, Stat.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(OptionalStat.class, metaDataMap); } public OptionalStat() { } public OptionalStat( Stat stat) { this(); this.stat = stat; } /** * Performs a deep copy on other. */ public OptionalStat(OptionalStat other) { if (other.isSetStat()) { this.stat = new Stat(other.stat); } } public OptionalStat deepCopy() { return new OptionalStat(this); } @Override public void clear() { this.stat = null; } public Stat getStat() { return this.stat; } public OptionalStat setStat(Stat stat) { this.stat = stat; return this; } public void unsetStat() { this.stat = null; } /** Returns true if field stat is set (has been assigned a value) and false otherwise */ public boolean isSetStat() { return this.stat != null; } public void setStatIsSet(boolean value) { if (!value) { this.stat = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case STAT: if (value == null) { unsetStat(); } else { setStat((Stat)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case STAT: return getStat(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case STAT: return isSetStat(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof OptionalStat) return this.equals((OptionalStat)that); return false; } public boolean equals(OptionalStat that) { if (that == null) return false; boolean this_present_stat = true && this.isSetStat(); boolean that_present_stat = true && that.isSetStat(); if (this_present_stat || that_present_stat) { if (!(this_present_stat && that_present_stat)) return false; if (!this.stat.equals(that.stat)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(OptionalStat other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetStat()).compareTo(other.isSetStat()); if (lastComparison != 0) { return lastComparison; } if (isSetStat()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.stat, other.stat); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("OptionalStat("); boolean first = true; sb.append("stat:"); if (this.stat == null) { sb.append("null"); } else { sb.append(this.stat); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (stat != null) { stat.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class OptionalStatStandardSchemeFactory implements SchemeFactory { public OptionalStatStandardScheme getScheme() { return new OptionalStatStandardScheme(); } } private static class OptionalStatStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, OptionalStat struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // STAT if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.stat = new Stat(); struct.stat.read(iprot); struct.setStatIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, OptionalStat struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.stat != null) { oprot.writeFieldBegin(STAT_FIELD_DESC); struct.stat.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class OptionalStatTupleSchemeFactory implements SchemeFactory { public OptionalStatTupleScheme getScheme() { return new OptionalStatTupleScheme(); } } private static class OptionalStatTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, OptionalStat struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetStat()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetStat()) { struct.stat.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, OptionalStat struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.stat = new Stat(); struct.stat.read(iprot); struct.setStatIsSet(true); } } } } Participant.java000066400000000000000000000343701245521677600340060ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Participant implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("Participant"); private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField IS_LEADER_FIELD_DESC = new org.apache.thrift.protocol.TField("isLeader", org.apache.thrift.protocol.TType.BOOL, (short)2); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new ParticipantStandardSchemeFactory()); schemes.put(TupleScheme.class, new ParticipantTupleSchemeFactory()); } public String id; // required public boolean isLeader; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ID((short)1, "id"), IS_LEADER((short)2, "isLeader"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // ID return ID; case 2: // IS_LEADER return IS_LEADER; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __ISLEADER_ISSET_ID = 0; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.IS_LEADER, new org.apache.thrift.meta_data.FieldMetaData("isLeader", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(Participant.class, metaDataMap); } public Participant() { } public Participant( String id, boolean isLeader) { this(); this.id = id; this.isLeader = isLeader; setIsLeaderIsSet(true); } /** * Performs a deep copy on other. */ public Participant(Participant other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetId()) { this.id = other.id; } this.isLeader = other.isLeader; } public Participant deepCopy() { return new Participant(this); } @Override public void clear() { this.id = null; setIsLeaderIsSet(false); this.isLeader = false; } public String getId() { return this.id; } public Participant setId(String id) { this.id = id; return this; } public void unsetId() { this.id = null; } /** Returns true if field id is set (has been assigned a value) and false otherwise */ public boolean isSetId() { return this.id != null; } public void setIdIsSet(boolean value) { if (!value) { this.id = null; } } public boolean isIsLeader() { return this.isLeader; } public Participant setIsLeader(boolean isLeader) { this.isLeader = isLeader; setIsLeaderIsSet(true); return this; } public void unsetIsLeader() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __ISLEADER_ISSET_ID); } /** Returns true if field isLeader is set (has been assigned a value) and false otherwise */ public boolean isSetIsLeader() { return EncodingUtils.testBit(__isset_bitfield, __ISLEADER_ISSET_ID); } public void setIsLeaderIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __ISLEADER_ISSET_ID, value); } public void setFieldValue(_Fields field, Object value) { switch (field) { case ID: if (value == null) { unsetId(); } else { setId((String)value); } break; case IS_LEADER: if (value == null) { unsetIsLeader(); } else { setIsLeader((Boolean)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case ID: return getId(); case IS_LEADER: return Boolean.valueOf(isIsLeader()); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case ID: return isSetId(); case IS_LEADER: return isSetIsLeader(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof Participant) return this.equals((Participant)that); return false; } public boolean equals(Participant that) { if (that == null) return false; boolean this_present_id = true && this.isSetId(); boolean that_present_id = true && that.isSetId(); if (this_present_id || that_present_id) { if (!(this_present_id && that_present_id)) return false; if (!this.id.equals(that.id)) return false; } boolean this_present_isLeader = true; boolean that_present_isLeader = true; if (this_present_isLeader || that_present_isLeader) { if (!(this_present_isLeader && that_present_isLeader)) return false; if (this.isLeader != that.isLeader) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(Participant other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); if (lastComparison != 0) { return lastComparison; } if (isSetId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetIsLeader()).compareTo(other.isSetIsLeader()); if (lastComparison != 0) { return lastComparison; } if (isSetIsLeader()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.isLeader, other.isLeader); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("Participant("); boolean first = true; sb.append("id:"); if (this.id == null) { sb.append("null"); } else { sb.append(this.id); } first = false; if (!first) sb.append(", "); sb.append("isLeader:"); sb.append(this.isLeader); first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class ParticipantStandardSchemeFactory implements SchemeFactory { public ParticipantStandardScheme getScheme() { return new ParticipantStandardScheme(); } } private static class ParticipantStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, Participant struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.id = iprot.readString(); struct.setIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // IS_LEADER if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isLeader = iprot.readBool(); struct.setIsLeaderIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, Participant struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.id != null) { oprot.writeFieldBegin(ID_FIELD_DESC); oprot.writeString(struct.id); oprot.writeFieldEnd(); } oprot.writeFieldBegin(IS_LEADER_FIELD_DESC); oprot.writeBool(struct.isLeader); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class ParticipantTupleSchemeFactory implements SchemeFactory { public ParticipantTupleScheme getScheme() { return new ParticipantTupleScheme(); } } private static class ParticipantTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, Participant struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetId()) { optionals.set(0); } if (struct.isSetIsLeader()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetId()) { oprot.writeString(struct.id); } if (struct.isSetIsLeader()) { oprot.writeBool(struct.isLeader); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, Participant struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.id = iprot.readString(); struct.setIdIsSet(true); } if (incoming.get(1)) { struct.isLeader = iprot.readBool(); struct.setIsLeaderIsSet(true); } } } } PathChildrenCacheEvent.java000066400000000000000000000437531245521677600360300ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PathChildrenCacheEvent implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("PathChildrenCacheEvent"); private static final org.apache.thrift.protocol.TField CACHED_PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("cachedPath", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("type", org.apache.thrift.protocol.TType.I32, (short)2); private static final org.apache.thrift.protocol.TField DATA_FIELD_DESC = new org.apache.thrift.protocol.TField("data", org.apache.thrift.protocol.TType.STRUCT, (short)3); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new PathChildrenCacheEventStandardSchemeFactory()); schemes.put(TupleScheme.class, new PathChildrenCacheEventTupleSchemeFactory()); } public String cachedPath; // required /** * * @see PathChildrenCacheEventType */ public PathChildrenCacheEventType type; // required public ChildData data; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { CACHED_PATH((short)1, "cachedPath"), /** * * @see PathChildrenCacheEventType */ TYPE((short)2, "type"), DATA((short)3, "data"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // CACHED_PATH return CACHED_PATH; case 2: // TYPE return TYPE; case 3: // DATA return DATA; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.CACHED_PATH, new org.apache.thrift.meta_data.FieldMetaData("cachedPath", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.TYPE, new org.apache.thrift.meta_data.FieldMetaData("type", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, PathChildrenCacheEventType.class))); tmpMap.put(_Fields.DATA, new org.apache.thrift.meta_data.FieldMetaData("data", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, ChildData.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(PathChildrenCacheEvent.class, metaDataMap); } public PathChildrenCacheEvent() { } public PathChildrenCacheEvent( String cachedPath, PathChildrenCacheEventType type, ChildData data) { this(); this.cachedPath = cachedPath; this.type = type; this.data = data; } /** * Performs a deep copy on other. */ public PathChildrenCacheEvent(PathChildrenCacheEvent other) { if (other.isSetCachedPath()) { this.cachedPath = other.cachedPath; } if (other.isSetType()) { this.type = other.type; } if (other.isSetData()) { this.data = new ChildData(other.data); } } public PathChildrenCacheEvent deepCopy() { return new PathChildrenCacheEvent(this); } @Override public void clear() { this.cachedPath = null; this.type = null; this.data = null; } public String getCachedPath() { return this.cachedPath; } public PathChildrenCacheEvent setCachedPath(String cachedPath) { this.cachedPath = cachedPath; return this; } public void unsetCachedPath() { this.cachedPath = null; } /** Returns true if field cachedPath is set (has been assigned a value) and false otherwise */ public boolean isSetCachedPath() { return this.cachedPath != null; } public void setCachedPathIsSet(boolean value) { if (!value) { this.cachedPath = null; } } /** * * @see PathChildrenCacheEventType */ public PathChildrenCacheEventType getType() { return this.type; } /** * * @see PathChildrenCacheEventType */ public PathChildrenCacheEvent setType(PathChildrenCacheEventType type) { this.type = type; return this; } public void unsetType() { this.type = null; } /** Returns true if field type is set (has been assigned a value) and false otherwise */ public boolean isSetType() { return this.type != null; } public void setTypeIsSet(boolean value) { if (!value) { this.type = null; } } public ChildData getData() { return this.data; } public PathChildrenCacheEvent setData(ChildData data) { this.data = data; return this; } public void unsetData() { this.data = null; } /** Returns true if field data is set (has been assigned a value) and false otherwise */ public boolean isSetData() { return this.data != null; } public void setDataIsSet(boolean value) { if (!value) { this.data = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case CACHED_PATH: if (value == null) { unsetCachedPath(); } else { setCachedPath((String)value); } break; case TYPE: if (value == null) { unsetType(); } else { setType((PathChildrenCacheEventType)value); } break; case DATA: if (value == null) { unsetData(); } else { setData((ChildData)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case CACHED_PATH: return getCachedPath(); case TYPE: return getType(); case DATA: return getData(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case CACHED_PATH: return isSetCachedPath(); case TYPE: return isSetType(); case DATA: return isSetData(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof PathChildrenCacheEvent) return this.equals((PathChildrenCacheEvent)that); return false; } public boolean equals(PathChildrenCacheEvent that) { if (that == null) return false; boolean this_present_cachedPath = true && this.isSetCachedPath(); boolean that_present_cachedPath = true && that.isSetCachedPath(); if (this_present_cachedPath || that_present_cachedPath) { if (!(this_present_cachedPath && that_present_cachedPath)) return false; if (!this.cachedPath.equals(that.cachedPath)) return false; } boolean this_present_type = true && this.isSetType(); boolean that_present_type = true && that.isSetType(); if (this_present_type || that_present_type) { if (!(this_present_type && that_present_type)) return false; if (!this.type.equals(that.type)) return false; } boolean this_present_data = true && this.isSetData(); boolean that_present_data = true && that.isSetData(); if (this_present_data || that_present_data) { if (!(this_present_data && that_present_data)) return false; if (!this.data.equals(that.data)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(PathChildrenCacheEvent other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetCachedPath()).compareTo(other.isSetCachedPath()); if (lastComparison != 0) { return lastComparison; } if (isSetCachedPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.cachedPath, other.cachedPath); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetType()).compareTo(other.isSetType()); if (lastComparison != 0) { return lastComparison; } if (isSetType()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.type, other.type); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetData()).compareTo(other.isSetData()); if (lastComparison != 0) { return lastComparison; } if (isSetData()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.data, other.data); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("PathChildrenCacheEvent("); boolean first = true; sb.append("cachedPath:"); if (this.cachedPath == null) { sb.append("null"); } else { sb.append(this.cachedPath); } first = false; if (!first) sb.append(", "); sb.append("type:"); if (this.type == null) { sb.append("null"); } else { sb.append(this.type); } first = false; if (!first) sb.append(", "); sb.append("data:"); if (this.data == null) { sb.append("null"); } else { sb.append(this.data); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (data != null) { data.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class PathChildrenCacheEventStandardSchemeFactory implements SchemeFactory { public PathChildrenCacheEventStandardScheme getScheme() { return new PathChildrenCacheEventStandardScheme(); } } private static class PathChildrenCacheEventStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, PathChildrenCacheEvent struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // CACHED_PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.cachedPath = iprot.readString(); struct.setCachedPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TYPE if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.type = PathChildrenCacheEventType.findByValue(iprot.readI32()); struct.setTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // DATA if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.data = new ChildData(); struct.data.read(iprot); struct.setDataIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, PathChildrenCacheEvent struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.cachedPath != null) { oprot.writeFieldBegin(CACHED_PATH_FIELD_DESC); oprot.writeString(struct.cachedPath); oprot.writeFieldEnd(); } if (struct.type != null) { oprot.writeFieldBegin(TYPE_FIELD_DESC); oprot.writeI32(struct.type.getValue()); oprot.writeFieldEnd(); } if (struct.data != null) { oprot.writeFieldBegin(DATA_FIELD_DESC); struct.data.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class PathChildrenCacheEventTupleSchemeFactory implements SchemeFactory { public PathChildrenCacheEventTupleScheme getScheme() { return new PathChildrenCacheEventTupleScheme(); } } private static class PathChildrenCacheEventTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, PathChildrenCacheEvent struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetCachedPath()) { optionals.set(0); } if (struct.isSetType()) { optionals.set(1); } if (struct.isSetData()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetCachedPath()) { oprot.writeString(struct.cachedPath); } if (struct.isSetType()) { oprot.writeI32(struct.type.getValue()); } if (struct.isSetData()) { struct.data.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, PathChildrenCacheEvent struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.cachedPath = iprot.readString(); struct.setCachedPathIsSet(true); } if (incoming.get(1)) { struct.type = PathChildrenCacheEventType.findByValue(iprot.readI32()); struct.setTypeIsSet(true); } if (incoming.get(2)) { struct.data = new ChildData(); struct.data.read(iprot); struct.setDataIsSet(true); } } } } PathChildrenCacheEventType.java000066400000000000000000000024621245521677600366620ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import java.util.Map; import java.util.HashMap; import org.apache.thrift.TEnum; public enum PathChildrenCacheEventType implements org.apache.thrift.TEnum { CHILD_ADDED(0), CHILD_UPDATED(1), CHILD_REMOVED(2), CONNECTION_SUSPENDED(3), CONNECTION_RECONNECTED(4), CONNECTION_LOST(5), INITIALIZED(6); private final int value; private PathChildrenCacheEventType(int value) { this.value = value; } /** * Get the integer value of this enum value, as defined in the Thrift IDL. */ public int getValue() { return value; } /** * Find a the enum type by its integer value, as defined in the Thrift IDL. * @return null if the value is not found. */ public static PathChildrenCacheEventType findByValue(int value) { switch (value) { case 0: return CHILD_ADDED; case 1: return CHILD_UPDATED; case 2: return CHILD_REMOVED; case 3: return CONNECTION_SUSPENDED; case 4: return CONNECTION_RECONNECTED; case 5: return CONNECTION_LOST; case 6: return INITIALIZED; default: return null; } } } PathChildrenCacheProjection.java000066400000000000000000000266271245521677600370640ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PathChildrenCacheProjection implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("PathChildrenCacheProjection"); private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.STRING, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new PathChildrenCacheProjectionStandardSchemeFactory()); schemes.put(TupleScheme.class, new PathChildrenCacheProjectionTupleSchemeFactory()); } public String id; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ID((short)1, "id"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // ID return ID; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(PathChildrenCacheProjection.class, metaDataMap); } public PathChildrenCacheProjection() { } public PathChildrenCacheProjection( String id) { this(); this.id = id; } /** * Performs a deep copy on other. */ public PathChildrenCacheProjection(PathChildrenCacheProjection other) { if (other.isSetId()) { this.id = other.id; } } public PathChildrenCacheProjection deepCopy() { return new PathChildrenCacheProjection(this); } @Override public void clear() { this.id = null; } public String getId() { return this.id; } public PathChildrenCacheProjection setId(String id) { this.id = id; return this; } public void unsetId() { this.id = null; } /** Returns true if field id is set (has been assigned a value) and false otherwise */ public boolean isSetId() { return this.id != null; } public void setIdIsSet(boolean value) { if (!value) { this.id = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case ID: if (value == null) { unsetId(); } else { setId((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case ID: return getId(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case ID: return isSetId(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof PathChildrenCacheProjection) return this.equals((PathChildrenCacheProjection)that); return false; } public boolean equals(PathChildrenCacheProjection that) { if (that == null) return false; boolean this_present_id = true && this.isSetId(); boolean that_present_id = true && that.isSetId(); if (this_present_id || that_present_id) { if (!(this_present_id && that_present_id)) return false; if (!this.id.equals(that.id)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(PathChildrenCacheProjection other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); if (lastComparison != 0) { return lastComparison; } if (isSetId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("PathChildrenCacheProjection("); boolean first = true; sb.append("id:"); if (this.id == null) { sb.append("null"); } else { sb.append(this.id); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class PathChildrenCacheProjectionStandardSchemeFactory implements SchemeFactory { public PathChildrenCacheProjectionStandardScheme getScheme() { return new PathChildrenCacheProjectionStandardScheme(); } } private static class PathChildrenCacheProjectionStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, PathChildrenCacheProjection struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.id = iprot.readString(); struct.setIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, PathChildrenCacheProjection struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.id != null) { oprot.writeFieldBegin(ID_FIELD_DESC); oprot.writeString(struct.id); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class PathChildrenCacheProjectionTupleSchemeFactory implements SchemeFactory { public PathChildrenCacheProjectionTupleScheme getScheme() { return new PathChildrenCacheProjectionTupleScheme(); } } private static class PathChildrenCacheProjectionTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, PathChildrenCacheProjection struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetId()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetId()) { oprot.writeString(struct.id); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, PathChildrenCacheProjection struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.id = iprot.readString(); struct.setIdIsSet(true); } } } } PathChildrenCacheStartMode.java000066400000000000000000000020461245521677600366370ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import java.util.Map; import java.util.HashMap; import org.apache.thrift.TEnum; public enum PathChildrenCacheStartMode implements org.apache.thrift.TEnum { NORMAL(0), BUILD_INITIAL_CACHE(1), POST_INITIALIZED_EVENT(2); private final int value; private PathChildrenCacheStartMode(int value) { this.value = value; } /** * Get the integer value of this enum value, as defined in the Thrift IDL. */ public int getValue() { return value; } /** * Find a the enum type by its integer value, as defined in the Thrift IDL. * @return null if the value is not found. */ public static PathChildrenCacheStartMode findByValue(int value) { switch (value) { case 0: return NORMAL; case 1: return BUILD_INITIAL_CACHE; case 2: return POST_INITIALIZED_EVENT; default: return null; } } } PersistentEphemeralNodeMode.java000066400000000000000000000022151245521677600371170ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import java.util.Map; import java.util.HashMap; import org.apache.thrift.TEnum; public enum PersistentEphemeralNodeMode implements org.apache.thrift.TEnum { EPHEMERAL(0), EPHEMERAL_SEQUENTIAL(1), PROTECTED_EPHEMERAL(2), PROTECTED_EPHEMERAL_SEQUENTIAL(3); private final int value; private PersistentEphemeralNodeMode(int value) { this.value = value; } /** * Get the integer value of this enum value, as defined in the Thrift IDL. */ public int getValue() { return value; } /** * Find a the enum type by its integer value, as defined in the Thrift IDL. * @return null if the value is not found. */ public static PersistentEphemeralNodeMode findByValue(int value) { switch (value) { case 0: return EPHEMERAL; case 1: return EPHEMERAL_SEQUENTIAL; case 2: return PROTECTED_EPHEMERAL; case 3: return PROTECTED_EPHEMERAL_SEQUENTIAL; default: return null; } } } PersistentEphemeralNodeProjection.java000066400000000000000000000271431245521677600403560ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PersistentEphemeralNodeProjection implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("PersistentEphemeralNodeProjection"); private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.STRING, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new PersistentEphemeralNodeProjectionStandardSchemeFactory()); schemes.put(TupleScheme.class, new PersistentEphemeralNodeProjectionTupleSchemeFactory()); } public String id; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ID((short)1, "id"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // ID return ID; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(PersistentEphemeralNodeProjection.class, metaDataMap); } public PersistentEphemeralNodeProjection() { } public PersistentEphemeralNodeProjection( String id) { this(); this.id = id; } /** * Performs a deep copy on other. */ public PersistentEphemeralNodeProjection(PersistentEphemeralNodeProjection other) { if (other.isSetId()) { this.id = other.id; } } public PersistentEphemeralNodeProjection deepCopy() { return new PersistentEphemeralNodeProjection(this); } @Override public void clear() { this.id = null; } public String getId() { return this.id; } public PersistentEphemeralNodeProjection setId(String id) { this.id = id; return this; } public void unsetId() { this.id = null; } /** Returns true if field id is set (has been assigned a value) and false otherwise */ public boolean isSetId() { return this.id != null; } public void setIdIsSet(boolean value) { if (!value) { this.id = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case ID: if (value == null) { unsetId(); } else { setId((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case ID: return getId(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case ID: return isSetId(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof PersistentEphemeralNodeProjection) return this.equals((PersistentEphemeralNodeProjection)that); return false; } public boolean equals(PersistentEphemeralNodeProjection that) { if (that == null) return false; boolean this_present_id = true && this.isSetId(); boolean that_present_id = true && that.isSetId(); if (this_present_id || that_present_id) { if (!(this_present_id && that_present_id)) return false; if (!this.id.equals(that.id)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(PersistentEphemeralNodeProjection other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); if (lastComparison != 0) { return lastComparison; } if (isSetId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("PersistentEphemeralNodeProjection("); boolean first = true; sb.append("id:"); if (this.id == null) { sb.append("null"); } else { sb.append(this.id); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class PersistentEphemeralNodeProjectionStandardSchemeFactory implements SchemeFactory { public PersistentEphemeralNodeProjectionStandardScheme getScheme() { return new PersistentEphemeralNodeProjectionStandardScheme(); } } private static class PersistentEphemeralNodeProjectionStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, PersistentEphemeralNodeProjection struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.id = iprot.readString(); struct.setIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, PersistentEphemeralNodeProjection struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.id != null) { oprot.writeFieldBegin(ID_FIELD_DESC); oprot.writeString(struct.id); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class PersistentEphemeralNodeProjectionTupleSchemeFactory implements SchemeFactory { public PersistentEphemeralNodeProjectionTupleScheme getScheme() { return new PersistentEphemeralNodeProjectionTupleScheme(); } } private static class PersistentEphemeralNodeProjectionTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, PersistentEphemeralNodeProjection struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetId()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetId()) { oprot.writeString(struct.id); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, PersistentEphemeralNodeProjection struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.id = iprot.readString(); struct.setIdIsSet(true); } } } } ProviderStrategyType.java000066400000000000000000000020741245521677600357030ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import java.util.Map; import java.util.HashMap; import org.apache.thrift.TEnum; public enum ProviderStrategyType implements org.apache.thrift.TEnum { RANDOM(0), STICKY_RANDOM(1), STICKY_ROUND_ROBIN(2), ROUND_ROBIN(3); private final int value; private ProviderStrategyType(int value) { this.value = value; } /** * Get the integer value of this enum value, as defined in the Thrift IDL. */ public int getValue() { return value; } /** * Find a the enum type by its integer value, as defined in the Thrift IDL. * @return null if the value is not found. */ public static ProviderStrategyType findByValue(int value) { switch (value) { case 0: return RANDOM; case 1: return STICKY_RANDOM; case 2: return STICKY_ROUND_ROBIN; case 3: return ROUND_ROBIN; default: return null; } } } SetDataSpec.java000066400000000000000000000663521245521677600336750ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SetDataSpec implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("SetDataSpec"); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField WATCHED_FIELD_DESC = new org.apache.thrift.protocol.TField("watched", org.apache.thrift.protocol.TType.BOOL, (short)2); private static final org.apache.thrift.protocol.TField ASYNC_CONTEXT_FIELD_DESC = new org.apache.thrift.protocol.TField("asyncContext", org.apache.thrift.protocol.TType.STRING, (short)3); private static final org.apache.thrift.protocol.TField COMPRESSED_FIELD_DESC = new org.apache.thrift.protocol.TField("compressed", org.apache.thrift.protocol.TType.BOOL, (short)4); private static final org.apache.thrift.protocol.TField VERSION_FIELD_DESC = new org.apache.thrift.protocol.TField("version", org.apache.thrift.protocol.TType.STRUCT, (short)5); private static final org.apache.thrift.protocol.TField DATA_FIELD_DESC = new org.apache.thrift.protocol.TField("data", org.apache.thrift.protocol.TType.STRING, (short)6); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new SetDataSpecStandardSchemeFactory()); schemes.put(TupleScheme.class, new SetDataSpecTupleSchemeFactory()); } public String path; // required public boolean watched; // required public String asyncContext; // required public boolean compressed; // required public Version version; // required public ByteBuffer data; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PATH((short)1, "path"), WATCHED((short)2, "watched"), ASYNC_CONTEXT((short)3, "asyncContext"), COMPRESSED((short)4, "compressed"), VERSION((short)5, "version"), DATA((short)6, "data"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PATH return PATH; case 2: // WATCHED return WATCHED; case 3: // ASYNC_CONTEXT return ASYNC_CONTEXT; case 4: // COMPRESSED return COMPRESSED; case 5: // VERSION return VERSION; case 6: // DATA return DATA; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __WATCHED_ISSET_ID = 0; private static final int __COMPRESSED_ISSET_ID = 1; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.WATCHED, new org.apache.thrift.meta_data.FieldMetaData("watched", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.ASYNC_CONTEXT, new org.apache.thrift.meta_data.FieldMetaData("asyncContext", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.COMPRESSED, new org.apache.thrift.meta_data.FieldMetaData("compressed", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.VERSION, new org.apache.thrift.meta_data.FieldMetaData("version", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, Version.class))); tmpMap.put(_Fields.DATA, new org.apache.thrift.meta_data.FieldMetaData("data", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(SetDataSpec.class, metaDataMap); } public SetDataSpec() { } public SetDataSpec( String path, boolean watched, String asyncContext, boolean compressed, Version version, ByteBuffer data) { this(); this.path = path; this.watched = watched; setWatchedIsSet(true); this.asyncContext = asyncContext; this.compressed = compressed; setCompressedIsSet(true); this.version = version; this.data = data; } /** * Performs a deep copy on other. */ public SetDataSpec(SetDataSpec other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetPath()) { this.path = other.path; } this.watched = other.watched; if (other.isSetAsyncContext()) { this.asyncContext = other.asyncContext; } this.compressed = other.compressed; if (other.isSetVersion()) { this.version = new Version(other.version); } if (other.isSetData()) { this.data = org.apache.thrift.TBaseHelper.copyBinary(other.data); ; } } public SetDataSpec deepCopy() { return new SetDataSpec(this); } @Override public void clear() { this.path = null; setWatchedIsSet(false); this.watched = false; this.asyncContext = null; setCompressedIsSet(false); this.compressed = false; this.version = null; this.data = null; } public String getPath() { return this.path; } public SetDataSpec setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public boolean isWatched() { return this.watched; } public SetDataSpec setWatched(boolean watched) { this.watched = watched; setWatchedIsSet(true); return this; } public void unsetWatched() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __WATCHED_ISSET_ID); } /** Returns true if field watched is set (has been assigned a value) and false otherwise */ public boolean isSetWatched() { return EncodingUtils.testBit(__isset_bitfield, __WATCHED_ISSET_ID); } public void setWatchedIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __WATCHED_ISSET_ID, value); } public String getAsyncContext() { return this.asyncContext; } public SetDataSpec setAsyncContext(String asyncContext) { this.asyncContext = asyncContext; return this; } public void unsetAsyncContext() { this.asyncContext = null; } /** Returns true if field asyncContext is set (has been assigned a value) and false otherwise */ public boolean isSetAsyncContext() { return this.asyncContext != null; } public void setAsyncContextIsSet(boolean value) { if (!value) { this.asyncContext = null; } } public boolean isCompressed() { return this.compressed; } public SetDataSpec setCompressed(boolean compressed) { this.compressed = compressed; setCompressedIsSet(true); return this; } public void unsetCompressed() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __COMPRESSED_ISSET_ID); } /** Returns true if field compressed is set (has been assigned a value) and false otherwise */ public boolean isSetCompressed() { return EncodingUtils.testBit(__isset_bitfield, __COMPRESSED_ISSET_ID); } public void setCompressedIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __COMPRESSED_ISSET_ID, value); } public Version getVersion() { return this.version; } public SetDataSpec setVersion(Version version) { this.version = version; return this; } public void unsetVersion() { this.version = null; } /** Returns true if field version is set (has been assigned a value) and false otherwise */ public boolean isSetVersion() { return this.version != null; } public void setVersionIsSet(boolean value) { if (!value) { this.version = null; } } public byte[] getData() { setData(org.apache.thrift.TBaseHelper.rightSize(data)); return data == null ? null : data.array(); } public ByteBuffer bufferForData() { return data; } public SetDataSpec setData(byte[] data) { setData(data == null ? (ByteBuffer)null : ByteBuffer.wrap(data)); return this; } public SetDataSpec setData(ByteBuffer data) { this.data = data; return this; } public void unsetData() { this.data = null; } /** Returns true if field data is set (has been assigned a value) and false otherwise */ public boolean isSetData() { return this.data != null; } public void setDataIsSet(boolean value) { if (!value) { this.data = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; case WATCHED: if (value == null) { unsetWatched(); } else { setWatched((Boolean)value); } break; case ASYNC_CONTEXT: if (value == null) { unsetAsyncContext(); } else { setAsyncContext((String)value); } break; case COMPRESSED: if (value == null) { unsetCompressed(); } else { setCompressed((Boolean)value); } break; case VERSION: if (value == null) { unsetVersion(); } else { setVersion((Version)value); } break; case DATA: if (value == null) { unsetData(); } else { setData((ByteBuffer)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PATH: return getPath(); case WATCHED: return Boolean.valueOf(isWatched()); case ASYNC_CONTEXT: return getAsyncContext(); case COMPRESSED: return Boolean.valueOf(isCompressed()); case VERSION: return getVersion(); case DATA: return getData(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PATH: return isSetPath(); case WATCHED: return isSetWatched(); case ASYNC_CONTEXT: return isSetAsyncContext(); case COMPRESSED: return isSetCompressed(); case VERSION: return isSetVersion(); case DATA: return isSetData(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof SetDataSpec) return this.equals((SetDataSpec)that); return false; } public boolean equals(SetDataSpec that) { if (that == null) return false; boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } boolean this_present_watched = true; boolean that_present_watched = true; if (this_present_watched || that_present_watched) { if (!(this_present_watched && that_present_watched)) return false; if (this.watched != that.watched) return false; } boolean this_present_asyncContext = true && this.isSetAsyncContext(); boolean that_present_asyncContext = true && that.isSetAsyncContext(); if (this_present_asyncContext || that_present_asyncContext) { if (!(this_present_asyncContext && that_present_asyncContext)) return false; if (!this.asyncContext.equals(that.asyncContext)) return false; } boolean this_present_compressed = true; boolean that_present_compressed = true; if (this_present_compressed || that_present_compressed) { if (!(this_present_compressed && that_present_compressed)) return false; if (this.compressed != that.compressed) return false; } boolean this_present_version = true && this.isSetVersion(); boolean that_present_version = true && that.isSetVersion(); if (this_present_version || that_present_version) { if (!(this_present_version && that_present_version)) return false; if (!this.version.equals(that.version)) return false; } boolean this_present_data = true && this.isSetData(); boolean that_present_data = true && that.isSetData(); if (this_present_data || that_present_data) { if (!(this_present_data && that_present_data)) return false; if (!this.data.equals(that.data)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(SetDataSpec other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetWatched()).compareTo(other.isSetWatched()); if (lastComparison != 0) { return lastComparison; } if (isSetWatched()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.watched, other.watched); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetAsyncContext()).compareTo(other.isSetAsyncContext()); if (lastComparison != 0) { return lastComparison; } if (isSetAsyncContext()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.asyncContext, other.asyncContext); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetCompressed()).compareTo(other.isSetCompressed()); if (lastComparison != 0) { return lastComparison; } if (isSetCompressed()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.compressed, other.compressed); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetVersion()).compareTo(other.isSetVersion()); if (lastComparison != 0) { return lastComparison; } if (isSetVersion()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.version, other.version); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetData()).compareTo(other.isSetData()); if (lastComparison != 0) { return lastComparison; } if (isSetData()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.data, other.data); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("SetDataSpec("); boolean first = true; sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; if (!first) sb.append(", "); sb.append("watched:"); sb.append(this.watched); first = false; if (!first) sb.append(", "); sb.append("asyncContext:"); if (this.asyncContext == null) { sb.append("null"); } else { sb.append(this.asyncContext); } first = false; if (!first) sb.append(", "); sb.append("compressed:"); sb.append(this.compressed); first = false; if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; if (!first) sb.append(", "); sb.append("data:"); if (this.data == null) { sb.append("null"); } else { org.apache.thrift.TBaseHelper.toString(this.data, sb); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (version != null) { version.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class SetDataSpecStandardSchemeFactory implements SchemeFactory { public SetDataSpecStandardScheme getScheme() { return new SetDataSpecStandardScheme(); } } private static class SetDataSpecStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, SetDataSpec struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // WATCHED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.watched = iprot.readBool(); struct.setWatchedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // ASYNC_CONTEXT if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.asyncContext = iprot.readString(); struct.setAsyncContextIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // COMPRESSED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.compressed = iprot.readBool(); struct.setCompressedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // VERSION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.version = new Version(); struct.version.read(iprot); struct.setVersionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // DATA if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.data = iprot.readBinary(); struct.setDataIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, SetDataSpec struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } oprot.writeFieldBegin(WATCHED_FIELD_DESC); oprot.writeBool(struct.watched); oprot.writeFieldEnd(); if (struct.asyncContext != null) { oprot.writeFieldBegin(ASYNC_CONTEXT_FIELD_DESC); oprot.writeString(struct.asyncContext); oprot.writeFieldEnd(); } oprot.writeFieldBegin(COMPRESSED_FIELD_DESC); oprot.writeBool(struct.compressed); oprot.writeFieldEnd(); if (struct.version != null) { oprot.writeFieldBegin(VERSION_FIELD_DESC); struct.version.write(oprot); oprot.writeFieldEnd(); } if (struct.data != null) { oprot.writeFieldBegin(DATA_FIELD_DESC); oprot.writeBinary(struct.data); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class SetDataSpecTupleSchemeFactory implements SchemeFactory { public SetDataSpecTupleScheme getScheme() { return new SetDataSpecTupleScheme(); } } private static class SetDataSpecTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, SetDataSpec struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetPath()) { optionals.set(0); } if (struct.isSetWatched()) { optionals.set(1); } if (struct.isSetAsyncContext()) { optionals.set(2); } if (struct.isSetCompressed()) { optionals.set(3); } if (struct.isSetVersion()) { optionals.set(4); } if (struct.isSetData()) { optionals.set(5); } oprot.writeBitSet(optionals, 6); if (struct.isSetPath()) { oprot.writeString(struct.path); } if (struct.isSetWatched()) { oprot.writeBool(struct.watched); } if (struct.isSetAsyncContext()) { oprot.writeString(struct.asyncContext); } if (struct.isSetCompressed()) { oprot.writeBool(struct.compressed); } if (struct.isSetVersion()) { struct.version.write(oprot); } if (struct.isSetData()) { oprot.writeBinary(struct.data); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, SetDataSpec struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(6); if (incoming.get(0)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } if (incoming.get(1)) { struct.watched = iprot.readBool(); struct.setWatchedIsSet(true); } if (incoming.get(2)) { struct.asyncContext = iprot.readString(); struct.setAsyncContextIsSet(true); } if (incoming.get(3)) { struct.compressed = iprot.readBool(); struct.setCompressedIsSet(true); } if (incoming.get(4)) { struct.version = new Version(); struct.version.read(iprot); struct.setVersionIsSet(true); } if (incoming.get(5)) { struct.data = iprot.readBinary(); struct.setDataIsSet(true); } } } } curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/Stat.java000066400000000000000000001237301245521677600325210ustar00rootroot00000000000000/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Stat implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("Stat"); private static final org.apache.thrift.protocol.TField CZXID_FIELD_DESC = new org.apache.thrift.protocol.TField("czxid", org.apache.thrift.protocol.TType.I64, (short)1); private static final org.apache.thrift.protocol.TField MZXID_FIELD_DESC = new org.apache.thrift.protocol.TField("mzxid", org.apache.thrift.protocol.TType.I64, (short)2); private static final org.apache.thrift.protocol.TField CTIME_FIELD_DESC = new org.apache.thrift.protocol.TField("ctime", org.apache.thrift.protocol.TType.I64, (short)3); private static final org.apache.thrift.protocol.TField MTIME_FIELD_DESC = new org.apache.thrift.protocol.TField("mtime", org.apache.thrift.protocol.TType.I64, (short)4); private static final org.apache.thrift.protocol.TField VERSION_FIELD_DESC = new org.apache.thrift.protocol.TField("version", org.apache.thrift.protocol.TType.I32, (short)5); private static final org.apache.thrift.protocol.TField CVERSION_FIELD_DESC = new org.apache.thrift.protocol.TField("cversion", org.apache.thrift.protocol.TType.I32, (short)6); private static final org.apache.thrift.protocol.TField AVERSION_FIELD_DESC = new org.apache.thrift.protocol.TField("aversion", org.apache.thrift.protocol.TType.I32, (short)7); private static final org.apache.thrift.protocol.TField EPHEMERAL_OWNER_FIELD_DESC = new org.apache.thrift.protocol.TField("ephemeralOwner", org.apache.thrift.protocol.TType.I64, (short)8); private static final org.apache.thrift.protocol.TField DATA_LENGTH_FIELD_DESC = new org.apache.thrift.protocol.TField("dataLength", org.apache.thrift.protocol.TType.I32, (short)9); private static final org.apache.thrift.protocol.TField NUM_CHILDREN_FIELD_DESC = new org.apache.thrift.protocol.TField("numChildren", org.apache.thrift.protocol.TType.I32, (short)10); private static final org.apache.thrift.protocol.TField PZXID_FIELD_DESC = new org.apache.thrift.protocol.TField("pzxid", org.apache.thrift.protocol.TType.I64, (short)11); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new StatStandardSchemeFactory()); schemes.put(TupleScheme.class, new StatTupleSchemeFactory()); } public long czxid; // required public long mzxid; // required public long ctime; // required public long mtime; // required public int version; // required public int cversion; // required public int aversion; // required public long ephemeralOwner; // required public int dataLength; // required public int numChildren; // required public long pzxid; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { CZXID((short)1, "czxid"), MZXID((short)2, "mzxid"), CTIME((short)3, "ctime"), MTIME((short)4, "mtime"), VERSION((short)5, "version"), CVERSION((short)6, "cversion"), AVERSION((short)7, "aversion"), EPHEMERAL_OWNER((short)8, "ephemeralOwner"), DATA_LENGTH((short)9, "dataLength"), NUM_CHILDREN((short)10, "numChildren"), PZXID((short)11, "pzxid"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // CZXID return CZXID; case 2: // MZXID return MZXID; case 3: // CTIME return CTIME; case 4: // MTIME return MTIME; case 5: // VERSION return VERSION; case 6: // CVERSION return CVERSION; case 7: // AVERSION return AVERSION; case 8: // EPHEMERAL_OWNER return EPHEMERAL_OWNER; case 9: // DATA_LENGTH return DATA_LENGTH; case 10: // NUM_CHILDREN return NUM_CHILDREN; case 11: // PZXID return PZXID; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __CZXID_ISSET_ID = 0; private static final int __MZXID_ISSET_ID = 1; private static final int __CTIME_ISSET_ID = 2; private static final int __MTIME_ISSET_ID = 3; private static final int __VERSION_ISSET_ID = 4; private static final int __CVERSION_ISSET_ID = 5; private static final int __AVERSION_ISSET_ID = 6; private static final int __EPHEMERALOWNER_ISSET_ID = 7; private static final int __DATALENGTH_ISSET_ID = 8; private static final int __NUMCHILDREN_ISSET_ID = 9; private static final int __PZXID_ISSET_ID = 10; private short __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.CZXID, new org.apache.thrift.meta_data.FieldMetaData("czxid", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); tmpMap.put(_Fields.MZXID, new org.apache.thrift.meta_data.FieldMetaData("mzxid", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); tmpMap.put(_Fields.CTIME, new org.apache.thrift.meta_data.FieldMetaData("ctime", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); tmpMap.put(_Fields.MTIME, new org.apache.thrift.meta_data.FieldMetaData("mtime", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); tmpMap.put(_Fields.VERSION, new org.apache.thrift.meta_data.FieldMetaData("version", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.CVERSION, new org.apache.thrift.meta_data.FieldMetaData("cversion", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.AVERSION, new org.apache.thrift.meta_data.FieldMetaData("aversion", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.EPHEMERAL_OWNER, new org.apache.thrift.meta_data.FieldMetaData("ephemeralOwner", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); tmpMap.put(_Fields.DATA_LENGTH, new org.apache.thrift.meta_data.FieldMetaData("dataLength", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.NUM_CHILDREN, new org.apache.thrift.meta_data.FieldMetaData("numChildren", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.PZXID, new org.apache.thrift.meta_data.FieldMetaData("pzxid", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(Stat.class, metaDataMap); } public Stat() { } public Stat( long czxid, long mzxid, long ctime, long mtime, int version, int cversion, int aversion, long ephemeralOwner, int dataLength, int numChildren, long pzxid) { this(); this.czxid = czxid; setCzxidIsSet(true); this.mzxid = mzxid; setMzxidIsSet(true); this.ctime = ctime; setCtimeIsSet(true); this.mtime = mtime; setMtimeIsSet(true); this.version = version; setVersionIsSet(true); this.cversion = cversion; setCversionIsSet(true); this.aversion = aversion; setAversionIsSet(true); this.ephemeralOwner = ephemeralOwner; setEphemeralOwnerIsSet(true); this.dataLength = dataLength; setDataLengthIsSet(true); this.numChildren = numChildren; setNumChildrenIsSet(true); this.pzxid = pzxid; setPzxidIsSet(true); } /** * Performs a deep copy on other. */ public Stat(Stat other) { __isset_bitfield = other.__isset_bitfield; this.czxid = other.czxid; this.mzxid = other.mzxid; this.ctime = other.ctime; this.mtime = other.mtime; this.version = other.version; this.cversion = other.cversion; this.aversion = other.aversion; this.ephemeralOwner = other.ephemeralOwner; this.dataLength = other.dataLength; this.numChildren = other.numChildren; this.pzxid = other.pzxid; } public Stat deepCopy() { return new Stat(this); } @Override public void clear() { setCzxidIsSet(false); this.czxid = 0; setMzxidIsSet(false); this.mzxid = 0; setCtimeIsSet(false); this.ctime = 0; setMtimeIsSet(false); this.mtime = 0; setVersionIsSet(false); this.version = 0; setCversionIsSet(false); this.cversion = 0; setAversionIsSet(false); this.aversion = 0; setEphemeralOwnerIsSet(false); this.ephemeralOwner = 0; setDataLengthIsSet(false); this.dataLength = 0; setNumChildrenIsSet(false); this.numChildren = 0; setPzxidIsSet(false); this.pzxid = 0; } public long getCzxid() { return this.czxid; } public Stat setCzxid(long czxid) { this.czxid = czxid; setCzxidIsSet(true); return this; } public void unsetCzxid() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __CZXID_ISSET_ID); } /** Returns true if field czxid is set (has been assigned a value) and false otherwise */ public boolean isSetCzxid() { return EncodingUtils.testBit(__isset_bitfield, __CZXID_ISSET_ID); } public void setCzxidIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __CZXID_ISSET_ID, value); } public long getMzxid() { return this.mzxid; } public Stat setMzxid(long mzxid) { this.mzxid = mzxid; setMzxidIsSet(true); return this; } public void unsetMzxid() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __MZXID_ISSET_ID); } /** Returns true if field mzxid is set (has been assigned a value) and false otherwise */ public boolean isSetMzxid() { return EncodingUtils.testBit(__isset_bitfield, __MZXID_ISSET_ID); } public void setMzxidIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __MZXID_ISSET_ID, value); } public long getCtime() { return this.ctime; } public Stat setCtime(long ctime) { this.ctime = ctime; setCtimeIsSet(true); return this; } public void unsetCtime() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __CTIME_ISSET_ID); } /** Returns true if field ctime is set (has been assigned a value) and false otherwise */ public boolean isSetCtime() { return EncodingUtils.testBit(__isset_bitfield, __CTIME_ISSET_ID); } public void setCtimeIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __CTIME_ISSET_ID, value); } public long getMtime() { return this.mtime; } public Stat setMtime(long mtime) { this.mtime = mtime; setMtimeIsSet(true); return this; } public void unsetMtime() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __MTIME_ISSET_ID); } /** Returns true if field mtime is set (has been assigned a value) and false otherwise */ public boolean isSetMtime() { return EncodingUtils.testBit(__isset_bitfield, __MTIME_ISSET_ID); } public void setMtimeIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __MTIME_ISSET_ID, value); } public int getVersion() { return this.version; } public Stat setVersion(int version) { this.version = version; setVersionIsSet(true); return this; } public void unsetVersion() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __VERSION_ISSET_ID); } /** Returns true if field version is set (has been assigned a value) and false otherwise */ public boolean isSetVersion() { return EncodingUtils.testBit(__isset_bitfield, __VERSION_ISSET_ID); } public void setVersionIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __VERSION_ISSET_ID, value); } public int getCversion() { return this.cversion; } public Stat setCversion(int cversion) { this.cversion = cversion; setCversionIsSet(true); return this; } public void unsetCversion() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __CVERSION_ISSET_ID); } /** Returns true if field cversion is set (has been assigned a value) and false otherwise */ public boolean isSetCversion() { return EncodingUtils.testBit(__isset_bitfield, __CVERSION_ISSET_ID); } public void setCversionIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __CVERSION_ISSET_ID, value); } public int getAversion() { return this.aversion; } public Stat setAversion(int aversion) { this.aversion = aversion; setAversionIsSet(true); return this; } public void unsetAversion() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __AVERSION_ISSET_ID); } /** Returns true if field aversion is set (has been assigned a value) and false otherwise */ public boolean isSetAversion() { return EncodingUtils.testBit(__isset_bitfield, __AVERSION_ISSET_ID); } public void setAversionIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __AVERSION_ISSET_ID, value); } public long getEphemeralOwner() { return this.ephemeralOwner; } public Stat setEphemeralOwner(long ephemeralOwner) { this.ephemeralOwner = ephemeralOwner; setEphemeralOwnerIsSet(true); return this; } public void unsetEphemeralOwner() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __EPHEMERALOWNER_ISSET_ID); } /** Returns true if field ephemeralOwner is set (has been assigned a value) and false otherwise */ public boolean isSetEphemeralOwner() { return EncodingUtils.testBit(__isset_bitfield, __EPHEMERALOWNER_ISSET_ID); } public void setEphemeralOwnerIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __EPHEMERALOWNER_ISSET_ID, value); } public int getDataLength() { return this.dataLength; } public Stat setDataLength(int dataLength) { this.dataLength = dataLength; setDataLengthIsSet(true); return this; } public void unsetDataLength() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __DATALENGTH_ISSET_ID); } /** Returns true if field dataLength is set (has been assigned a value) and false otherwise */ public boolean isSetDataLength() { return EncodingUtils.testBit(__isset_bitfield, __DATALENGTH_ISSET_ID); } public void setDataLengthIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __DATALENGTH_ISSET_ID, value); } public int getNumChildren() { return this.numChildren; } public Stat setNumChildren(int numChildren) { this.numChildren = numChildren; setNumChildrenIsSet(true); return this; } public void unsetNumChildren() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __NUMCHILDREN_ISSET_ID); } /** Returns true if field numChildren is set (has been assigned a value) and false otherwise */ public boolean isSetNumChildren() { return EncodingUtils.testBit(__isset_bitfield, __NUMCHILDREN_ISSET_ID); } public void setNumChildrenIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __NUMCHILDREN_ISSET_ID, value); } public long getPzxid() { return this.pzxid; } public Stat setPzxid(long pzxid) { this.pzxid = pzxid; setPzxidIsSet(true); return this; } public void unsetPzxid() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __PZXID_ISSET_ID); } /** Returns true if field pzxid is set (has been assigned a value) and false otherwise */ public boolean isSetPzxid() { return EncodingUtils.testBit(__isset_bitfield, __PZXID_ISSET_ID); } public void setPzxidIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __PZXID_ISSET_ID, value); } public void setFieldValue(_Fields field, Object value) { switch (field) { case CZXID: if (value == null) { unsetCzxid(); } else { setCzxid((Long)value); } break; case MZXID: if (value == null) { unsetMzxid(); } else { setMzxid((Long)value); } break; case CTIME: if (value == null) { unsetCtime(); } else { setCtime((Long)value); } break; case MTIME: if (value == null) { unsetMtime(); } else { setMtime((Long)value); } break; case VERSION: if (value == null) { unsetVersion(); } else { setVersion((Integer)value); } break; case CVERSION: if (value == null) { unsetCversion(); } else { setCversion((Integer)value); } break; case AVERSION: if (value == null) { unsetAversion(); } else { setAversion((Integer)value); } break; case EPHEMERAL_OWNER: if (value == null) { unsetEphemeralOwner(); } else { setEphemeralOwner((Long)value); } break; case DATA_LENGTH: if (value == null) { unsetDataLength(); } else { setDataLength((Integer)value); } break; case NUM_CHILDREN: if (value == null) { unsetNumChildren(); } else { setNumChildren((Integer)value); } break; case PZXID: if (value == null) { unsetPzxid(); } else { setPzxid((Long)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case CZXID: return Long.valueOf(getCzxid()); case MZXID: return Long.valueOf(getMzxid()); case CTIME: return Long.valueOf(getCtime()); case MTIME: return Long.valueOf(getMtime()); case VERSION: return Integer.valueOf(getVersion()); case CVERSION: return Integer.valueOf(getCversion()); case AVERSION: return Integer.valueOf(getAversion()); case EPHEMERAL_OWNER: return Long.valueOf(getEphemeralOwner()); case DATA_LENGTH: return Integer.valueOf(getDataLength()); case NUM_CHILDREN: return Integer.valueOf(getNumChildren()); case PZXID: return Long.valueOf(getPzxid()); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case CZXID: return isSetCzxid(); case MZXID: return isSetMzxid(); case CTIME: return isSetCtime(); case MTIME: return isSetMtime(); case VERSION: return isSetVersion(); case CVERSION: return isSetCversion(); case AVERSION: return isSetAversion(); case EPHEMERAL_OWNER: return isSetEphemeralOwner(); case DATA_LENGTH: return isSetDataLength(); case NUM_CHILDREN: return isSetNumChildren(); case PZXID: return isSetPzxid(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof Stat) return this.equals((Stat)that); return false; } public boolean equals(Stat that) { if (that == null) return false; boolean this_present_czxid = true; boolean that_present_czxid = true; if (this_present_czxid || that_present_czxid) { if (!(this_present_czxid && that_present_czxid)) return false; if (this.czxid != that.czxid) return false; } boolean this_present_mzxid = true; boolean that_present_mzxid = true; if (this_present_mzxid || that_present_mzxid) { if (!(this_present_mzxid && that_present_mzxid)) return false; if (this.mzxid != that.mzxid) return false; } boolean this_present_ctime = true; boolean that_present_ctime = true; if (this_present_ctime || that_present_ctime) { if (!(this_present_ctime && that_present_ctime)) return false; if (this.ctime != that.ctime) return false; } boolean this_present_mtime = true; boolean that_present_mtime = true; if (this_present_mtime || that_present_mtime) { if (!(this_present_mtime && that_present_mtime)) return false; if (this.mtime != that.mtime) return false; } boolean this_present_version = true; boolean that_present_version = true; if (this_present_version || that_present_version) { if (!(this_present_version && that_present_version)) return false; if (this.version != that.version) return false; } boolean this_present_cversion = true; boolean that_present_cversion = true; if (this_present_cversion || that_present_cversion) { if (!(this_present_cversion && that_present_cversion)) return false; if (this.cversion != that.cversion) return false; } boolean this_present_aversion = true; boolean that_present_aversion = true; if (this_present_aversion || that_present_aversion) { if (!(this_present_aversion && that_present_aversion)) return false; if (this.aversion != that.aversion) return false; } boolean this_present_ephemeralOwner = true; boolean that_present_ephemeralOwner = true; if (this_present_ephemeralOwner || that_present_ephemeralOwner) { if (!(this_present_ephemeralOwner && that_present_ephemeralOwner)) return false; if (this.ephemeralOwner != that.ephemeralOwner) return false; } boolean this_present_dataLength = true; boolean that_present_dataLength = true; if (this_present_dataLength || that_present_dataLength) { if (!(this_present_dataLength && that_present_dataLength)) return false; if (this.dataLength != that.dataLength) return false; } boolean this_present_numChildren = true; boolean that_present_numChildren = true; if (this_present_numChildren || that_present_numChildren) { if (!(this_present_numChildren && that_present_numChildren)) return false; if (this.numChildren != that.numChildren) return false; } boolean this_present_pzxid = true; boolean that_present_pzxid = true; if (this_present_pzxid || that_present_pzxid) { if (!(this_present_pzxid && that_present_pzxid)) return false; if (this.pzxid != that.pzxid) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(Stat other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetCzxid()).compareTo(other.isSetCzxid()); if (lastComparison != 0) { return lastComparison; } if (isSetCzxid()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.czxid, other.czxid); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetMzxid()).compareTo(other.isSetMzxid()); if (lastComparison != 0) { return lastComparison; } if (isSetMzxid()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.mzxid, other.mzxid); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetCtime()).compareTo(other.isSetCtime()); if (lastComparison != 0) { return lastComparison; } if (isSetCtime()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ctime, other.ctime); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetMtime()).compareTo(other.isSetMtime()); if (lastComparison != 0) { return lastComparison; } if (isSetMtime()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.mtime, other.mtime); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetVersion()).compareTo(other.isSetVersion()); if (lastComparison != 0) { return lastComparison; } if (isSetVersion()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.version, other.version); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetCversion()).compareTo(other.isSetCversion()); if (lastComparison != 0) { return lastComparison; } if (isSetCversion()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.cversion, other.cversion); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetAversion()).compareTo(other.isSetAversion()); if (lastComparison != 0) { return lastComparison; } if (isSetAversion()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.aversion, other.aversion); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEphemeralOwner()).compareTo(other.isSetEphemeralOwner()); if (lastComparison != 0) { return lastComparison; } if (isSetEphemeralOwner()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ephemeralOwner, other.ephemeralOwner); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetDataLength()).compareTo(other.isSetDataLength()); if (lastComparison != 0) { return lastComparison; } if (isSetDataLength()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.dataLength, other.dataLength); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetNumChildren()).compareTo(other.isSetNumChildren()); if (lastComparison != 0) { return lastComparison; } if (isSetNumChildren()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.numChildren, other.numChildren); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPzxid()).compareTo(other.isSetPzxid()); if (lastComparison != 0) { return lastComparison; } if (isSetPzxid()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.pzxid, other.pzxid); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("Stat("); boolean first = true; sb.append("czxid:"); sb.append(this.czxid); first = false; if (!first) sb.append(", "); sb.append("mzxid:"); sb.append(this.mzxid); first = false; if (!first) sb.append(", "); sb.append("ctime:"); sb.append(this.ctime); first = false; if (!first) sb.append(", "); sb.append("mtime:"); sb.append(this.mtime); first = false; if (!first) sb.append(", "); sb.append("version:"); sb.append(this.version); first = false; if (!first) sb.append(", "); sb.append("cversion:"); sb.append(this.cversion); first = false; if (!first) sb.append(", "); sb.append("aversion:"); sb.append(this.aversion); first = false; if (!first) sb.append(", "); sb.append("ephemeralOwner:"); sb.append(this.ephemeralOwner); first = false; if (!first) sb.append(", "); sb.append("dataLength:"); sb.append(this.dataLength); first = false; if (!first) sb.append(", "); sb.append("numChildren:"); sb.append(this.numChildren); first = false; if (!first) sb.append(", "); sb.append("pzxid:"); sb.append(this.pzxid); first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class StatStandardSchemeFactory implements SchemeFactory { public StatStandardScheme getScheme() { return new StatStandardScheme(); } } private static class StatStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, Stat struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // CZXID if (schemeField.type == org.apache.thrift.protocol.TType.I64) { struct.czxid = iprot.readI64(); struct.setCzxidIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // MZXID if (schemeField.type == org.apache.thrift.protocol.TType.I64) { struct.mzxid = iprot.readI64(); struct.setMzxidIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // CTIME if (schemeField.type == org.apache.thrift.protocol.TType.I64) { struct.ctime = iprot.readI64(); struct.setCtimeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // MTIME if (schemeField.type == org.apache.thrift.protocol.TType.I64) { struct.mtime = iprot.readI64(); struct.setMtimeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // VERSION if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.version = iprot.readI32(); struct.setVersionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // CVERSION if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.cversion = iprot.readI32(); struct.setCversionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 7: // AVERSION if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.aversion = iprot.readI32(); struct.setAversionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 8: // EPHEMERAL_OWNER if (schemeField.type == org.apache.thrift.protocol.TType.I64) { struct.ephemeralOwner = iprot.readI64(); struct.setEphemeralOwnerIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 9: // DATA_LENGTH if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.dataLength = iprot.readI32(); struct.setDataLengthIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 10: // NUM_CHILDREN if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.numChildren = iprot.readI32(); struct.setNumChildrenIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 11: // PZXID if (schemeField.type == org.apache.thrift.protocol.TType.I64) { struct.pzxid = iprot.readI64(); struct.setPzxidIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, Stat struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldBegin(CZXID_FIELD_DESC); oprot.writeI64(struct.czxid); oprot.writeFieldEnd(); oprot.writeFieldBegin(MZXID_FIELD_DESC); oprot.writeI64(struct.mzxid); oprot.writeFieldEnd(); oprot.writeFieldBegin(CTIME_FIELD_DESC); oprot.writeI64(struct.ctime); oprot.writeFieldEnd(); oprot.writeFieldBegin(MTIME_FIELD_DESC); oprot.writeI64(struct.mtime); oprot.writeFieldEnd(); oprot.writeFieldBegin(VERSION_FIELD_DESC); oprot.writeI32(struct.version); oprot.writeFieldEnd(); oprot.writeFieldBegin(CVERSION_FIELD_DESC); oprot.writeI32(struct.cversion); oprot.writeFieldEnd(); oprot.writeFieldBegin(AVERSION_FIELD_DESC); oprot.writeI32(struct.aversion); oprot.writeFieldEnd(); oprot.writeFieldBegin(EPHEMERAL_OWNER_FIELD_DESC); oprot.writeI64(struct.ephemeralOwner); oprot.writeFieldEnd(); oprot.writeFieldBegin(DATA_LENGTH_FIELD_DESC); oprot.writeI32(struct.dataLength); oprot.writeFieldEnd(); oprot.writeFieldBegin(NUM_CHILDREN_FIELD_DESC); oprot.writeI32(struct.numChildren); oprot.writeFieldEnd(); oprot.writeFieldBegin(PZXID_FIELD_DESC); oprot.writeI64(struct.pzxid); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class StatTupleSchemeFactory implements SchemeFactory { public StatTupleScheme getScheme() { return new StatTupleScheme(); } } private static class StatTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, Stat struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetCzxid()) { optionals.set(0); } if (struct.isSetMzxid()) { optionals.set(1); } if (struct.isSetCtime()) { optionals.set(2); } if (struct.isSetMtime()) { optionals.set(3); } if (struct.isSetVersion()) { optionals.set(4); } if (struct.isSetCversion()) { optionals.set(5); } if (struct.isSetAversion()) { optionals.set(6); } if (struct.isSetEphemeralOwner()) { optionals.set(7); } if (struct.isSetDataLength()) { optionals.set(8); } if (struct.isSetNumChildren()) { optionals.set(9); } if (struct.isSetPzxid()) { optionals.set(10); } oprot.writeBitSet(optionals, 11); if (struct.isSetCzxid()) { oprot.writeI64(struct.czxid); } if (struct.isSetMzxid()) { oprot.writeI64(struct.mzxid); } if (struct.isSetCtime()) { oprot.writeI64(struct.ctime); } if (struct.isSetMtime()) { oprot.writeI64(struct.mtime); } if (struct.isSetVersion()) { oprot.writeI32(struct.version); } if (struct.isSetCversion()) { oprot.writeI32(struct.cversion); } if (struct.isSetAversion()) { oprot.writeI32(struct.aversion); } if (struct.isSetEphemeralOwner()) { oprot.writeI64(struct.ephemeralOwner); } if (struct.isSetDataLength()) { oprot.writeI32(struct.dataLength); } if (struct.isSetNumChildren()) { oprot.writeI32(struct.numChildren); } if (struct.isSetPzxid()) { oprot.writeI64(struct.pzxid); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, Stat struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(11); if (incoming.get(0)) { struct.czxid = iprot.readI64(); struct.setCzxidIsSet(true); } if (incoming.get(1)) { struct.mzxid = iprot.readI64(); struct.setMzxidIsSet(true); } if (incoming.get(2)) { struct.ctime = iprot.readI64(); struct.setCtimeIsSet(true); } if (incoming.get(3)) { struct.mtime = iprot.readI64(); struct.setMtimeIsSet(true); } if (incoming.get(4)) { struct.version = iprot.readI32(); struct.setVersionIsSet(true); } if (incoming.get(5)) { struct.cversion = iprot.readI32(); struct.setCversionIsSet(true); } if (incoming.get(6)) { struct.aversion = iprot.readI32(); struct.setAversionIsSet(true); } if (incoming.get(7)) { struct.ephemeralOwner = iprot.readI64(); struct.setEphemeralOwnerIsSet(true); } if (incoming.get(8)) { struct.dataLength = iprot.readI32(); struct.setDataLengthIsSet(true); } if (incoming.get(9)) { struct.numChildren = iprot.readI32(); struct.setNumChildrenIsSet(true); } if (incoming.get(10)) { struct.pzxid = iprot.readI64(); struct.setPzxidIsSet(true); } } } } curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/Version.java000066400000000000000000000265121245521677600332330ustar00rootroot00000000000000/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Version implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("Version"); private static final org.apache.thrift.protocol.TField VERSION_FIELD_DESC = new org.apache.thrift.protocol.TField("version", org.apache.thrift.protocol.TType.I32, (short)1); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new VersionStandardSchemeFactory()); schemes.put(TupleScheme.class, new VersionTupleSchemeFactory()); } public int version; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { VERSION((short)1, "version"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // VERSION return VERSION; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __VERSION_ISSET_ID = 0; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.VERSION, new org.apache.thrift.meta_data.FieldMetaData("version", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(Version.class, metaDataMap); } public Version() { } public Version( int version) { this(); this.version = version; setVersionIsSet(true); } /** * Performs a deep copy on other. */ public Version(Version other) { __isset_bitfield = other.__isset_bitfield; this.version = other.version; } public Version deepCopy() { return new Version(this); } @Override public void clear() { setVersionIsSet(false); this.version = 0; } public int getVersion() { return this.version; } public Version setVersion(int version) { this.version = version; setVersionIsSet(true); return this; } public void unsetVersion() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __VERSION_ISSET_ID); } /** Returns true if field version is set (has been assigned a value) and false otherwise */ public boolean isSetVersion() { return EncodingUtils.testBit(__isset_bitfield, __VERSION_ISSET_ID); } public void setVersionIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __VERSION_ISSET_ID, value); } public void setFieldValue(_Fields field, Object value) { switch (field) { case VERSION: if (value == null) { unsetVersion(); } else { setVersion((Integer)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case VERSION: return Integer.valueOf(getVersion()); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case VERSION: return isSetVersion(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof Version) return this.equals((Version)that); return false; } public boolean equals(Version that) { if (that == null) return false; boolean this_present_version = true; boolean that_present_version = true; if (this_present_version || that_present_version) { if (!(this_present_version && that_present_version)) return false; if (this.version != that.version) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(Version other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetVersion()).compareTo(other.isSetVersion()); if (lastComparison != 0) { return lastComparison; } if (isSetVersion()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.version, other.version); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("Version("); boolean first = true; sb.append("version:"); sb.append(this.version); first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class VersionStandardSchemeFactory implements SchemeFactory { public VersionStandardScheme getScheme() { return new VersionStandardScheme(); } } private static class VersionStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, Version struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // VERSION if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.version = iprot.readI32(); struct.setVersionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, Version struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldBegin(VERSION_FIELD_DESC); oprot.writeI32(struct.version); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class VersionTupleSchemeFactory implements SchemeFactory { public VersionTupleScheme getScheme() { return new VersionTupleScheme(); } } private static class VersionTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, Version struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetVersion()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetVersion()) { oprot.writeI32(struct.version); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, Version struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.version = iprot.readI32(); struct.setVersionIsSet(true); } } } } WatchedEvent.java000066400000000000000000000436631245521677600341160ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WatchedEvent implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("WatchedEvent"); private static final org.apache.thrift.protocol.TField KEEPER_STATE_FIELD_DESC = new org.apache.thrift.protocol.TField("keeperState", org.apache.thrift.protocol.TType.I32, (short)1); private static final org.apache.thrift.protocol.TField EVENT_TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("eventType", org.apache.thrift.protocol.TType.I32, (short)2); private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("path", org.apache.thrift.protocol.TType.STRING, (short)3); private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); static { schemes.put(StandardScheme.class, new WatchedEventStandardSchemeFactory()); schemes.put(TupleScheme.class, new WatchedEventTupleSchemeFactory()); } /** * * @see KeeperState */ public KeeperState keeperState; // required /** * * @see EventType */ public EventType eventType; // required public String path; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { /** * * @see KeeperState */ KEEPER_STATE((short)1, "keeperState"), /** * * @see EventType */ EVENT_TYPE((short)2, "eventType"), PATH((short)3, "path"); private static final Map byName = new HashMap(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // KEEPER_STATE return KEEPER_STATE; case 2: // EVENT_TYPE return EVENT_TYPE; case 3: // PATH return PATH; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.KEEPER_STATE, new org.apache.thrift.meta_data.FieldMetaData("keeperState", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, KeeperState.class))); tmpMap.put(_Fields.EVENT_TYPE, new org.apache.thrift.meta_data.FieldMetaData("eventType", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, EventType.class))); tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData("path", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(WatchedEvent.class, metaDataMap); } public WatchedEvent() { } public WatchedEvent( KeeperState keeperState, EventType eventType, String path) { this(); this.keeperState = keeperState; this.eventType = eventType; this.path = path; } /** * Performs a deep copy on other. */ public WatchedEvent(WatchedEvent other) { if (other.isSetKeeperState()) { this.keeperState = other.keeperState; } if (other.isSetEventType()) { this.eventType = other.eventType; } if (other.isSetPath()) { this.path = other.path; } } public WatchedEvent deepCopy() { return new WatchedEvent(this); } @Override public void clear() { this.keeperState = null; this.eventType = null; this.path = null; } /** * * @see KeeperState */ public KeeperState getKeeperState() { return this.keeperState; } /** * * @see KeeperState */ public WatchedEvent setKeeperState(KeeperState keeperState) { this.keeperState = keeperState; return this; } public void unsetKeeperState() { this.keeperState = null; } /** Returns true if field keeperState is set (has been assigned a value) and false otherwise */ public boolean isSetKeeperState() { return this.keeperState != null; } public void setKeeperStateIsSet(boolean value) { if (!value) { this.keeperState = null; } } /** * * @see EventType */ public EventType getEventType() { return this.eventType; } /** * * @see EventType */ public WatchedEvent setEventType(EventType eventType) { this.eventType = eventType; return this; } public void unsetEventType() { this.eventType = null; } /** Returns true if field eventType is set (has been assigned a value) and false otherwise */ public boolean isSetEventType() { return this.eventType != null; } public void setEventTypeIsSet(boolean value) { if (!value) { this.eventType = null; } } public String getPath() { return this.path; } public WatchedEvent setPath(String path) { this.path = path; return this; } public void unsetPath() { this.path = null; } /** Returns true if field path is set (has been assigned a value) and false otherwise */ public boolean isSetPath() { return this.path != null; } public void setPathIsSet(boolean value) { if (!value) { this.path = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case KEEPER_STATE: if (value == null) { unsetKeeperState(); } else { setKeeperState((KeeperState)value); } break; case EVENT_TYPE: if (value == null) { unsetEventType(); } else { setEventType((EventType)value); } break; case PATH: if (value == null) { unsetPath(); } else { setPath((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case KEEPER_STATE: return getKeeperState(); case EVENT_TYPE: return getEventType(); case PATH: return getPath(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case KEEPER_STATE: return isSetKeeperState(); case EVENT_TYPE: return isSetEventType(); case PATH: return isSetPath(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof WatchedEvent) return this.equals((WatchedEvent)that); return false; } public boolean equals(WatchedEvent that) { if (that == null) return false; boolean this_present_keeperState = true && this.isSetKeeperState(); boolean that_present_keeperState = true && that.isSetKeeperState(); if (this_present_keeperState || that_present_keeperState) { if (!(this_present_keeperState && that_present_keeperState)) return false; if (!this.keeperState.equals(that.keeperState)) return false; } boolean this_present_eventType = true && this.isSetEventType(); boolean that_present_eventType = true && that.isSetEventType(); if (this_present_eventType || that_present_eventType) { if (!(this_present_eventType && that_present_eventType)) return false; if (!this.eventType.equals(that.eventType)) return false; } boolean this_present_path = true && this.isSetPath(); boolean that_present_path = true && that.isSetPath(); if (this_present_path || that_present_path) { if (!(this_present_path && that_present_path)) return false; if (!this.path.equals(that.path)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(WatchedEvent other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetKeeperState()).compareTo(other.isSetKeeperState()); if (lastComparison != 0) { return lastComparison; } if (isSetKeeperState()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.keeperState, other.keeperState); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEventType()).compareTo(other.isSetEventType()); if (lastComparison != 0) { return lastComparison; } if (isSetEventType()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.eventType, other.eventType); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath()); if (lastComparison != 0) { return lastComparison; } if (isSetPath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("WatchedEvent("); boolean first = true; sb.append("keeperState:"); if (this.keeperState == null) { sb.append("null"); } else { sb.append(this.keeperState); } first = false; if (!first) sb.append(", "); sb.append("eventType:"); if (this.eventType == null) { sb.append("null"); } else { sb.append(this.eventType); } first = false; if (!first) sb.append(", "); sb.append("path:"); if (this.path == null) { sb.append("null"); } else { sb.append(this.path); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class WatchedEventStandardSchemeFactory implements SchemeFactory { public WatchedEventStandardScheme getScheme() { return new WatchedEventStandardScheme(); } } private static class WatchedEventStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, WatchedEvent struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // KEEPER_STATE if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.keeperState = KeeperState.findByValue(iprot.readI32()); struct.setKeeperStateIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // EVENT_TYPE if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.eventType = EventType.findByValue(iprot.readI32()); struct.setEventTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.path = iprot.readString(); struct.setPathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, WatchedEvent struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.keeperState != null) { oprot.writeFieldBegin(KEEPER_STATE_FIELD_DESC); oprot.writeI32(struct.keeperState.getValue()); oprot.writeFieldEnd(); } if (struct.eventType != null) { oprot.writeFieldBegin(EVENT_TYPE_FIELD_DESC); oprot.writeI32(struct.eventType.getValue()); oprot.writeFieldEnd(); } if (struct.path != null) { oprot.writeFieldBegin(PATH_FIELD_DESC); oprot.writeString(struct.path); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class WatchedEventTupleSchemeFactory implements SchemeFactory { public WatchedEventTupleScheme getScheme() { return new WatchedEventTupleScheme(); } } private static class WatchedEventTupleScheme extends TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, WatchedEvent struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetKeeperState()) { optionals.set(0); } if (struct.isSetEventType()) { optionals.set(1); } if (struct.isSetPath()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetKeeperState()) { oprot.writeI32(struct.keeperState.getValue()); } if (struct.isSetEventType()) { oprot.writeI32(struct.eventType.getValue()); } if (struct.isSetPath()) { oprot.writeString(struct.path); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, WatchedEvent struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.keeperState = KeeperState.findByValue(iprot.readI32()); struct.setKeeperStateIsSet(true); } if (incoming.get(1)) { struct.eventType = EventType.findByValue(iprot.readI32()); struct.setEventTypeIsSet(true); } if (incoming.get(2)) { struct.path = iprot.readString(); struct.setPathIsSet(true); } } } } ZooKeeperExceptionType.java000066400000000000000000000036461245521677600361560ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/generated/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.curator.generated; import java.util.Map; import java.util.HashMap; import org.apache.thrift.TEnum; public enum ZooKeeperExceptionType implements org.apache.thrift.TEnum { SYSTEMERROR(0), RUNTIMEINCONSISTENCY(1), DATAINCONSISTENCY(2), CONNECTIONLOSS(3), MARSHALLINGERROR(4), UNIMPLEMENTED(5), OPERATIONTIMEOUT(6), BADARGUMENTS(7), APIERROR(8), NOAUTH(9), NOCHILDRENFOREPHEMERALS(10), INVALIDACL(11), AUTHFAILED(12), SESSIONEXPIRED(13), INVALIDCALLBACK(14), SESSIONMOVED(15), NOTREADONLY(16); private final int value; private ZooKeeperExceptionType(int value) { this.value = value; } /** * Get the integer value of this enum value, as defined in the Thrift IDL. */ public int getValue() { return value; } /** * Find a the enum type by its integer value, as defined in the Thrift IDL. * @return null if the value is not found. */ public static ZooKeeperExceptionType findByValue(int value) { switch (value) { case 0: return SYSTEMERROR; case 1: return RUNTIMEINCONSISTENCY; case 2: return DATAINCONSISTENCY; case 3: return CONNECTIONLOSS; case 4: return MARSHALLINGERROR; case 5: return UNIMPLEMENTED; case 6: return OPERATIONTIMEOUT; case 7: return BADARGUMENTS; case 8: return APIERROR; case 9: return NOAUTH; case 10: return NOCHILDRENFOREPHEMERALS; case 11: return INVALIDACL; case 12: return AUTHFAILED; case 13: return SESSIONEXPIRED; case 14: return INVALIDCALLBACK; case 15: return SESSIONMOVED; case 16: return NOTREADONLY; default: return null; } } } curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/x/000077500000000000000000000000001245521677600272465ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/x/rpc/000077500000000000000000000000001245521677600300325ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/x/rpc/RpcTests.java000066400000000000000000000251631245521677600324530ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.generated.*; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.InstanceSpec; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.utils.ThreadUtils; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.node.ArrayNode; import org.codehaus.jackson.node.ObjectNode; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.nio.ByteBuffer; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; public class RpcTests extends BaseClassForTests { private Timing timing = new Timing(); private CuratorProjectionServer thriftServer; private CuratorService.Client curatorServiceClient; private EventService.Client eventServiceClient; private int thriftPort; @BeforeMethod @Override public void setup() throws Exception { super.setup(); ObjectMapper mapper = new ObjectMapper(); ObjectNode connectionNode = mapper.createObjectNode(); connectionNode.put("name", "test"); connectionNode.put("connectionString", server.getConnectString()); ObjectNode thriftNode = mapper.createObjectNode(); thriftPort = InstanceSpec.getRandomPort(); thriftNode.put("port", thriftPort); ArrayNode connections = mapper.createArrayNode(); connections.add(connectionNode); ObjectNode node = mapper.createObjectNode(); node.put("connections", connections); node.put("thrift", thriftNode); final String configurationJson = mapper.writeValueAsString(node); thriftServer = CuratorProjectionServer.startServer(configurationJson); TSocket clientTransport = new TSocket("localhost", thriftPort); clientTransport.setTimeout(timing.connection()); clientTransport.open(); TProtocol clientProtocol = new TBinaryProtocol(clientTransport); curatorServiceClient = new CuratorService.Client(clientProtocol); TSocket eventTransport = new TSocket("localhost", thriftPort); eventTransport.setTimeout(timing.connection()); eventTransport.open(); TProtocol eventProtocol = new TBinaryProtocol(eventTransport); eventServiceClient = new EventService.Client(eventProtocol); } @AfterMethod @Override public void teardown() throws Exception { thriftServer.stop(); super.teardown(); } @Test public void testBasic() throws Exception { CuratorProjection curatorProjection = curatorServiceClient.newCuratorProjection("test"); CreateSpec spec = new CreateSpec(); spec.path = "/test"; spec.data = ByteBuffer.wrap("value".getBytes()); OptionalPath node = curatorServiceClient.createNode(curatorProjection, spec); Assert.assertEquals(node.path, "/test"); GetDataSpec dataSpec = new GetDataSpec(); dataSpec.path = "/test"; OptionalData data = curatorServiceClient.getData(curatorProjection, dataSpec); Assert.assertEquals(data.data, ByteBuffer.wrap("value".getBytes())); } @Test public void testEvents() throws Exception { final CuratorProjection curatorProjection = curatorServiceClient.newCuratorProjection("test"); final CountDownLatch connectedLatch = new CountDownLatch(1); final CountDownLatch nodeCreatedLatch = new CountDownLatch(1); Callable proc = new Callable() { @Override public Void call() throws Exception { while ( !Thread.currentThread().isInterrupted() ) { CuratorEvent event = eventServiceClient.getNextEvent(curatorProjection); if ( event.type == CuratorEventType.CONNECTION_CONNECTED ) { connectedLatch.countDown(); } else if ( event.type == CuratorEventType.WATCHED ) { if ( event.watchedEvent.eventType == EventType.NodeCreated ) { nodeCreatedLatch.countDown(); } } } return null; } }; Future eventFuture = ThreadUtils.newSingleThreadExecutor("test").submit(proc); Assert.assertTrue(timing.awaitLatch(connectedLatch)); ExistsSpec spec = new ExistsSpec(); spec.path = "/test"; spec.watched = true; curatorServiceClient.exists(curatorProjection, spec); CreateSpec createSpec = new CreateSpec(); createSpec.path = "/test"; curatorServiceClient.createNode(curatorProjection, createSpec); Assert.assertTrue(timing.awaitLatch(nodeCreatedLatch)); eventFuture.cancel(true); } @Test public void testLockMultiThread() throws Exception { final Timing timing = new Timing(); TSocket clientTransport = new TSocket("localhost", thriftPort); clientTransport.setTimeout(timing.connection()); clientTransport.open(); TProtocol clientProtocol = new TBinaryProtocol(clientTransport); final CuratorService.Client secondCuratorServiceClient = new CuratorService.Client(clientProtocol); ExecutorService service = ThreadUtils.newFixedThreadPool(2, "test"); ExecutorCompletionService completer = new ExecutorCompletionService(service); final CountDownLatch lockLatch = new CountDownLatch(2); final AtomicBoolean hasTheLock = new AtomicBoolean(); for ( int i = 0; i < 2; ++i ) { final CuratorService.Client client = (i == 0) ? curatorServiceClient : secondCuratorServiceClient; Callable proc = new Callable() { @Override public Void call() throws Exception { CuratorProjection curatorProjection = client.newCuratorProjection("test"); OptionalLockProjection lockProjection = client.acquireLock(curatorProjection, "/lock", timing.forWaiting().milliseconds()); if ( lockProjection.lockProjection == null ) { throw new Exception("Could not acquire lock"); } try { if ( !hasTheLock.compareAndSet(false, true) ) { throw new Exception("Two lockers"); } timing.sleepABit(); } finally { hasTheLock.set(false); lockLatch.countDown(); client.closeGenericProjection(curatorProjection, lockProjection.lockProjection.id); } return null; } }; completer.submit(proc); } completer.take().get(); completer.take().get(); Assert.assertTrue(timing.awaitLatch(lockLatch)); service.shutdownNow(); } @Test public void testRecoverableException() throws Exception { CuratorProjection curatorProjection = curatorServiceClient.newCuratorProjection("test"); CreateSpec spec = new CreateSpec(); spec.path = "/this/wont/work"; spec.data = ByteBuffer.wrap("value".getBytes()); try { curatorServiceClient.createNode(curatorProjection, spec); Assert.fail("Should have failed"); } catch ( CuratorException e ) { Assert.assertEquals(e.getType(), ExceptionType.NODE); Assert.assertNotNull(e.nodeException); Assert.assertEquals(e.nodeException, NodeExceptionType.NONODE); } } @Test public void testEphemeralCleanup() throws Exception { CuratorProjection curatorProjection = curatorServiceClient.newCuratorProjection("test"); CreateSpec spec = new CreateSpec(); spec.path = "/test"; spec.data = ByteBuffer.wrap("value".getBytes()); spec.mode = CreateMode.EPHEMERAL; OptionalPath node = curatorServiceClient.createNode(curatorProjection, spec); System.out.println(node); final CountDownLatch latch = new CountDownLatch(1); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { if ( event.getType() == Event.EventType.NodeDeleted ) { latch.countDown(); } } }; client.checkExists().usingWatcher(watcher).forPath("/test"); curatorServiceClient.closeCuratorProjection(curatorProjection); Assert.assertTrue(timing.awaitLatch(latch)); } finally { CloseableUtils.closeQuietly(client); } } } curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/x/rpc/TestClient.java000066400000000000000000000171261245521677600327620ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc; import org.apache.curator.generated.*; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import java.nio.ByteBuffer; import java.util.List; import java.util.concurrent.Executors; public class TestClient { public static void main(String[] args) throws Exception { TSocket clientTransport = new TSocket("localhost", 8899); clientTransport.open(); TProtocol clientProtocol = new TBinaryProtocol(clientTransport); final CuratorService.Client client = new CuratorService.Client(clientProtocol); TSocket eventTransport = new TSocket("localhost", 8899); eventTransport.open(); TProtocol eventProtocol = new TBinaryProtocol(eventTransport); final EventService.Client serviceClient = new EventService.Client(eventProtocol); TSocket discoveryTransport = new TSocket("localhost", 8899); discoveryTransport.open(); TProtocol discoveryProtocol = new TBinaryProtocol(discoveryTransport); final DiscoveryService.Client discoveryClient = new DiscoveryService.Client(discoveryProtocol); final CuratorProjection curatorProjection = client.newCuratorProjection("test"); Executors.newSingleThreadExecutor().submit ( new Runnable() { @Override public void run() { try { //noinspection InfiniteLoopStatement for(;;) { CuratorEvent nextEvent = serviceClient.getNextEvent(curatorProjection); System.out.println(nextEvent); } } catch ( TException e ) { e.printStackTrace(); } } } ); CreateSpec createSpec = new CreateSpec(); createSpec.path = "/this/should/fail"; createSpec.data = ByteBuffer.wrap("hey".getBytes()); try { client.createNode(curatorProjection, createSpec); } catch ( CuratorException e ) { System.out.println("Ex: " + e); } createSpec = new CreateSpec(); createSpec.path = "/a/b/c"; createSpec.creatingParentsIfNeeded = true; createSpec.data = ByteBuffer.wrap("hey".getBytes()); OptionalPath path = client.createNode(curatorProjection, createSpec); System.out.println("Path: " + path); PathChildrenCacheProjection pathChildrenCacheProjection = client.startPathChildrenCache(curatorProjection, "/a/b", true, false, PathChildrenCacheStartMode.BUILD_INITIAL_CACHE); NodeCacheProjection nodeCache = client.startNodeCache(curatorProjection, "/a/b/c", false, true); ChildData nodeCacheData = client.getNodeCacheData(curatorProjection, nodeCache); System.out.println("nodeCacheData: " + nodeCacheData); List pathChildrenCacheData = client.getPathChildrenCacheData(curatorProjection, pathChildrenCacheProjection); System.out.println("Child data: " + pathChildrenCacheData); GetChildrenSpec getChildrenSpec = new GetChildrenSpec(); getChildrenSpec.path = "/a"; OptionalChildrenList children = client.getChildren(curatorProjection, getChildrenSpec); System.out.println("Children: " + children); ChildData pathChildrenCacheDataForPath = client.getPathChildrenCacheDataForPath(curatorProjection, pathChildrenCacheProjection, "/a/b/c"); System.out.println(pathChildrenCacheDataForPath); OptionalLockProjection lockId = client.acquireLock(curatorProjection, "/mylock", 1000); client.closeGenericProjection(curatorProjection, lockId.lockProjection.id); GetDataSpec getDataSpec = new GetDataSpec(); getDataSpec.watched = true; getDataSpec.path = "/a/b/c"; getDataSpec.asyncContext = "hey"; OptionalData optionalData = client.getData(curatorProjection, getDataSpec); System.out.println("getData: " + optionalData); ExistsSpec existsSpec = new ExistsSpec(); existsSpec.path = "/a/b/c"; System.out.println("exists: " + client.exists(curatorProjection, existsSpec)); DeleteSpec deleteSpec = new DeleteSpec(); deleteSpec.path = "/a/b/c"; client.deleteNode(curatorProjection, deleteSpec); System.out.println("exists: " + client.exists(curatorProjection, existsSpec)); LeaderResult leader = client.startLeaderSelector(curatorProjection, "/leader", "me", 10000); System.out.println("Has Leader: " + leader.isLeader); List leaderParticipants = client.getLeaderParticipants(curatorProjection, leader.projection); System.out.println("Participants: " + leaderParticipants); boolean isLeader = client.isLeader(curatorProjection, leader.projection); System.out.println("isLeader: " + isLeader); client.closeGenericProjection(curatorProjection, leader.projection.id); pathChildrenCacheData = client.getPathChildrenCacheData(curatorProjection, pathChildrenCacheProjection); System.out.println("Child data: " + pathChildrenCacheData); nodeCacheData = client.getNodeCacheData(curatorProjection, nodeCache); System.out.println("nodeCacheData: " + nodeCacheData); PersistentEphemeralNodeProjection node = client.startPersistentEphemeralNode(curatorProjection, "/my/path", ByteBuffer.wrap("hey".getBytes()), PersistentEphemeralNodeMode.EPHEMERAL); existsSpec.path = "/my/path"; OptionalStat nodeExists = client.exists(curatorProjection, existsSpec); System.out.println("nodeExists: " + nodeExists); client.closeGenericProjection(curatorProjection, node.id); List leaseProjections = client.acquireSemaphore(curatorProjection, "/semi", 3, 1000, 10); System.out.println("leaseProjections: " + leaseProjections); for ( LeaseProjection leaseProjection : leaseProjections ) { client.closeGenericProjection(curatorProjection, leaseProjection.id); } DiscoveryInstance yourInstance = discoveryClient.makeDiscoveryInstance("mine", ByteBuffer.wrap(new byte[]{}), 8080); DiscoveryProjection discovery = discoveryClient.startDiscovery(curatorProjection, "/discovery", yourInstance); DiscoveryProviderProjection provider = discoveryClient.startProvider(curatorProjection, discovery, "mine", ProviderStrategyType.ROUND_ROBIN, 1000, 3); DiscoveryInstance instance = discoveryClient.getInstance(curatorProjection, provider); System.out.println("Instance: " + instance); } } curator-apache-curator-2.7.1/curator-x-rpc/src/test/java/org/apache/curator/x/rpc/TestServer.java000066400000000000000000000024271245521677600330100ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.rpc; import com.google.common.io.Resources; import org.apache.curator.test.TestingServer; import java.nio.charset.Charset; public class TestServer { public static void main(String[] args) throws Exception { new TestingServer(2181); String configurationSource = Resources.toString(Resources.getResource("configuration/test.json"), Charset.defaultCharset()); CuratorProjectionServer.main(new String[]{configurationSource}); } } curator-apache-curator-2.7.1/curator-x-rpc/src/test/resources/000077500000000000000000000000001245521677600244015ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/resources/configuration/000077500000000000000000000000001245521677600272505ustar00rootroot00000000000000curator-apache-curator-2.7.1/curator-x-rpc/src/test/resources/configuration/connections.json000066400000000000000000000012361245521677600324670ustar00rootroot00000000000000{ "connections": [ { "name": "test", "connectionString": "one:1,two:2", "sessionLength": "3m", "connectionTimeout": "20s", "retry": { "type": "exponential-backoff", "baseSleepTime": "1s", "maxRetries": 10 } }, { "name": "alt", "connectionString": "three:3,four:4", "sessionLength": "4m", "connectionTimeout": "30s", "retry": { "type": "ntimes", "sleepBetweenRetries": "1m", "n": 10 } } ] }curator-apache-curator-2.7.1/curator-x-rpc/src/test/resources/configuration/logging.json000066400000000000000000000006261245521677600315750ustar00rootroot00000000000000{ "logging": { "level": "INFO", "appenders": [ { "type": "file", "currentLogFilename": "logs/foo.log", "archivedLogFilenamePattern": "logs/foo-%d.log.gz", "archivedFileCount": 10, "timeZone": "UTC" }, { "type": "console" } ] } }curator-apache-curator-2.7.1/curator-x-rpc/src/test/resources/configuration/simple.json000066400000000000000000000001061245521677600314310ustar00rootroot00000000000000{ "thrift": { "port": 1234 }, "pingTime": "10s" }curator-apache-curator-2.7.1/curator-x-rpc/src/test/resources/configuration/test.json000066400000000000000000000003201245521677600311150ustar00rootroot00000000000000{ "projectionExpiration": "15s", "thrift": { "port": 8899 }, "connections": [ { "name": "test", "connectionString": "localhost:2181" } ] }curator-apache-curator-2.7.1/doap.rdf000066400000000000000000000060661245521677600175430ustar00rootroot00000000000000 2011-02-06 Apache Curator A set of Java libraries that make using Apache ZooKeeper much easier. New users of ZooKeeper are surprised to learn that a significant amount of connection management must be done manually. For example, when the ZooKeeper client connects to the ensemble it must negotiate a new session, etc. This takes some time. If you use a ZooKeeper client API before the connection process has completed, ZooKeeper will throw an exception. These types of exceptions are referred to as "recoverable" errors. Curator automatically handles connection management, greatly simplifying client code. Instead of directly using the ZooKeeper APIs you use Curator APIs that internally check for connection completion and wrap each ZooKeeper API in a retry loop. Curator uses a retry mechanism to handle recoverable errors and automatically retry operations. The method of retry is customizable. Curator comes bundled with several implementations (ExponentialBackoffRetry, etc.) or custom implementations can be written. Java curator-apache-curator-2.7.1/pom.xml000066400000000000000000000761231245521677600174410ustar00rootroot00000000000000 4.0.0 org.apache apache 14 org.apache.curator apache-curator 2.7.1 pom Apache Curator Curator is a set of Java libraries that make using Apache ZooKeeper much easier. http://curator.apache.org 2011 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo The Apache Software Foundation http://www.apache.org/ UTF-8 UTF-8 UTF-8 1.6 1 2.7 2.9.1 2.8 2.5.1 3.1 2.3.7 2.17 3.3 1.5 1.0 1.9.0 2.5 0.10 3.18.1-GA 2.2 1.9.13 1.18.1 1.1.1 6.1.26 1.0.2 2.3.0.GA 3.4.6 16.0.1 6.8.8 0.12.0 0.7.0 2.3 1.7.6 https://github.com/apache/curator.git scm:git:https://git-wip-us.apache.org/repos/asf/curator.git scm:git:https://git-wip-us.apache.org/repos/asf/curator.git apache-curator-2.7.1 JIRA http://issues.apache.org/jira/browse/CURATOR Jenkins https://builds.apache.org/job/Curator/ mail true true false false
dev@curator.apache.org
apache.website.svnpub scm:svn:https://svn.apache.org/repos/asf/curator/site/trunk Users user@curator.apache.org user-subscribe@curator.apache.org user-unsubscribe@curator.apache.org http://mail-archives.apache.org/mod_mbox/curator-user/ Development dev@curator.apache.org dev-subscribe@curator.apache.org dev-unsubscribe@curator.apache.org http://mail-archives.apache.org/mod_mbox/curator-dev/ Commits commits@curator.apache.org commits-subscribe@curator.apache.org commits-unsubscribe@curator.apache.org http://mail-archives.apache.org/mod_mbox/curator-commits/ randgalt Jordan Zimmerman randgalt@apache.org -5 Committer PMC Chair https://people.apache.org/~randgalt zarfide Jay Zarfoss zarfide@apache.org -8 Committer PMC Member http://www.linkedin.com/pub/jay-zarfoss/34/56/a19 cheddar Eric Tschetter cheddar@apache.org -6 Committer PMC Member ChedHeader iocanel Ioannis Canellos iocanel@apache.org +2 Committer PMC Member http://iocanel.blogspot.com cammckenzie Cameron McKenzie cammckenzie@apache.org +10 Committer PMC Member https://people.apache.org/~cammckenzie dragonsinth Scott Blum dragonsinth@apache.org -5 Committer PMC Member http://github.com/dragonsinth Patrick Hunt phunt1@gmail.com PMC Member -8 http://www.linkedin.com/pub/patrick-hunt/2/5b2/24a Mahadev Konar mahadev@apache.org PMC Member -8 http://www.linkedin.com/in/mahadevkonar Luciano Resende lresende@apache.org PMC Member -8 https://people.apache.org/~lresende Enis Söztutar enis@apache.org PMC Member -8 https://people.apache.org/~enis curator-client curator-test curator-framework curator-recipes curator-examples curator-x-discovery curator-x-discovery-server curator-x-rpc org.slf4j slf4j-api ${slf4j-version} org.slf4j slf4j-log4j12 ${slf4j-version} org.mockito mockito-core 1.9.5 org.apache.curator curator-client ${project.version} org.apache.curator curator-framework ${project.version} org.apache.curator curator-recipes ${project.version} org.apache.curator curator-test ${project.version} org.apache.curator curator-x-discovery ${project.version} org.apache.curator curator-x-discovery-server ${project.version} org.javassist javassist ${javassist-version} org.apache.commons commons-math ${commons-math-version} org.codehaus.jackson jackson-mapper-asl ${jackson-mapper-asl-version} com.sun.jersey jersey-server ${jersey-version} com.sun.jersey jersey-servlet ${jersey-version} com.sun.jersey jersey-client ${jersey-version} com.sun.jersey jersey-core ${jersey-version} javax.ws.rs jsr311-api ${jsr311-api-version} org.mortbay.jetty jetty ${jetty-version} net.sf.scannotation scannotation ${scannotation-version} org.jboss.resteasy resteasy-jaxrs ${resteasy-jaxrs-version} org.scannotation scannotation org.apache.zookeeper zookeeper ${zookeeper-version} com.sun.jmx jmxri com.sun.jdmk jmxtools javax.jms jms junit junit org.slf4j slf4j-log4j12 com.google.guava guava ${guava-version} org.testng testng ${testng-version} com.facebook.swift swift-codec ${swift-version} com.facebook.swift swift-service ${swift-version} io.dropwizard dropwizard-configuration ${dropwizard-version} io.dropwizard dropwizard-logging ${dropwizard-version} org.apache.zookeeper zookeeper com.google.guava guava org.testng testng test org.slf4j slf4j-log4j12 test org.apache.maven.plugins maven-project-info-reports-plugin ${maven-project-info-reports-plugin-version} org.apache.maven.plugins maven-javadoc-plugin ${maven-javadoc-plugin-version} true -J-Xmx1g false org.apache.maven.plugins maven-dependency-plugin ${maven-dependency-plugin-version} org.apache.maven.plugins maven-install-plugin ${maven-install-plugin-version} org.apache.maven.plugins maven-compiler-plugin ${maven-compiler-plugin-version} org.apache.felix maven-bundle-plugin ${maven-bundle-plugin-version} org.apache.maven.plugins maven-surefire-plugin ${maven-surefire-plugin-version} org.apache.maven.plugins maven-javadoc-plugin ${maven-javadoc-plugin-version} org.apache.maven.plugins maven-site-plugin ${maven-site-plugin-version} org.apache.maven.plugins maven-scm-publish-plugin ${maven-scm-publish-plugin-version} com.mycila.maven-license-plugin maven-license-plugin ${maven-license-plugin-version} org.apache.maven.plugins maven-release-plugin ${maven-release-plugin-version} true ${project.artifactId}-${project.version} false true org.apache.rat apache-rat-plugin ${apache-rat-plugin-version} org.apache.maven.plugins maven-shade-plugin ${maven-shade-plugin-version} ${basedir} META-INF DISCLAIMER LICENSE NOTICE org.apache.maven.plugins maven-dependency-plugin org.apache.maven.plugins maven-install-plugin true org.apache.maven.plugins maven-compiler-plugin ${jdk-version} ${jdk-version} org.apache.felix maven-bundle-plugin true true ${project.name} ${project.artifactId} ${osgi.export.package} ${osgi.import.package} ${osgi.dynamic.import} ${osgi.private.package} ${osgi.require.bundle} ${osgi.activator} ${osgi.export.service} jar war bundle true bundle-manifest process-classes manifest org.apache.maven.plugins maven-surefire-plugin ${surefire-forkcount} false true org.apache.maven.plugins maven-javadoc-plugin true -J-Xmx1g false org.apache.maven.plugins maven-site-plugin en true org.apache.maven.doxia doxia-module-confluence ${doxia-module-confluence-version} site site org.apache.maven.plugins maven-scm-publish-plugin false Curator website deployment ${curator-website-checkout-path} scm-publish site-deploy publish-scm com.mycila.maven-license-plugin maven-license-plugin
src/etc/header.txt
**/*.confluence **/help.txt **/*.rdf **/.gitignore **/*.thrift **/*.json **/.idea/** **/DISCLAIMER **/DEPENDENCIES **/KEYS **/LICENSE **/NOTICE **/README **/CHANGES **/RELEASE-NOTES **/generated/** true
license check
org.apache.maven.plugins maven-release-plugin -Dmaven.test.skip=true forked-path org.apache.rat apache-rat-plugin 0 false **/*.confluence **/*.rdf **/help.txt **/.gitignore **/*.thrift **/*.json **/.idea/** **/DISCLAIMER **/DEPENDENCIES **/KEYS **/LICENSE **/NOTICE **/README **/CHANGES **/RELEASE-NOTES **/generated/**
curator-apache-curator-2.7.1/src/000077500000000000000000000000001245521677600167025ustar00rootroot00000000000000curator-apache-curator-2.7.1/src/etc/000077500000000000000000000000001245521677600174555ustar00rootroot00000000000000curator-apache-curator-2.7.1/src/etc/header.txt000066400000000000000000000013631245521677600214510ustar00rootroot00000000000000Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. curator-apache-curator-2.7.1/src/site/000077500000000000000000000000001245521677600176465ustar00rootroot00000000000000curator-apache-curator-2.7.1/src/site/confluence/000077500000000000000000000000001245521677600217675ustar00rootroot00000000000000curator-apache-curator-2.7.1/src/site/confluence/errors.confluence000066400000000000000000000052521245521677600253520ustar00rootroot00000000000000h1. Error Handling h2. Background ZooKeeper is a very low level system that requires users to do a lot of housekeeping. See: * [[http://wiki.apache.org/hadoop/ZooKeeper/FAQ]] The Curator [[Framework|curator-framework/index.html]] is designed to hide as much of the details/tedium of this housekeeping as is possible. h2. Connection Guarantees The Curator [[Framework|curator-framework/index.html]] constantly monitors the connection to the ZooKeeper ensemble. Further every operation is wrapped in a retry mechanism. Thus, the following guarantees can be made: * Every Curator operation properly waits until the ZooKeeper connection is established * Every Curator [[Framework|curator-framework/index.html]] operation (create, getData, etc.) is guaranteed to manage connection loss and/or session expiration per the currently set retry policy * If the connection is temporarily lost, Curator will attempt to retry the operation until it succeeds per the currently set retry policy * All Curator recipes attempt to deal with connection issues in an appropriate way h2. Notifications Curator exposes several listenable interfaces for clients to monitor the state of the ZooKeeper connection. {{ConnectionStateListener}} is called when there are connection disruptions. Clients can monitor these changes and take appropriate action. These are the possible state changes: |CONNECTED|Sent for the first successful connection to the server. NOTE: You will only get one of these messages for any CuratorFramework instance.| |SUSPENDED|There has been a loss of connection. Leaders, locks, etc. should suspend until the connection is re\-established. If the connection times\-out you will receive a LOST notice.| |RECONNECTED|A suspended or lost connection has been re\-established.| |LOST|The connection is confirmed to be lost. Close any locks, leaders, etc. and attempt to re\-create them. NOTE: it is possible to get a RECONNECTED state after this but you should still consider any locks, etc. as dirty/unstable.| |READ_ONLY|The connection has gone into read\-only mode. This can only happen if you pass true for CuratorFrameworkFactory.Builder.canBeReadOnly(). See the ZooKeeper doc regarding read only connections: [[http://wiki.apache.org/hadoop/ZooKeeper/GSoCReadOnlyMode]]. The connection will remain in read only mode until another state change is sent.| {{UnhandledErrorListener}} is called when a background task, etc. catches an exception. In general, Curator users shouldn't care about these as they are logged. However, you can listen for them if you choose. h2. Recipes In general, the recipes attempt to deal with errors and connection issues. See the doc for each recipe for details on how it deals with errors. curator-apache-curator-2.7.1/src/site/confluence/exhibitor.confluence000066400000000000000000000031361245521677600260320ustar00rootroot00000000000000h1. Exhibitor Integration Curator can be integrated with Netflix [[Exhibitor|https://github.com/Netflix/exhibitor]] to achieve a live/updating list of the ZooKeeper ensemble. This means that your ZooKeeper client (i.e. Curator) will automatically/dynamically adjust to changes in the makeup of a ZooKeeper ensemble. Further, this support is generalized so that a service other than Exhibitor could be used if available. h2. Enabling The integration is enabled via the {{CuratorFrameworkFactory}} (or when constructing the {{CuratorZookeeperClient}} if not using the framework). Pass an {{EnsembleProvider}} to the {{ensembleProvider()}} method of the {{CuratorFrameworkFactory}} builder. h2. EnsembleProvider For Exhibitor, construct an instance of {{ExhibitorEnsembleProvider}} to pass to the builder. It takes a number of arguments: * exhibitors \- a list of the exhibitor instances. This is the initial set of Exhibitor instances. This set will get automatically updated if it changes. * restClient \- a simple facade to access the Exhibitor instances via REST. Use the provided {{DefaultExhibitorRestClient}} or something else of your choosing. * restUriPath \- the REST path to use. In most cases this should be: {{/exhibitor/v1/cluster/list}} * pollingMs \- how often to poll the Exhibitor instances * retryPolicy \- the retry policy to use when polling the Exhibitor instances. h2. Details Once configured, Curator will poll the Exhibitors for changes in the ensemble. If Curator should need to re\-create the ZooKeeper instance (due to a SysDisconnected event, etc.) it will use the updated ensemble list to do so. curator-apache-curator-2.7.1/src/site/confluence/getting-started.confluence000066400000000000000000000054351245521677600271460ustar00rootroot00000000000000h1. Getting Started h2. Learn ZooKeeper Curator users are assumed to know ZooKeeper. A good place to start is here: [[http://zookeeper.apache.org/doc/trunk/zookeeperStarted.html]] h2. Using Curator The Curator JARs are available from Maven Central. The various artifacts are listed on the [[main page|index.html]]. Users of Maven, Gradle, Ant, etc. can easily include Curator into their build script. Most users will want to use one of Curator's pre\-built recipes. So, the curator\-recipes is the correct artifact to use. If you only want a wrapper around ZooKeeper that adds connection management and retry policies, use curator\-framework. h2. Getting a Connection Curator uses [[Fluent Style|http://en.wikipedia.org/wiki/Fluent%5Finterface]]. If you haven't used this before, it might seem odd so it's suggested that you familiarize yourself with the style. Curator connection instances ({{CuratorFramework}}) are allocated from the {{CuratorFrameworkFactory}}. You only need *one* {{CuratorFramework}} object for each ZooKeeper cluster you are connecting to: {code} CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy) {code} This will create a connection to a ZooKeeper cluster using default values. The only thing that you need to specify is the retry policy. For most cases, you should use: {code} RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3) CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy); client.start(); {code} The client must be started (and closed when no longer needed). h2. Calling ZooKeeper Directly Once you have a CuratorFramework instance, you can make direct calls to ZooKeeper in a similar way to using the raw {{ZooKeeper}} object provided in the ZooKeeper distribution. E.g.: {code} client.create().forPath("/my/path", myData) {code} The benefit here is that Curator manages the ZooKeeper connection and will retry operations if there are connection problems. h2. Recipes h3. Distributed Lock {code} InterProcessMutex lock = new InterProcessMutex(client, lockPath); if ( lock.acquire(maxWait, waitUnit) ) { try { // do some work inside of the critical section here } finally { lock.release(); } } {code} h3. Leader Election {code} LeaderSelectorListener listener = new LeaderSelectorListenerAdapter() { public void takeLeadership(CuratorFramework client) throws Exception { // this callback will get called when you are the leader // do whatever leader work you need to and only exit // this method when you want to relinquish leadership } } LeaderSelector selector = new LeaderSelector(client, path, listener); selector.autoRequeue(); // not required, but this is behavior that you will probably expect selector.start(); {code} curator-apache-curator-2.7.1/src/site/confluence/index.confluence000066400000000000000000000052251245521677600251450ustar00rootroot00000000000000h1. Welcome to Apache Curator h2. What is Curator? Curator _n ˈkyoor͝ˌātər_: a keeper or custodian of a museum or other collection \- A ZooKeeper Keeper. !images/ph-quote.png! h2. Getting Started See the page for quick start: [[Getting Started|getting-started.html]]. h2. Components |[[Recipes|curator-recipes/index.html]]|Implementations of some of the common ZooKeeper "recipes". The implementations are built on top of the Curator Framework.| |[[Framework|curator-framework/index.html]]|The Curator Framework is a high\-level API that greatly simplifies using ZooKeeper. It adds many features that build on ZooKeeper and handles the complexity of managing connections to the ZooKeeper cluster and retrying operations.| |[[Utilities|utilities.html]]|Various utilities that are useful when using ZooKeeper.| |[[Client|curator-client/index.html]]|A replacement for the bundled {{ZooKeeper}} class that takes care of some low\-level housekeeping and provides some useful utilities.| |[[Errors|errors.html]]|How Curator deals with errors, connection issues, recoverable exceptions, etc.| |Extensions|The curator\-recipes package implements the common recipes that are described in the ZooKeeper documentation. To avoid bloating that package, recipes/applications that have a vertical appeal will be put in separate "extension" packages using the naming convention curator\-x\-name.| h2. Maven / Artifacts Curator binaries are published to Maven Central. Curator consists of several artifacts. Which artifacts to use depends on your needs. For most users, the only artifact you need is curator\-recipes. ||GroupID/Org||ArtifactID/Name||Description|| |org.apache.curator|curator\-recipes|All of the recipes. Note: this artifact has dependencies on client and framework and, so, Maven (or whatever tool you're using) should pull those in automatically.| |org.apache.curator|curator\-framework|The Curator Framework high level API. This is built on top of the client and should pull it in automatically.| |org.apache.curator|curator\-client|The Curator Client \- replacement for the ZooKeeper class in the ZK distribution.| |org.apache.curator|curator\-test|Contains the TestingServer, the TestingCluster and a few other tools useful for testing.| |org.apache.curator|curator\-examples|Example usages of various Curator features.| |org.apache.curator|curator\-x\-discovery|A Service Discovery implementation built on the Curator Framework.| |org.apache.curator|curator\-x\-discovery-server|A RESTful server that can be used with Curator Discovery.| |org.apache.curator|curator\-x\-rpc|A proxy that bridges non\-java environments with the Curator framework and recipes.| curator-apache-curator-2.7.1/src/site/confluence/logging.confluence000066400000000000000000000014071245521677600254620ustar00rootroot00000000000000h1. Logging and Tracing h2. Details Curator is logging and tracing neutral. The Curator code is instrumented with logging and tracers but uses a driver mechanism that allows easy integration into your preferred logging and tracing frameworks. h2. Logging Curator uses SLF4J ([[http://www.slf4j.org/]]) for logging. SLF4J is a facade over logging that allows you to plug in any (or no) logging framework. See the SLF4J website for details. h2. Tracing Connect Curator tracing to your tracing framework via an instance of {{TracerDriver}}. Curator calls the various methods (e.g. addTrace() or addCount() ) and your instance proxies the calls to your tracing framework. Inform Curator of your tracing driver instance by calling {{CuratorZookeeperClient.setTracerDriver()}}. curator-apache-curator-2.7.1/src/site/confluence/utilities.confluence000066400000000000000000000054141245521677600260510ustar00rootroot00000000000000h1. Utilities h2. Test Server In the curator\-test sub\-model the {{TestingServer}} class is provided. This class creates a local, in\-process ZooKeeper server that can be used for testing. h2. Test Cluster In the curator\-test sub\-model the {{TestingCluster}} class is provided. This class creates an internally running ensemble of ZooKeeper servers. h2. ZKPaths Various static methods to help with using ZooKeeper ZNode paths: * getNodeFromPath: Given a full path, return the node name. i.e. "/one/two/three" will return "three" * mkdirs: Make sure all the nodes in the path are created. * getSortedChildren: Return the children of the given path sorted by sequence number * makePath: Given a parent path and a child node, create a combined full path h2. EnsurePath Utility to ensure that a particular path is created. The first time it is used, a synchronized call to {{ZKPaths.mkdirs(ZooKeeper, String)}} is made to ensure that the entire path has been created (with an empty byte array if needed). Subsequent calls with the instance are un\-synchronized NOPs. Usage: {code} EnsurePath ensurePath = new EnsurePath(aFullPathToEnsure); ... String nodePath = aFullPathToEnsure + "/foo"; ensurePath.ensure(zk); // first time syncs and creates if needed zk.create(nodePath, ...); ... ensurePath.ensure(zk); // subsequent times are NOPs zk.create(nodePath, ...); {code} *NOTE:* There's a method in the [[CuratorFramework class|curator-framework/index.html]] that returns an EnsurePath instance that is namespace aware. h2. BlockingQueueConsumer See: *[[DistributedQueue|curator-recipes/distributed-queue.html]]* and *[[DistributedPriorityQueue|curator-recipes/distributed-priority-queue.html]]* A queue consumer that provides behavior similar to a the JDK's BlockingQueue. h2. QueueSharder Due to limitations in ZooKeeper's transport layer, a single queue will break if it has more than 10K\-ish items in it. This class provides a facade over multiple distributed queues. It monitors the queues and if any one of them goes over a threshold, a new queue is added. Puts are distributed amongst the queues. h2. Reaper and ChildReaper _Reaper_ A Utility to delete parent paths of locks, etc. Periodically checks paths added to the reaper. If at check time, there are no children, the path is deleted. Clients should create one Reaper instance per application. Add lock paths to the reaper as needed and the reaper will periodically delete them. Curator's lock recipes will correctly handle parents getting deleted. _ChildReaper_ Utility to reap the empty child nodes in a parent node. Periodically calls getChildren() on the node and adds empty nodes to an internally managed Reaper. *NOTE:* You should consider using LeaderSelector to run the Reapers as they don't need to run in every client. curator-apache-curator-2.7.1/src/site/resources/000077500000000000000000000000001245521677600216605ustar00rootroot00000000000000curator-apache-curator-2.7.1/src/site/resources/css/000077500000000000000000000000001245521677600224505ustar00rootroot00000000000000curator-apache-curator-2.7.1/src/site/resources/css/site.css000066400000000000000000000026511245521677600241320ustar00rootroot00000000000000/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ body { font-size: 16px; line-height: 22px; } tt { font-size: 14px; background-color: transparent; } pre { font-size: 14px; } .well, .breadcrumb { background-color: #f5f5ff; } a:link, a:visited, a:active { color: #0035AC; } a:hover { color: #001F67; } .nav-list .active a:link, .nav-list .active a:visited, .nav-list .active a:active, .nav-list .active a:hover { background-color: #0035AC; } .nav-list li a:hover { background-color: #DDDDDD; } footer { font-size: 12px; line-height: 15px; } h2 { text-align: center; border-bottom: 1px solid #0035AC; margin-bottom: 18px; }curator-apache-curator-2.7.1/src/site/resources/images/000077500000000000000000000000001245521677600231255ustar00rootroot00000000000000curator-apache-curator-2.7.1/src/site/resources/images/curator-logo.png000066400000000000000000000634231245521677600262600ustar00rootroot00000000000000PNG  IHDRZi$gAMA|Q AiCCPICC ProfileH wTSϽ7" %z ;HQIP&vDF)VdTG"cE b PQDE݌k 5ޚYg}׺PtX4X\XffGD=HƳ.d,P&s"7C$ E6<~&S2)212 "įl+ɘ&Y4Pޚ%ᣌ\%g|eTI(L0_&l2E9r9hxgIbטifSb1+MxL 0oE%YmhYh~S=zU&ϞAYl/$ZUm@O ޜl^ ' lsk.+7oʿ9V;?#I3eE妧KD d9i,UQ h A1vjpԁzN6p\W p G@ K0ށiABZyCAP8C@&*CP=#t] 4}a ٰ;GDxJ>,_“@FXDBX$!k"EHqaYbVabJ0՘cVL6f3bձX'?v 6-V``[a;p~\2n5׌ &x*sb|! ߏƿ' Zk! $l$T4QOt"y\b)AI&NI$R$)TIj"]&=&!:dGrY@^O$ _%?P(&OJEBN9J@y@yCR nXZOD}J}/G3ɭk{%Oחw_.'_!JQ@SVF=IEbbbb5Q%O@%!BӥyҸM:e0G7ӓ e%e[(R0`3R46i^)*n*|"fLUo՝mO0j&jajj.ϧwϝ_4갺zj=U45nɚ4ǴhZ ZZ^0Tf%9->ݫ=cXgN].[7A\SwBOK/X/_Q>QG[ `Aaac#*Z;8cq>[&IIMST`ϴ kh&45ǢYYF֠9<|y+ =X_,,S-,Y)YXmĚk]c}džjcΦ浭-v};]N"&1=xtv(}'{'IߝY) Σ -rqr.d._xpUەZM׍vm=+KGǔ ^WWbj>:>>>v}/avO8 FV> 2 u/_$\BCv< 5 ]s.,4&yUx~xw-bEDCĻHGKwFGEGME{EEKX,YFZ ={$vrK .3\rϮ_Yq*©L_wד+]eD]cIIIOAu_䩔)3ѩiB%a+]3='/40CiU@ёL(sYfLH$%Y jgGeQn~5f5wugv5k֮\۹Nw]m mHFˍenQQ`hBBQ-[lllfjۗ"^bO%ܒY}WwvwXbY^Ю]WVa[q`id2JjGէ{׿m>PkAma꺿g_DHGGu;776ƱqoC{P38!9 ҝˁ^r۽Ug9];}}_~imp㭎}]/}.{^=}^?z8hc' O*?f`ϳgC/Oϩ+FFGGόzˌㅿ)ѫ~wgbk?Jި9mdwi獵ޫ?cǑOO?w| x&mf2:Y~ pHYs.#.#x?v@IDATx}չ۷SeE b[FAc"b716"D_i+b4 "-[63;w.TA_=pwfΜ~lVGipW2m'_u{df GωZ>Gd4\MN9Y7; :i~O>?gp߭nYCFwk7tDӜ1ct?u`0^ UAjӦM룉؈Sns ttc5.ru1ekMiYm/?g=wd+f\c Qlp{F]_iէU[S,[%Ei1<^DIJ 5-{Ru>  ׅWSwWWWg^qւc2FeZߡJ7F玽oSh׆u(TVЯm~97EO+ԁ [r%izbP41oz :tR~kEc~Għ3f0QgsrM0>UU]~]Wq)bOw:]{f::MA9--[e'xO4sX9A:(.\ԷNhi,5B()ϫ{iC 01G03<7ԯb{Acp'8N 2tY :AeeXx<Ʌ VLޙ#']M/PT*bs~vP^yLKɘZ?&y@P"_c}Fǵ6>r_NHnc哯z urK{75GĢ]ƀ?g⁙OZ,54.٦n7 ;vؾcP(++7'/POD9'" $ulΕ:́LRl6tw|O:ytٺmg-uѨ]\}ĈΨ5~O:HQʪV">7pTjlD2@ܼ2L |-aSvSGߡc f:8#. qʫ-*謜:v 3O$juqD*HYpZ*Oy;BYU:W"5Y)N 3 jΉqo!xn/tꡍ;UW2O^wO/qɎYUqO(Wv 92-i,:G?nr΅[F{ ĜT8 ,zK`#UDoUv rB܆9/%/y=}&M 1OMuԮ8No0}ס~֣?m3OgA܎ LŌy|Jˎ|*'3m;o*/JLŔ3~??hŇ 볖fxcP8+9-5ϖՃǂ0 !1hTQp؀ϣ[ ̓֙,_9tDh1/\B,֡wD-u)R/^$z ׌˴jp ɏk+>xMu%?2-^0Zg\v쐕>ֆ!ĀkT1=KL4 ;_P#L4йv,LMay% DX&7h8-(AU<ޅ_!@.ݎ%ZJ,٠Y `BuC dŊ;VcW-{٧Š(cTA:u'X] +;#pָ5SPw̢EΚ9׎2F M+|dZ1@Y?^3^>.ߦ?q@꫃O>=ss9K.vY?RhgX 4̠$-.]~ kwR2Efvu1\R{t~*Ǝ;v9c8m^QsJr+p3 p]2DVPI&l\O_zeh8vIoNfnOw]OPm N /J2\&D(;VHRѰ \[Of/6Z9;A=WC9jXl_LN52L`-DsF4nѣK[zo0C0Gr_`q՗s@oa% 'QVUaa5@ J<1^ngLMQXpcWuk+dA+wT9]Qs\Ha1m úBE8Ǔ0l䠡1 k2ɑ΀q{e 8a{Y¾r\i4~,SRb[e̟#I̾?iÔ%V |I7ݥw(dR @d\ȕC4r䋯酻FӮEacΕq_]i1ݧvWU#x z\xO7ܷEmя\9r1ŭf<4'JX}]O+v -Xi$#%}ciԀwybJZ7qBS<`!Y>8gKi^]D7a6zpI"qU:O'}n^2M+pu(ִNܣ [>jDESKXj1_4t#90K'xc`0HDz{#5s1Gg˴jt̘rώ~b ʵ7Bj͎Z4wiH=@A@ RDr'\[M%zR#L)Z3"490_O?; uWO"y!hə8 TXŝ'?W{5ʞ=BrZpR^v֠<\erwU],é00ĕ32H|J)64Լ i#ؒ%貚7:Y <6:JJ;\ `z"VkC%-q(s?߇XB} r@Sb'ry9Erk6K[r0u!,j|?=vm fK/ ܠAdx꨼lwI]Z]xtg_#yp/\ֺ>Xd];qZu 2' ,KśB- ࠪuϛ+@NKlwf" ¸KSwoK %ݬ;t( PܢZn*s؋hnV}<кSXXި3&=,p\`^N=sQ4 r;CC_^qNjg5snAJ; ˓Z蟾ŕ*;Uqnt,g>K6_mWRl--|UzOݮJ@qy.XSJN67 +6|F#lCNAԢ"14\>#> 4 |`N:ͱn!b)-טE7ÉⵐAީVҰ v8ɴi 72p+26ނhh_~O  GsŅusc¿OQ=ˀ<;ri]?YshhlƣcҺ62tVH|Oe>{yk\9N긎b`Mp03wC ҄'O JY^'V_i^!n}84zT7]v}yl(}t"l!wNx'ͽޟtSĠl` DB(\Ht{+QP4@'lQ9R+|WSd,`9tt$Z\!aw?TIrb@ӝ%ˀxP!مߋC&?z&dVN0<pTkIa;4ƳqJ Tσo ;s` c&u/Ć]_kwc['mCoSLh0N8 JpBifVL{3Ykk cKWEn~Cمᱼ3sơxA35GhSvrw6H v"뭛Z,=eo,!c۞ ]Pwfð-{7J]ۂ5[%H`nDC 3@r5k4UZwͺ iFmUѵ J dN?S\[:#^ct;!IGU쑧vG֬J|SJA֪1UOcIX{@mի٥ T;1n`}m'Bi0)7ijHx^Jlj{qxyiEXi?WWޣ*%L=?nۍe92 5nap @'-暽7ap^-xm8\T@#iJːȵ7\(P+)F33;Z _ fOXٷ[ZZ%)U~|l&}BES.1#νT$K]S!ZgjeSy88]S|Qz5c~ &Oou*Pk9`N`Z8KaLTG ɥx̓r@Muq)[d)8'/Yd MCE&%(a8= B⽴X5Eߴ~ä9(s"} ^&qS=94d>-C^yE|%J㦏:rR74ͶNӋ&̹u+Di7N;)QisuҿI]ʢ(91>̯rW ;'O+]g$ ݺ0HJ0)8!<, ̹x6bnB؃:IhBifѲL FeR +RNu$҉n i,Z AZir,q6M};F=?4nglbޏtX=˔*?wG=ua2!8󦎩JПi¥&'nOilA=MNsRH 5Ly;7, WgфY}uo` *&TqTv3|RwW[4qimchc dW6@(~8#:iӶ! R t\Ή&O|9u1 -Odu4sA#F*L?>EiGL,kveWttq sdX A *:5g ICG"b$p$@IAZ$ÊD!q=Df9\9agß5'j؉(H\KՐ{C'p5HhO T@l9m\-  C[N!@=9%j|8&Zp@%0"ȟI0%&OC(ƒQIvQpZܧ|x3R`w|liHB>$Mmx@!L˹Q"4}NJ.9a༦~>y^瀐Ag*A 7i, >0`aXZ:,œ猂6/ƌQbtr9~{)*IP€u uj6)>&(9PaN tBk8E+aOuuc=($( N֑uwxjD PhP+Rk=KIi9k\`f$*Rvv&AΏAԟû Rq@%tPMj2G Wuppm.m$W˫bjgHB' 2]4?Ь0* :rz͹g~QLy-_v*xMp\&;V!| W6Y>Ώuqh<,1崩x%`S&dg=c,.P+nqҨ/0xl|+ oܐ.=1YׁU,"?H 5V#ߧxbLz>80fyYt!>)PK\M9  cSbEm?H-chf4LB7Q PNTE屐7ln%WWkumu|qWȉMraq4uej3'#݋44YԶVyp| "$.ٕ+; N[sTak!?WoDDH.e{wd0,b4QFBl SN(#  ؑ/Qo:zLdt@LLt=0fGv5 Ȅ1e-uXInsQ:p/% SuH#/6pP*9&5.,l:1AOA jˑ?cn&!MXvhL%L[1׷Ltb؃-Oǡ r3J1S_R3v垭7%y3ښAڪ{ꀂH}p(W?v[ȂT'Y7p@6y^Vj+( |aL?؃1e#$mIԅe攀dY74|yj́/k_ l Ѡ83t}+͞,`<߮8́7#P`0Qo,K 2g^q)@ΑBP%5F7=>Ag3^Qn(sF/i`(>meE ‘>%CuU ^܌2G%7$%TM5t> ^x)?b&1 $MX!j uοY {Yh D@ 1";_Ob)dj\/X$Fx % Wev[_L|5[?zczkU >#\r$jh ۠"g} Ү85MvSQ~%Mf6S1yvǧr*B~{..#+69l@av}㯭S?B2O/;5xܬF# hCmD k1!߂Ö.MY5kevYs5*tFSkjH7]X(qT_-$|1;Z\(rZpÀ pݝoyɺ+Ej77uQ̓ L'=G n\Y$̗m_Fk/s>& "BzYP9g#-'7vs{ i(U4V|2 UkfvҼgxQA%}>~:RGɵ~~m#xXxnt a HN`bFw?c޺e~ n=s&DuH?gb9S3) OL[2`# K.!\ujڲm;ew 4FH t?;Njcvlƀ؇%?J+tUt\+OU=3<ژ,x{ʌʼn U4Q\>^_u:_fH\+ 98g] Іrz9))Y,0inYJU N]6%5ГD]Ɓ{cySPo\[e\qiâ[O|ph&(#&v~xc7mJI#~-Il6dsRZ*6ϣĦ7Ek_f"pāu Ex}4!/8MU'1X86mQV;hq$A,! Dfqp|ѴYD7x>_ޮRUL3w\XDc<^x&I-9ijJywJZy\m?˟Pb ?8i}-5x&DM|_UI=쥢ysGy֨5 /!lJͧLFMXn5 6c]X0l=ڸi3۵GfWY8I6/A~G7TIM)#b 7$ɺ@zˊE6I"}SGZB.n-J$ :/m]sA䱍aLC8zľgJtב&Y$(ϩGL4-ԑ `ŭO^IL1_P{O!Њ;vp1A>!}I sz#2Νpk߈YCqưɋ֚ M6uVB 9(J]/6 #7j:Ou :03`CvJZvys#o A];gpI]ʏ\p;?b߶Dᄭ#]Dˁ:UglO띘BTaDpE9"gyㅸ)pqhmDv:/7$ m]pZN埞{/?p sRqܛ3L4nz|U\4SHQ(JaVɬݲ$hؘ°D.FX@N;{2WyrKu)#mv٬ĩ=5P]~_oީmY6㷭Fm]vⷫ:}n]c\0n.Z.߮zV};FsF_6ꞐW7`^p^_߫53i=_Y9 GKeKEl{/_];o-\9΅z8J_j$4An`AsЎ4O?cm ,l#T #c]Lhl`la7c# NTL*9NiQVې.g!bVA1~S$nELQ\F1眊"$ahwDu.mxH1iЮif;NC(Eٲ[.w Y=ʏm?TX%h :6y^8rB\1Vl g^@,~ 9刈bjMkۢMگkaȓ cQnk}[^ΛۈԌܣ keo/PRo_x[-vrrmS>#-8ˋ B91*}vZxcHX7/><|ƾ!@tA96T-9 )$3hH}'*)~BS#L L>NB!QÂ)'؞r2ޭa&c9-p"^*Ҋ/C˲ZI!.>,.}⽃K"j!˴5jXNN{xLXuo ~ԋSZo `pnT6]G {M%.7imF)<.I_e럝?vu N\s/DEFs|xk SyU9 'N@0%+WBE~iKv/}Z6ő>6r'c4{ai2tkf|Aj증4=DIٍ{oiWo+JzxGnԫyc000!h5^:QSp=2sZ.Llz#r䣀ylaAhǡ=}0ˆ ༑BaMsYx"C3yF#NĀs"e"Бv(uTb]RrRu"|͹~IVNSRR=z<+Xez1a8%_Q:hwt:A10AJa;!կ {?93g^0C`k IMs;]}PMaRڳ$<b? yn&rx"/]~LPqz<8ƅK{u"Ӈrp‘*KԮD#zW9QPA0@]z:Uy@T@nId<*|37\T`IX5dKb!XDaFthfV;FپJ]^PӠlx*M._w6G-CR7)kv)x4>\kpjKפ~(A)%R^mNO*qӽq莁FG<-F\%"TrRS+D^sp/b|#ࠃr hg`,f슯 b_*iET#AFN{Fe|3o̕!~}Oq[A 78 daT5XZQ_ׅ']2coa# ɚhiI4a[s+>{=q͕k޿]n^r@8@xrrVpľԐg% @.%#LajT`p@DmuK(ua:Ÿp,n a؜ԛ=%he5ngNXNC -5W$% ?hc{.(?s>viX. %;N >6% n$-d=B\Q0 u$:G+q \7 C _o}zų ţ|%i9vsoPLp nOJE9~Z+W6:GxGՎZP`u~xьGJ@?&͚ < oIB%Rd#ESdAAKP)=mo6r2HJLjz5's|R+ȍřq3l7%7>zj:zmZhɆŞ THm+,vtƣm^0qE]?7OsY<`S0.ML+YFlꖅ7}A)ӓ;SI_7 >/; MDL|^E]n cz$TEg0a6wiHۃ 1N}d5j`Id$ko`9{䧰B%Rҋe?K2؂{)+ 8oV{cJHLB'r!|d"uۂfT|8G{hNߤ)!\IDATV(ӳc(GOĊn }+mгM,`eߴd{^Y\˃=Yp9p D] ??70Wk01')5*ygFxQŹË]DA=+qWhWPgY'r'k8X$mhI.,9DtJ| y2. ĮsWTCӈy$ ȀDn@]VcxK쥆9cFqK~xgOMn۩"l\ㆃ=G x(|/t~A4цp)vKAt?2"ڴp? %%xw!.c~ \WEAcЀ;`sYw51ued si5 $81R[]>|1쾐$Hd4Qy؀pEm(nJȝ%!"x>)qn}m/k|NS\sQ9~8nJ6=IyޔJi4 %H_DX~0gDc|x]Qs꫔/09A8vM,u㺰3X& ݏ(ZofK.1D%;vgi5GṯKbK* bA念Yo c!"e4w[yGå 4h0r@̚!Ri%h%q-4 2O'U FZXUo {ʘ7څX={|߆趁eGBYCو=fNrF0muW]}qywn'F2dN*N= q֎h146//5fn{A?nmr@śOYޣUaAE1zdV m"%Hǒ-hK@9̖bm4fέh8а%6> 'X&uuk jY pPU NtzF 4,&ҎqM9aKdVyi;xLyz7Xc> ?DqH` >cI! u32N/X=7X0f6=EH%rlFq]EڬWllz+uʦ'ni/n}ڷs2/^ GmhT g qc/0а(Ґt "bh7Ibߏ[n(փ"7bt3{{ڨA:TW5#Wcy!p ?bo8PK;M|0PUɊq!{hBg nY0N۵uY~I'x uqRI [gTfM|Cd~]4q2pd*H/έ gY_I6VPP吓~рKNp80l 7r**.mYUsxXbÈ$nL|n1Z7份F f$i&, g%cfջJzγ|>>ظ^a_ dԆGoOĢ׋5mWol|j.n^HT5ԋ+CϘll^!uyIj&/:-IMlm|xWqr3hw]aK9ʪs_Y7ԐDnL 2#>a*t: bIQJ1> MO!#Bcu7Ҥa0}?=D:/ X*,˾%)nyMppN U c]8 m`*p,>˨ n3ndgCy݇2NH(*zbӑ&۷8hR8"5=^?i8,pfOd*Յ=XH ັo8`dRZE?Ͻnp`M'>)3 bɾad3fhtix/q14m _U߾ֶnBfSq2Kyh 1up3 c~ k o nNvX*> L!yC.gSgԽJ住a(u0_QeSc}<ԣi {T=:/ ؎"/чhӼ)4ob/%GO3DMi2sl]owmUX)sw$pu6 >Jpop''v1JS0]9{rxƏ不$AHsR^Aͩ11uRGcX՘OnD3tM?aUYhZDM/f6eh> SedrĮͪ%Cy~ܧ=0 rRsܳm)'D,TkĴh0b#zwtyCrWEd-G%E̚ME50bY`N$n d8l;NC ZhOj~hItl xHO2E"P~;ؼ,7}]TYf 9֭1*nz clXOΛ`@$c-p!q =UDGŚ mb+hwJ7utԏ޳:gű*WI[2HpR[eR+K"7T%c'VЮ X2xZR)ur "&^20&-%<v@B`uU4 wv<==ޣ!Eh>h2 +`{lA`=]F똞v^뾏7'F5xCh]&v%Ez㚰v`5U'qSQHf:!hq!?oaۻJkO_N, j65Sl{m01z6)!3=2MQ{jeKUպsJ]$Fq`5[]uiSִWMk8`Ǻuv[JĻrm[CQRd dp1?ͅǢ܋dQkS眐Vt&u.N&<6(-ʀ *j/,}ցĝiwjf̴@z {ea t<*h,=1:ER^(y|PѺ 6ϩcS2%g{42Kxäg]Gcu{熛+>5jيAUF`iF9>mpAOL~3M_M  HCZ< i# U3ݣzVn b 0`UL `CD5<0Gܪ =O; XzYPr=~p> A{e[^AzokćV95[ێ*(,?^@8 axX%Ю/22-p[`Á H+ڪeWWmmxphsb0y#m?G?.}q,P >оZbX/IN@a2?Xrλѷ7 tىP P]7wgj#m^c3Nbx\lk'm^0n $9p}2L 9[ O\|iK Avh-5&yi9|5v]vmC!"^ wsLOf^v FbD->_=.NA:]JYpml[ nfg:­,صoOEj3y7^JZ3>2-p$[Aȸ9[]4 [ju0O6~kTE 3,[m=5Dz=xrP d[~̵oal~cgxip8 ^91|)&(fgcy Y_̼!e$l5qN[@얼)'vӮ> )ia0 oPv7xw6gSgy;# a2\/Jj๪cǍ ܫSR萻vG71A7q*x0YP_C:?˴PEurod4Xtq+40jyQU!9da7vkm;^n^?dʋi y{|o Ër({F<ʋ5fQWEL062`s&pc 6#9#֘K +v>aeF /(5J } WΜb\[vB QBr3K}k㩆8^tJ&?rt2'U7-h s:ۍH"o Wlb@-5]ɸL |W-p@ i\Q`'k׮%_/P;7Sn4)Z}{]woy5+-JMт>_CZ5v@jz>_ 3 )gxi]cTgzlyln}̏ia v3?n텼5<|p_M+?n[8iIͦ>+ܯxŖ7jkڅ8jq%6'"9;ABdy$nAg`"yx}osp<޶J:˸L |Z1Xf{e]pX`Ԙ"vxɍ7o]n;ilqqȹT~ 䓖}qKaə .O3Dfn[!OG{i#tăȭ3.A^c~#a lp ZKG[!n5=m900 -qi2 ޹y+,,2Bfq@S r_*yǙ/Jpw0k~3 q=]JpM\ʈ^aqӚ:?u*(xt@A tpNP@Bɑނf-h#Xq`:+3!WhYWMV@ x6\wa1n3Nՙ 0K,]+Lkz[~9B(WIV&a@v[a 6(gc~Ob%H.v1Lo8IENDB`curator-apache-curator-2.7.1/src/site/resources/images/ph-quote.png000066400000000000000000001050031245521677600253740ustar00rootroot00000000000000PNG  IHDRWW DiCCPICC ProfileH WgTS޷$Л(JTa,$Pb VtT6:2Dݱ GTELBoZ7"Ah4F8S4 Tx0*q'+dze$A\..K@<ҀggJãF U,ILA다 \@i\-PG4["#SN|V^BPz> %Gc84 a^bX4 8(Qˀ Җ.o ( 8 HQYdObdȧ`h\*"b:BZOHCҟ%cP Ezk꤇Cp B:5HF61Nz`_ўZih7hm; d:E@1`(XhC"FAiTҏ<I7IrsG`(!m_k9XA?J5/9{Зߣ|HAI|O"'Q DpUuhA:Tii(Wb(7@P<?*fI Ahd‘#.NnԚNjw+]j9S^ #Oor/RQGR70т ``rr@1 Q%TOY0J jXa삽p(3p F;tKIG4?#$RHs%zrYK6ȇd7Ʀh>(ZmVAA;L;v[:Σ=ѿJϦϤ/o7[= Àc2BF cc*^MCTE-\-MM@BmqjOzյԭ}cE3ԗoWoPޮf0l|Z>i=k s oRyk5hxòg&Fk6md KS.g$'#Trj9W9/4544'kkVhҼ٥e%КUuDV6WY;V;O{n: k0Bm:ts 7+~=mץFfmsK֛WwLGyQ\2AMaÂ-oaKh731XaPgpߐ47o8piî} ?87#(h6KF=&ruƧLx&&&LtrMMLO>f~YlYYy-^,,-M-ZβJJb;kEu66Q6656lٶUv^v9vJaCU#n9k䍌`d,GZ1/NNN۝:8q^ERrݕ:׵mmwXEM=<=<:=-==7xZuΛ=B>:m3ZU /VD+v` uVaQeiMמ.~i38)4lYg:1i܅sE59?g /xmʷ [jJ8%[|m^}b)^(s*(D?oiҖe6-/-"`Ůr+Ǯ]_U)WUl^\\Ӷ6fm:u}Z/Y2r 7(xuS}7mEֈUUۊ=ٞ^?V0QNζ]񻚫=w^V(k:Lseo}/;̓ysb3j$umGijm8_v5;ZyLز (>(o:uqӔ&>ig _ ^@= j';09g.NDh7. h;4lB aS@]]b E0mM6`4|Vn4(o η,ΙsQj pHYs  iTXtXML:com.adobe.xmp 716 116 'q4@IDATx=`EӓB&zwPDQ@EQ '"(M@@Ei -Z %eW~w yw;;;3;;;v[=%K@.]Y" "Գ~%K@.]t  &%K@.]_,ݻaP\90PtM%K@.]#GGG\dddŋI&`HMM\2xzzBzzp>X%K@.]w% #G!d%K@^ %%Ew2D]t %K / pBV_p0;*+VL8K@.]t KŊdP߯A.]t %u &lNWub=M.]t %7S^%K@.]ODDĪ#%K@.]t'C]t %KH@w2Xut %K@d:K@.]t < NT.]t Н ]t %K@.'"x"bՑ%K@.].]t $'%gE40f ET:^]t %K W Pwl>e9ϖf2PbgȽ΄w;cJ}2^c"NG$]_{_ z4c ]*|©81> bЏ~DaMNF&DApĎ$ 4Sn-L6L4Yr'7)7eUN,I֝4y?*;X&1@[c ذ5D\Ґs5\y~Bw 9#sJND^ 3~ !)3%12hTզ4H'i>i4J7:,۝hyOf/Ì;x8k1, KO]d-0fm6w-&='d^1*<t "\9WB/+E!!M8}= GW|!&1] ? \?y_|$6D$7tqwx{pZvpk(@pp0pݻAApm S uMU6^>9 Wf#|0?s?Vbr~X cJ߄ 6>$O¬>4Nl2?"پ"nE_ 8'@&zfR|_Bҕ!?Ʀjشx!ahH2}ux+*!*2,QnXغq- kn߲ӹ3T&zwg'HPƵD$rC?Sw~8{8vJ\~>~UhU)QϣBHGÌ/WmYYr3}9\A2B&MZ^ugdHmUΏCDo}N7OC1*O8s8.~ 3nΚ)ݐr֔ v G:/! ~^Cb@XI/b 8<"F^[fhP0ҩL$5`e*a[v6l? M{td8qO*UFqkPYsE_*+EeЮ*T=f}M0Tl!>Bu>o*4Pȍ>dxE1-Y<v$@qdT?q{ⷯ +lȦYdmt[JNgo JԽu#'? ?ID4}"4pM\ )шеSsa+xRR; KHcz4GW6&:-"w̝ޣE +Mօ*&GÛAD"B655U eFes j$ͧY5{i9Py"ah4 NS&& qv|7@ P:kEIN;,A0|h#jÅhñ΅ =|7}*l?n O(\JA} "'HWei5e(,2k?9UeͩuǭHpg%y-I<} &P-9Ս@#ȜNT&2DÆ='Gu*^>nssW &<V she|pt>t)W9R"/Jz/;eT*)GJ/r&wxA*gt\>ea~fWx6aspvWe7%$D]37s~ng lD"? /_Ja=5)_L ^U-iT{4v ^V\G5zҚ3A0=b5cN\̯c,@63cŲ7˴T0ДKbŠ apS:DCɲP!RxV)/6(ʜ՘ Pҵwwe ʕ WO7^eQФ'j4Z2ɍ;R.RB**iX eSFH4Q8LKj4٠i޺NAMqƌtYOP +͕RLBš|f)5>BiS*Ue8 4HI1$Eo[]&r/2nh,VJ9OOs.HdcZGJՠD4FENuO2- K"Һnr7>~h ]S_3r=( %6,~}`kàaP0١ l;Šq%9s@ P|,!^0ҿ P!`Wai֩LmGgLYs2R  \/bn&JsvfVFR $!E0#v:SQyꎫ >8 C IEFr z|AF2Ьu P3&*hU ME>}2H6ŠfвE(ZMnB.g{Axǔu @o6 ܜLp:7fT!$E?εK$cE ^YrD +wݛm|vE odafMI9``J)+/>MiFJm 4V&=vkkz[px,+W#R 6f4-%V"E:2"BDWĴ`t WdEh޲9T.]Vm BPͽ0$~kC*os}[rIR/5B zeD;֭[&K<Cݑ t4iۃݹomk@czğIvzeLT|ï6$Q<jX4=c_n{`.m~Qx=A C%Dc?~=cWCEM$aT7$X%j|@LIlϲ`.Md%r_|lߴUN[|n؇Z(<8f8w돟ۀ BTdڻ2> Cj|[EQEIq!z}ztOwc>1M(7 *L~dq٤g>^@wawO_=w~!QRzܵ|ΓD!S| 6 7@-O8U䙾%0*݈awx9{? Zӱ&GݛuU+2Է^zop_l\]SuW|nخe'\"Q Z{0_= /[!ލfF%f6維p]>[U냻ߖT*ثq/z.@Kco>w+ˤZ#޿q ^M5kc"Sz={/Vo8 IoŋU;t(SYDF[c.f}WgSH)$m:nz/%ʪ꽅 MRb#r>'v !*0ҧ˸f ^bLjAWN㢙_8t'rL1%G۷KQ.!fMEnO+i!9Oa?k$PgS'>}b_cp hԂiQۇkuӾC<*{S%AOus z*c[-gѡ۸ky\;,kS:߱[[4$nZny |||8/7OP2- nLVvT5$*΀v|'򎘱#BQ#]Ha~Uu ~4\[U7/F/FsnriT('wb+:yW%G󫭇QP@NJ2Q{lc>5cOi? g~6u4)JPLM~~7Mkn\e]k=!wڬe@qHHxkxf2vhNi7pzL .1,`QsCnÙx 6y}t_TUYc8٦fX%u]GB%tdu.Q+8}~x9Ϥ%;1FqCt nX09|!#i(ljcHCeJ %6f-vSrĹt 9͗.rF +LV(#BS'ȗbHz ڍs&eh9s<~A?~7ӐĽGo>Ē_x\Ӣ uD>u˓q=i(^O cq7$C?(%'~i;x-8^v/f;.i3n,;^G_m*Mh!v8B%!ܘ=E9?cFqy+vi^ 'w-øiئ^M^*?-\Ee'h4I-G 댢+]_IYZ q+===d۰\^v_gocT?>lxќpU6qֽiXi|y1ǰw_DGq킷EYMO]Ǽa Ɣh\3Yuo|=j?K4켫U+/f= {y0<f-yJ/^kx#FP܅O7昜Kk~ skg*--1.|,'P{G$L}lkE.•g({ą\mKhm5f[=iybܷm >Ls m@e[f۱KSNԭCCU8iVImIѫh cKIZ78gO9ok7LF=bP Aȅje3o3=kiR}ְٜ`b#"l&pG]smm_ኳ؆Q>|KsAL0ƈdyZNs2쑩^;qKR߬;nwOP [x`Mxn:uƶNF&aHM>fgⱍrJg=Js'tuUNSw})8YI'!7c8)ɗa8)}ȸ"Cae,2E{ӇsV|i?vd0*AC4DϵمN]%R&C ~?'d[G\ǐDЯWĿ`?i %vk4i(v1ƫ(W,ֱ`6l%?-^CۇVgQ|)g+iI6qXG&95;b#bQ(rnqYlxLOf=\1U1a~>2_,Y^i$ʁfo @iZmE(dPv1p\Lmo\Ov4ڕtq؍qctig#. BhF_"m5 D:9<p3WBDҨ)5x AقNy5 $΅xez@!#-UHK^__:ұ mMh`'cO":@Zضc?lrxg`pn&mHIlcu"cHk0e-tSGҰ;+ZRz&C'ÑSW 1MrO9I1J1id`w%G|o1wWl䛕^{-x HMKe:X_.mhVy)96b2n$T*FHO`b$ziBB,]c_6gZ9Z]wϰSy3i$Ļ!eɻ5^iB]١rhI8eL߾~fvMOY >VT&_+aS L}:զ]IT6EfeϹ]K7!55Yn XFx8A8L|qlȚW`)%=6 Aڟ`܀֐NV얬01%5z5Մ%x-O} iE`ֹ"ADڎC~B& iCt~ >4 ^FPlI +9r$  Q4(ڙ m Zʆ0u 5 եt;x;гgp bǂϣ^ήG`>תւF oWõ7IS\Հ.u 疱:jat(G- L۰6u; 5!N 9{X2:ƫoXt(hݿ|PӓO#Qhhy(rϏ5R9iׁ>Օ%th;GQmCU}|nѓ>Z)MCѢ ;fŐQRս p=0v̳P ѹ6n.ДUxp)Hh)?2E c ʧ?AF/`ƣ },mMwA R;D#vhS>A"qh7+dG,3Mip`?`W[I#Yntpx8Aߞ[6L7ye:KtOj|<8xDKl<]Pzcxn0vD? }è@swRRiWAF_Uqqr0Hz B9RIpG$ePg@tBCJ[NuxT豻`@v BnqFHׯx'_BKo*"@SDO\ :V. Mۉ\ R"ςL1Zv_VJ(dhlNY5Sx>8-bB,ݖ *щs3 LL0f][o ;A"APg OTpy02D6<[%vW}p|N‰K{lj{sn,E@&6K 7jZb%i/C/d7:)gIFp׫>/e3ٮl^^B#mg[s靏h\"ph~Q_bCnF$>|`]pUcFVi b:,;V18:*7(<獲BNIdJPeSD(FZKA$cwdz 䓐+ͪX#HN/0o2jN<3LIo΄=D[a9^ hA"_? #\H$Л /HkQ ~ >q<\9c5bŋA^])O Q_[ЁL}AŒdڅG!Rq[g_COL pxvx{֧hfAt"{E<0MgF)|~ bH w\XSdֹuuPTCn4%#a_ \\s#͒LC^dhޘV0g^Q3>joh߱3ټH0uA2 ڑtxq8E7]paO.yT>MZ7 |nNL#T4&+ap0?^=t֭yw̄/]mkào{w7" 6*AeYs2!2*7±ŝ!-3.JąxBbܖ?C4{evm\3rRi W (vR`à  @^;BլTAKUT.['VkiƟv|An]2Ţc7zNZkz[w!  8u v5BšlyY7 (NB|0|;ԯRu"P8n.m4} ];h094H^uy[w )N'-5gCP1m >z-hҨl:sKz@6y7nP6$4s n3 `ˆeޛ;NLiܷ#Td#Ans7^uݞjO;ܹ| } n~ĈI),rBa\~4VZ![W6i*~W8qWK~%COgJ%/3v#b$J qJ5Ð\ l'-RFSH_vbK,8khHEm5?j6o~7$ܺ]F@=wk m"TCܵLnbٟhxA>?~\Zy Xi< ȉQ17ϗ [;qtm%8jZM- tI5!/–&ͬ#ɫ04K!qΌ~5fǎb߾?a<'p7',evb8i:Ԍh 4 x} 3>@mDsS~DH4,Z;{ n] /l^ R2r`WC:*Wt/ۯ^r Fj#eg[CT꾂oK D[ SU>erfO`}.#5X6F!l>^sȼJ֬m=(p\%aY av˃AS #SiK5`^ dY>0.xz lt <(t+AOI!ÇCJ~cW[Ym{?#7qwՁ˒u&D|N(Ӿޡ$KYPɈ?4YJd*Ϝv-:j FJ1 )Ѡdm58U7q]|#<m?dҐ'U)>Bkwf˾'ѽwdֱ$NX5RJ~Sf\ 'Z?לnr|JW{y&#@;\][/ [k ڦuZQkp@nx jKb ݳZxkr =‘C"Z՗ {}}ޟf͟r2ӦStt9骣XghW$?krKSv;3J|sɲQLxjUtƉqLBR2O8,hJ?///޽XzBS<|oU&@p-7F Cuz.-*NIH4VDi(l!^0I,UU4 !*HnYfbJ(հ#oXIL/2Rq_ާ ol^8NfD1GzCmᩦ5iMc8@߫m0)-;< [֥ Y f 7QP^S,#s+Ͱv@w(Ի T+ Wb]ػu=҇JU ][C+ţhrb7>4._dۢkq߼T.g*MSzVugDAX0vh7(FU̘O H @Az!yrvyQ+T0&;QШI} -q6ܣ-xVZzljw|?k63RbMx" gj[Z4z#rZDF@Sɢ;.E+@Y>/Lx!P81EkNH-œP~3hP$ܾpJCŧ9[r\8\nq]7T`ϖMv/9C5ṡáPYNB{>Ex h#1iOɄ?PӓA-\ zumE٨0^+ܼ>>m$hЪ ti {2pz!Pޕ>Ӑ BBhGD!Z+;H"+1JGN55/S q/[Z|oIbHaݪp.0;Cv}aԈм^Uz dK$Zݖ`e: es-?O| AJUg5T2!ˇ?!s?@‹ô@j)"DMjw?Rh]Y^TkZI-ݾȬ4<ӽfk(Q4~7@f#"'0~i-Jn8ՙ eS GkW;IDAT'yEZ ` )<9]5]ѐ*ZZ̩,"Ю6d٘-Ysğ >ˇ8k!gR̒`@%GVRZ̧dickr;KGXD;ؙd=ǫ^KrxL\c]cy%PJ|ςͩ8}6fY˪ 1 ~,cM,qlnT3+l)^Qp PdișcNFj,\6SdpIԂWK~+L5=4Xfϙk^gE"SI 6(-MOo37\Dì2.ϒ8c@屖SxlrTBeZ%إK[jKIRe#rFTpޭs[+fI#^+h7݊.^!*sms`rGkهR.._~Ә:-eK]y2?TҒ::27K処̵Y1sL| |4&{T'+shQ\ȟ=e]z䛵N {ּ`<=tT3U$6>N:0ɲ$<љOxL.]t xd :1y$V ?3\zF]t %𯑀zD/tjt/ &Dw2 ,2=.]t x utZtм?t'uu %K!^Gg߰nIJFw2tu܏Qr5a>YsvՆƣw&.//g_'\`!d_߶_ZԺO׀^~Pidzxk<o@yy%L~*(8keɿ>wZ_΢N#K@k\BIV]uE/7"g߇ttq8$ZO=)%=! EV2CcZb4EkK S>kyC<7Rj3'IjL30mKpRpO$hIKM?n) w>=>?e+>u@0ǥ xhqFA12gh\hx~Snn0\6w |n| u+ї)x͍J=8j6SFPVQy(+<< ΣQ|YjΘES~8|qyY(WNbCX`нMBB'-kWQ Iaptm!R)jC ̙Rjq9WZCh)%_ ׄn`H~ª)#NtԺU+F3̀4.vME1JƁ;t:qg@g:s<RxtGWK'ik9&Ud2lLT(wopHrp!'G9#P\=p g;N_IOIhL;2VeZlM Rie2X9I$AzvҜPr.ߊN6R\Ƕ} ǯd ->@.Nh\jBHEtf! ?U $5Q*J|pC1h9?|jx %nuvnMbYc!(/o1WVѓXLDI|6=J; ,okGBӳ 㹹 GVŶnXJNI삅~ܤ0-M5iQ]ؕ9T0}J.01hxTLcN[s.Q^y{& 4Чs)˓X)T h.Y|LgO@8Tàѥ`rR^Gtfa3Av %o24=NK9rw`Ȥ)8ii!?.Uj?Zј!ꍳ3LP|H~NzRÝFP,_qZ_{KtD?&2"ٺp#1&|$@n`i"\Y#9¯\1`*ނ3kܫ:%<w zu9T¥d¢PܮְmGRA$s(+e꫿"VEP-8خX>9ԽOF,nk\7 k_Xvu!>R D0!r5@s3 N)$0X CX[H[ t'6 P;)ioY]Ձ!C߂dz޿GNFm%E6萑 QL#2pT,W\Jȇa)B߃h2@Q P+%҈49U(CDs}"A]UzQxf \9u΅gzA 78u0>vvХSШF%H4L3)> ]mN)}h\a.5 >@4%aUD ĝ.@\S"Wg P n= ~{H/} ^_i4.jY~T[6[=E7%&3{k/h,iwCl_8 x^g2I`J Ư4"C'8\KD9ߙM` R<}dIwsGdWKy{o8V{<;`'/N6m;|?(ЮfV7̛7O<}$nt'JZ?'MMo4'cA鴘Or >/|;vW_=/4Za-0n'׈֭b٢.Lض]+q?u _Qd+p<@=hSS:SLg;U୰8|xxv0ⵃt*<' tǜ~T[v2O{iN[!ᕣ8<]qFYߍmD KsJ][hՌS=b^H[@S0oi"^?`zMCڃLŇxG:^e hcbjqfU7a5Y=oZs-xމ8xv2K:Pn _$=خ˱j>af #JK\5{uqXٵ \t[C\2i*FgclZQJ9 O\ SzclVuo/1Yw!\sv6^val7 fLgL_Ա[RE A};:]ԇ?aDԭGfxc'Zv>][S|{֨.ZޕtUlȢ .V̬gX,3f.m2wQs_0WQA1A6ٙ{/b_Μ93rfN]Ka8Y /L\T@4"۷O8zMZW!(o wH[ 8#7wѸu[ѡ#:"+ҟ Z*=hD S:W'{kOrL!â@BȌs^S;2Ċ_R5UoEEZiϕt!mtgAr>m;lKRĒ)d|G}$b3$qVAJ]4 8ϊA+9%mfC4ܧ8.2.c*wJ"EaQa| w6@ɍue.)E'bjt׃s5ڈMi:8:NSGζ?I&JIeIPDY؆'Du63|zR@t.%)E_.'v }ˆGCz,B'y< gNh_|^P:=zGP2Y-|c&SȨ# ;^g4jlhա?Kӱ  {_xS{R v& ۹l9@iw`NFEebvlCFeN%#)'XkԐ _ٹDB&:>kc롯DO? mEWNuo[[Gq5r$И4!-b'^5".ð Ak͹Q# CzhOjRŇ3%"u4ՓSoUFcXk' 0s0ɑ1m_XZէm\J]4/4[}@=ި@ҥJꀶR3Ԝ+3u'ѽGSET)/G upoVhܽ&\I_⧙3m[. q{(~ ŝχ >]=}:E1~?bM? K:aUe-{Y^m]QG lr "[k5̈ڲ\ 0EO]HNG ATw˭;\>bEdCв17;Ҁac~i !6I,;Xj41'ixol8,flh|J{GI jt(é&uA>嫢`|Vɟ6͇pKm1jᔐ"~gҎhۛ)d6L_wh\AѲ]0^}~~fG67F4rϧaS4mp֠F~g맚Ó/!.)ɕFZuelcQv+{ᚪ5,ܴP%wvk}z9 Qá*/WbIj0/CLF&`cqyՇx'}߆A5!_Y +'ى<$|p'DLz!I-iIiH:LN!%WH~!UK>NvE.NBϺJ (NoNGZaKܼDAG6aewSghV; l6磎J;W:uԖfBTdG9d_~fgaĴUtBmM;f j:CfRä-縃Ug'`p_RV4"-=cDÃ`ʼҶwMp(q@=|ص}GA rB]JT̍]oNt;TwT;zIoΣiyB"mDnf:^&,fIu"U^/' lH~5^GEeE :qyDUrcay=e;iZҒ^ijɊ]Y\5V0ۆpgPŞ&(ΧqơYPW<ܽR#gQ- T0"7A39\T8Y!]oS:%=%OyQ5}%Mr4;4u@lR/ы)CgY NO3*ct$= !KƿkFǑg"UrZnk#JH=(ћ+\Z6$9g| ]umt>}$^pC~g&zǡᆻ=#ep>rh x0#ivb-UgRBWMx00'ǚhJ üw"S[rRYpӽ+$ J,` V{3@~tJ"R/K'9ov.xȡ/|7lٌ7G=7g4 شL7yh] .p%crܚg':v$VJ7Эcsu\>u<>.vyYB[l*\s&)FGc+>j2<n5]AVՈPEnǕʱ^${U|u' GΧCnǑt2YZޠX  9I$D V偒kSI+SMY)_enTo-Eʛt|r*>|kց!5INƾMs/:X4)?Bժ?DD <܎[i6dLFbyӟmM_/c70k Q[3kӍ;1[ilQ>b#rK^ʐtv5*Cu7[q5>[#ªjQH:O:@ʦXM;P~eirht*CI[?j#;}/jdʹ,޹afro.:f_5+?!ANl6ItHwX$rOT =ݍ$F3 f 2S `\0'!|?捜BcC kػ}`߾}8t ߋaDl<~gsEn%M$LNVbd,?Inޣ\ߪ||g(.SBdqh6ՊrQB{nSTsϾsr1~Xr)Q3/?.i(hƍUh%N،Wνwp!!xb%9*:MFT ꀰxـl/!a&$uD`Tb_LG5\HpF3ǡox_O,;%xp/3VEzӃ ,NXQGuN½Y32ӰHCb;$gGG+TִBJ2ZZu!},^TY%%Ԗҗ\_4 z.CZ~Òb$bC帆bcػyGmsP2WtBAV2BCVbS>eRDvGoOxvG 5Tø$=Zy,s2U:I+DCed5 :Ti&}&,ij~a^7T1{S&-(b}A?au'?U<.}^CO];#_e<d7aiKC/ Qd#>ϊݫIumGI(:˳ bxA}YaR6u6~uƏUv牸Ҹ姊yO*ˡh%*32Oډ5u ]"2K-^ɩ8]l#Ne[1gd8,0`'էAbiƮPi q8&퍲 VSv'M=VSD:QVyRn84.$f&.px{i(l.]wKRÔ4B /O/"~ΰ~z>ˈ z! MY)g9+ח2yX߹\wzTߵG/QL48>c̙(HGl?kMX\(iTk⬦EK :ùmuv~ϋ=arY,!)ϫpn8a^; jػa}R*ӒsMK{t|8e:q*n鐥Z6zcⰱ{YR'zhֺ\kW%G!5hm5_zAч}Fp5s<@ u.xҜFNߪZ4(D6~֐g3W%0ePԯqRGO>kkGcCxh-krEuZ/ȿAG.#'Pj$/UO OrkoGy~wy954~#œKIxkOR0O'8uIs c³J$G \=#];G(]>{S-6Fn'ѹMS `*n f_tҠh؏fnPI5ӑߴugYͽ!;1ovR־@ߠD ?>׬"K8rYvο˯;~/8^©K2?~zKv%-|(/c{CGm7ZOዖ]ihWm8eVmpp6nZ3j{\\jʧscx)Q3d]$MS?ʯ*.60}LQ.qzNi_L5lHnu9'<&:g=6MHxŮZZ̧iY[14#^lX]n ]vW^rJZF#2yTUU KZx0CFG:>_teI&"SDytE-4 H+_jbY3-P pQ\Bڠ&-/XWx;ED& 2t Jwp?3CFe_^n$(u$pYǓ6i>_e$:ӽ bi'sH)pA`xȫ/{TsPk+%祀փSc,zJ[] OWj(ҼݲScq62Zhzh$dTG]tjg&c ll"a=t퓛lJH4lU,tY)BryMjZX9/{qJ s߃ڡjG8'cBp<*'޽Ђpn0s e"b*tKlD${9t73}CJ8j{z{Kz,J|1Xi ^LjC{…V!)-+.{y\is[wU㗓!pZi7=F>6U_BQK֥;zҽ.11QzPyQ(\uE@}o0Π! d ➞ qH̱=)}fb^/DD\g""<hB() ,/􅔄k({<܌Ae U+1Hȃ[OR լB#:4.N, ozsŤI@NJM60"hی?SDws#כ],m/Tn)"U-#_̋0~@w,;L_>@wTH-54η &nry1ƄoE݉!hW&DQ52꒐6FҚoA[Xyƨ7PSnYǪRA~>eŸiq$Olp mam53p"h ?֯F#M}a~N-e' 7 lO X45os9/k~(?ܐR~JiˋtfK^hEv %MbhgPơwֈ̀t2ya͖-ze0p+`,k%?>A2i"\v -Nk6+ [Źfzki<*Wi/z|tZY}'͵N149!+OU]?*s| nf1ʹz47-Z0MTe>)nVqDޞdHU*ޒ{)j*B ۡT h))L[E<ʳ/vyTT*nx(;S-ï)dT)DD ݠmUʓnH|pX^6*-1;B DDx궢 UF@MF]fN2A2f(&& Po%MJqq7V#.**e`:NL!whz700o@NHq d0000De)K{DN"`dItM&&&?IFŢad2LB2f8&&&&&1L!/frMLLLLq610000!`  7k"`"`"`"`"pIDWq2՝Vw#2k02 uὝMG3&&&&&&&"H+֩?_ti"`"`"`"`"`"`"g .S4h"I` Z?ᛖ?uDDDDDDு <- Ck@`DDDDDDn @R/NIENDB`curator-apache-curator-2.7.1/src/site/site.xml000066400000000000000000000126351245521677600213430ustar00rootroot00000000000000 org.apache.maven.skins maven-fluido-skin 1.3.0 apache-curator factoids ApacheCurator false false Apache Curator /images/curator-logo.png /index.html Apache http://apache.org/images/feather-small.gif http://apache.org