zookeeper-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From an...@apache.org
Subject [39/51] [partial] zookeeper git commit: ZOOKEEPER-3032: MAVEN MIGRATION - branch-3.5 - move java server, client
Date Fri, 05 Oct 2018 13:37:07 GMT
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/main/org/apache/zookeeper/common/ZKHostnameVerifier.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/common/ZKHostnameVerifier.java b/src/java/main/org/apache/zookeeper/common/ZKHostnameVerifier.java
deleted file mode 100644
index 740fef0..0000000
--- a/src/java/main/org/apache/zookeeper/common/ZKHostnameVerifier.java
+++ /dev/null
@@ -1,349 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper.common;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.naming.InvalidNameException;
-import javax.naming.NamingException;
-import javax.naming.directory.Attribute;
-import javax.naming.directory.Attributes;
-import javax.naming.ldap.LdapName;
-import javax.naming.ldap.Rdn;
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLSession;
-import javax.security.auth.x500.X500Principal;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateParsingException;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Locale;
-import java.util.NoSuchElementException;
-import java.util.Objects;
-import java.util.regex.Pattern;
-
-/**
- * Note: copied from Apache httpclient with some modifications. We want host verification, but depending
- * on the httpclient jar caused unexplained performance regressions (even when the code was not used).
- */
-final class ZKHostnameVerifier implements HostnameVerifier {
-
-    /**
-     * Note: copied from Apache httpclient with some minor modifications. We want host verification, but depending
-     * on the httpclient jar caused unexplained performance regressions (even when the code was not used).
-     */
-    private static final class SubjectName {
-        static final int DNS = 2;
-        static final int IP = 7;
-
-        private final String value;
-        private final int type;
-
-        static SubjectName IP(final String value) {
-            return new SubjectName(value, IP);
-        }
-
-        static SubjectName DNS(final String value) {
-            return new SubjectName(value, DNS);
-        }
-
-        SubjectName(final String value, final int type) {
-            if (type != DNS && type != IP) {
-                throw new IllegalArgumentException("Invalid type: " + type);
-            }
-            this.value = Objects.requireNonNull(value);
-            this.type = type;
-        }
-
-        public int getType() {
-            return type;
-        }
-
-        public String getValue() {
-            return value;
-        }
-
-        @Override
-        public String toString() {
-            return value;
-        }
-    }
-
-    /**
-     * Note: copied from Apache httpclient. We want host verification, but depending on the
-     * httpclient jar caused unexplained performance regressions (even when the code was not used).
-     */
-    private static class InetAddressUtils {
-        private InetAddressUtils() {}
-
-        private static final Pattern IPV4_PATTERN = Pattern.compile(
-                "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
-
-        private static final Pattern IPV6_STD_PATTERN = Pattern.compile(
-                "^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$");
-
-        private static final Pattern IPV6_HEX_COMPRESSED_PATTERN = Pattern.compile(
-                "^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$");
-
-        static boolean isIPv4Address(final String input) {
-            return IPV4_PATTERN.matcher(input).matches();
-        }
-
-        static boolean isIPv6StdAddress(final String input) {
-            return IPV6_STD_PATTERN.matcher(input).matches();
-        }
-
-        static boolean isIPv6HexCompressedAddress(final String input) {
-            return IPV6_HEX_COMPRESSED_PATTERN.matcher(input).matches();
-        }
-
-        static boolean isIPv6Address(final String input) {
-            return isIPv6StdAddress(input) || isIPv6HexCompressedAddress(input);
-        }
-    }
-
-    enum HostNameType {
-
-        IPv4(7), IPv6(7), DNS(2);
-
-        final int subjectType;
-
-        HostNameType(final int subjectType) {
-            this.subjectType = subjectType;
-        }
-
-    }
-
-    private final Logger log = LoggerFactory.getLogger(ZKHostnameVerifier.class);
-
-    @Override
-    public boolean verify(final String host, final SSLSession session) {
-        try {
-            final Certificate[] certs = session.getPeerCertificates();
-            final X509Certificate x509 = (X509Certificate) certs[0];
-            verify(host, x509);
-            return true;
-        } catch (final SSLException ex) {
-            if (log.isDebugEnabled()) {
-                log.debug(ex.getMessage(), ex);
-            }
-            return false;
-        }
-    }
-
-    void verify(final String host, final X509Certificate cert) throws SSLException {
-        final HostNameType hostType = determineHostFormat(host);
-        final List<SubjectName> subjectAlts = getSubjectAltNames(cert);
-        if (subjectAlts != null && !subjectAlts.isEmpty()) {
-            switch (hostType) {
-                case IPv4:
-                    matchIPAddress(host, subjectAlts);
-                    break;
-                case IPv6:
-                    matchIPv6Address(host, subjectAlts);
-                    break;
-                default:
-                    matchDNSName(host, subjectAlts);
-            }
-        } else {
-            // CN matching has been deprecated by rfc2818 and can be used
-            // as fallback only when no subjectAlts are available
-            final X500Principal subjectPrincipal = cert.getSubjectX500Principal();
-            final String cn = extractCN(subjectPrincipal.getName(X500Principal.RFC2253));
-            if (cn == null) {
-                throw new SSLException("Certificate subject for <" + host + "> doesn't contain " +
-                        "a common name and does not have alternative names");
-            }
-            matchCN(host, cn);
-        }
-    }
-
-    private static void matchIPAddress(final String host, final List<SubjectName> subjectAlts) throws SSLException {
-        for (int i = 0; i < subjectAlts.size(); i++) {
-            final SubjectName subjectAlt = subjectAlts.get(i);
-            if (subjectAlt.getType() == SubjectName.IP) {
-                if (host.equals(subjectAlt.getValue())) {
-                    return;
-                }
-            }
-        }
-        throw new SSLPeerUnverifiedException("Certificate for <" + host + "> doesn't match any " +
-                "of the subject alternative names: " + subjectAlts);
-    }
-
-    private static void matchIPv6Address(final String host, final List<SubjectName> subjectAlts) throws SSLException {
-        final String normalisedHost = normaliseAddress(host);
-        for (int i = 0; i < subjectAlts.size(); i++) {
-            final SubjectName subjectAlt = subjectAlts.get(i);
-            if (subjectAlt.getType() == SubjectName.IP) {
-                final String normalizedSubjectAlt = normaliseAddress(subjectAlt.getValue());
-                if (normalisedHost.equals(normalizedSubjectAlt)) {
-                    return;
-                }
-            }
-        }
-        throw new SSLPeerUnverifiedException("Certificate for <" + host + "> doesn't match any " +
-                "of the subject alternative names: " + subjectAlts);
-    }
-
-    private static void matchDNSName(final String host, final List<SubjectName> subjectAlts) throws SSLException {
-        final String normalizedHost = host.toLowerCase(Locale.ROOT);
-        for (int i = 0; i < subjectAlts.size(); i++) {
-            final SubjectName subjectAlt = subjectAlts.get(i);
-            if (subjectAlt.getType() == SubjectName.DNS) {
-                final String normalizedSubjectAlt = subjectAlt.getValue().toLowerCase(Locale.ROOT);
-                if (matchIdentityStrict(normalizedHost, normalizedSubjectAlt)) {
-                    return;
-                }
-            }
-        }
-        throw new SSLPeerUnverifiedException("Certificate for <" + host + "> doesn't match any " +
-                "of the subject alternative names: " + subjectAlts);
-    }
-
-    private static void matchCN(final String host, final String cn) throws SSLException {
-        final String normalizedHost = host.toLowerCase(Locale.ROOT);
-        final String normalizedCn = cn.toLowerCase(Locale.ROOT);
-        if (!matchIdentityStrict(normalizedHost, normalizedCn)) {
-            throw new SSLPeerUnverifiedException("Certificate for <" + host + "> doesn't match " +
-                    "common name of the certificate subject: " + cn);
-        }
-    }
-
-    private static boolean matchIdentity(final String host, final String identity,
-                                         final boolean strict) {
-        // RFC 2818, 3.1. Server Identity
-        // "...Names may contain the wildcard
-        // character * which is considered to match any single domain name
-        // component or component fragment..."
-        // Based on this statement presuming only singular wildcard is legal
-        final int asteriskIdx = identity.indexOf('*');
-        if (asteriskIdx != -1) {
-            final String prefix = identity.substring(0, asteriskIdx);
-            final String suffix = identity.substring(asteriskIdx + 1);
-            if (!prefix.isEmpty() && !host.startsWith(prefix)) {
-                return false;
-            }
-            if (!suffix.isEmpty() && !host.endsWith(suffix)) {
-                return false;
-            }
-            // Additional sanity checks on content selected by wildcard can be done here
-            if (strict) {
-                final String remainder = host.substring(
-                        prefix.length(), host.length() - suffix.length());
-                if (remainder.contains(".")) {
-                    return false;
-                }
-            }
-            return true;
-        }
-        return host.equalsIgnoreCase(identity);
-    }
-
-    private static boolean matchIdentityStrict(final String host, final String identity) {
-        return matchIdentity(host, identity, true);
-    }
-
-    private static String extractCN(final String subjectPrincipal) throws SSLException {
-        if (subjectPrincipal == null) {
-            return null;
-        }
-        try {
-            final LdapName subjectDN = new LdapName(subjectPrincipal);
-            final List<Rdn> rdns = subjectDN.getRdns();
-            for (int i = rdns.size() - 1; i >= 0; i--) {
-                final Rdn rds = rdns.get(i);
-                final Attributes attributes = rds.toAttributes();
-                final Attribute cn = attributes.get("cn");
-                if (cn != null) {
-                    try {
-                        final Object value = cn.get();
-                        if (value != null) {
-                            return value.toString();
-                        }
-                    } catch (final NoSuchElementException ignore) {
-                        // ignore exception
-                    } catch (final NamingException ignore) {
-                        // ignore exception
-                    }
-                }
-            }
-            return null;
-        } catch (final InvalidNameException e) {
-            throw new SSLException(subjectPrincipal + " is not a valid X500 distinguished name");
-        }
-    }
-
-    private static HostNameType determineHostFormat(final String host) {
-        if (InetAddressUtils.isIPv4Address(host)) {
-            return HostNameType.IPv4;
-        }
-        String s = host;
-        if (s.startsWith("[") && s.endsWith("]")) {
-            s = host.substring(1, host.length() - 1);
-        }
-        if (InetAddressUtils.isIPv6Address(s)) {
-            return HostNameType.IPv6;
-        }
-        return HostNameType.DNS;
-    }
-
-    private static List<SubjectName> getSubjectAltNames(final X509Certificate cert) {
-        try {
-            final Collection<List<?>> entries = cert.getSubjectAlternativeNames();
-            if (entries == null) {
-                return Collections.emptyList();
-            }
-            final List<SubjectName> result = new ArrayList<SubjectName>();
-            for (List<?> entry: entries) {
-                final Integer type = entry.size() >= 2 ? (Integer) entry.get(0) : null;
-                if (type != null) {
-                    final String s = (String) entry.get(1);
-                    result.add(new SubjectName(s, type));
-                }
-            }
-            return result;
-        } catch (final CertificateParsingException ignore) {
-            return Collections.emptyList();
-        }
-    }
-
-    /*
-     * Normalize IPv6 or DNS name.
-     */
-    private static String normaliseAddress(final String hostname) {
-        if (hostname == null) {
-            return hostname;
-        }
-        try {
-            final InetAddress inetAddress = InetAddress.getByName(hostname);
-            return inetAddress.getHostAddress();
-        } catch (final UnknownHostException unexpected) { // Should not happen, because we check for IPv6 address above
-            return hostname;
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/main/org/apache/zookeeper/common/ZKTrustManager.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/common/ZKTrustManager.java b/src/java/main/org/apache/zookeeper/common/ZKTrustManager.java
deleted file mode 100644
index 73006d0..0000000
--- a/src/java/main/org/apache/zookeeper/common/ZKTrustManager.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.zookeeper.common;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.X509ExtendedTrustManager;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.UnknownHostException;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-
-/**
- * A custom TrustManager that supports hostname verification via org.apache.http.conn.ssl.DefaultHostnameVerifier.
- *
- * We attempt to perform verification using just the IP address first and if that fails will attempt to perform a
- * reverse DNS lookup and verify using the hostname.
- */
-public class ZKTrustManager extends X509ExtendedTrustManager {
-
-    private static final Logger LOG = LoggerFactory.getLogger(ZKTrustManager.class);
-
-    private X509ExtendedTrustManager x509ExtendedTrustManager;
-    private boolean serverHostnameVerificationEnabled;
-    private boolean clientHostnameVerificationEnabled;
-
-    private ZKHostnameVerifier hostnameVerifier;
-
-    /**
-     * Instantiate a new ZKTrustManager.
-     *
-     * @param x509ExtendedTrustManager The trustmanager to use for checkClientTrusted/checkServerTrusted logic
-     * @param serverHostnameVerificationEnabled  If true, this TrustManager should verify hostnames of servers that this
-     *                                 instance connects to.
-     * @param clientHostnameVerificationEnabled  If true, the hostname of a client connecting to this machine will be
-     *                                           verified.
-     */
-    ZKTrustManager(X509ExtendedTrustManager x509ExtendedTrustManager, boolean serverHostnameVerificationEnabled,
-                   boolean clientHostnameVerificationEnabled) {
-        this.x509ExtendedTrustManager = x509ExtendedTrustManager;
-        this.serverHostnameVerificationEnabled = serverHostnameVerificationEnabled;
-        this.clientHostnameVerificationEnabled = clientHostnameVerificationEnabled;
-        hostnameVerifier = new ZKHostnameVerifier();
-    }
-
-    @Override
-    public X509Certificate[] getAcceptedIssuers() {
-        return x509ExtendedTrustManager.getAcceptedIssuers();
-    }
-
-    @Override
-    public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
-        x509ExtendedTrustManager.checkClientTrusted(chain, authType, socket);
-        if (clientHostnameVerificationEnabled) {
-            performHostVerification(socket.getInetAddress(), chain[0]);
-        }
-    }
-
-    @Override
-    public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
-        x509ExtendedTrustManager.checkServerTrusted(chain, authType, socket);
-        if (serverHostnameVerificationEnabled) {
-            performHostVerification(socket.getInetAddress(), chain[0]);
-        }
-    }
-
-    @Override
-    public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
-        x509ExtendedTrustManager.checkServerTrusted(chain, authType, engine);
-        if (clientHostnameVerificationEnabled) {
-            try {
-                performHostVerification(InetAddress.getByName(engine.getPeerHost()), chain[0]);
-            } catch (UnknownHostException e) {
-                throw new CertificateException("Failed to verify host", e);
-            }
-        }
-    }
-
-    @Override
-    public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine)
-            throws CertificateException {
-        x509ExtendedTrustManager.checkServerTrusted(chain, authType, engine);
-        if (serverHostnameVerificationEnabled) {
-            try {
-                performHostVerification(InetAddress.getByName(engine.getPeerHost()), chain[0]);
-            } catch (UnknownHostException e) {
-                throw new CertificateException("Failed to verify host", e);
-            }
-        }
-    }
-
-    @Override
-    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
-        x509ExtendedTrustManager.checkClientTrusted(chain, authType);
-    }
-
-    @Override
-    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
-        x509ExtendedTrustManager.checkServerTrusted(chain, authType);
-    }
-
-    /**
-     * Compares peer's hostname with the one stored in the provided client certificate. Performs verification
-     * with the help of provided HostnameVerifier.
-     *
-     * @param inetAddress Peer's inet address.
-     * @param certificate Peer's certificate
-     * @throws CertificateException Thrown if the provided certificate doesn't match the peer hostname.
-     */
-    private void performHostVerification(InetAddress inetAddress, X509Certificate certificate)
-            throws CertificateException {
-        String hostAddress = "";
-        String hostName = "";
-        try {
-            hostAddress = inetAddress.getHostAddress();
-            hostnameVerifier.verify(hostAddress, certificate);
-        } catch (SSLException addressVerificationException) {
-            try {
-                LOG.debug("Failed to verify host address: {} attempting to verify host name with reverse dns lookup",
-                        hostAddress, addressVerificationException);
-                hostName = inetAddress.getHostName();
-                hostnameVerifier.verify(hostName, certificate);
-            } catch (SSLException hostnameVerificationException) {
-                LOG.error("Failed to verify host address: {}", hostAddress, addressVerificationException);
-                LOG.error("Failed to verify hostname: {}", hostName, hostnameVerificationException);
-                throw new CertificateException("Failed to verify both host address and host name",
-                        hostnameVerificationException);
-            }
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/main/org/apache/zookeeper/jmx/CommonNames.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/jmx/CommonNames.java b/src/java/main/org/apache/zookeeper/jmx/CommonNames.java
deleted file mode 100644
index 986d69d..0000000
--- a/src/java/main/org/apache/zookeeper/jmx/CommonNames.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper.jmx;
-
-/**
- * A bunch of constants.
- * TODO: will get rid of it eventually.
- */
-public class CommonNames {
-    public static final String DOMAIN="org.apache.ZooKeeperService";
-    public static final String DATA_TREE_KEY="DataTree";
-    public static final String STANDALONE_SERVER_KEY="StandaloneServer";
-}

http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/main/org/apache/zookeeper/jmx/MBeanRegistry.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/jmx/MBeanRegistry.java b/src/java/main/org/apache/zookeeper/jmx/MBeanRegistry.java
deleted file mode 100644
index 817afc0..0000000
--- a/src/java/main/org/apache/zookeeper/jmx/MBeanRegistry.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper.jmx;
-
-import java.lang.management.ManagementFactory;
-import java.util.Collection;
-import java.util.Map;
-import java.util.Set;
-import java.util.HashSet;
-import java.util.concurrent.ConcurrentHashMap;
-
-import javax.management.JMException;
-import javax.management.MBeanServer;
-import javax.management.MBeanServerFactory;
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This class provides a unified interface for registering/unregistering of
- * zookeeper MBeans with the platform MBean server. It builds a hierarchy of MBeans
- * where each MBean represented by a filesystem-like path. Eventually, this hierarchy
- * will be stored in the zookeeper data tree instance as a virtual data tree.
- */
-public class MBeanRegistry {
-    private static final Logger LOG = LoggerFactory.getLogger(MBeanRegistry.class);
-    
-    private static volatile MBeanRegistry instance = new MBeanRegistry();
-    
-    private final Object LOCK = new Object();
-    
-    private Map<ZKMBeanInfo, String> mapBean2Path =
-        new ConcurrentHashMap<ZKMBeanInfo, String>();
-    
-    private MBeanServer mBeanServer;
-
-    /**
-     * Useful for unit tests. Change the MBeanRegistry instance
-     *
-     * @param instance new instance
-     */
-    public static void setInstance(MBeanRegistry instance) {
-        MBeanRegistry.instance = instance;
-    }
-
-    public static MBeanRegistry getInstance() {
-        return instance;
-    }
-
-    public MBeanRegistry () {
-        try {
-            mBeanServer = ManagementFactory.getPlatformMBeanServer();        
-        } catch (Error e) {
-            // Account for running within IKVM and create a new MBeanServer
-            // if the PlatformMBeanServer does not exist.
-            mBeanServer =  MBeanServerFactory.createMBeanServer();
-        }
-    }
-
-    /**
-     * Return the underlying MBeanServer that is being
-     * used to register MBean's. The returned MBeanServer
-     * may be a new empty MBeanServer if running through IKVM.
-     */
-    public MBeanServer getPlatformMBeanServer() {
-        return mBeanServer;
-    }
-
-    /**
-     * Registers a new MBean with the platform MBean server. 
-     * @param bean the bean being registered
-     * @param parent if not null, the new bean will be registered as a child
-     * node of this parent.
-     */
-    public void register(ZKMBeanInfo bean, ZKMBeanInfo parent)
-        throws JMException
-    {
-        assert bean != null;
-        String path = null;
-        if (parent != null) {
-            path = mapBean2Path.get(parent);
-            assert path != null;
-        }
-        path = makeFullPath(path, parent);
-        if(bean.isHidden())
-            return;
-        ObjectName oname = makeObjectName(path, bean);
-        try {
-            synchronized (LOCK) {
-                mBeanServer.registerMBean(bean, oname);
-                mapBean2Path.put(bean, path);
-            }
-        } catch (JMException e) {
-            LOG.warn("Failed to register MBean " + bean.getName());
-            throw e;
-        }
-    }
-
-    /**
-     * Unregister the MBean identified by the path.
-     * @param path
-     * @param bean
-     */
-    private void unregister(String path,ZKMBeanInfo bean) throws JMException  {
-        if(path==null)
-            return;
-        if (!bean.isHidden()) {
-            final ObjectName objName = makeObjectName(path, bean);
-            LOG.debug("Unregister MBean [{}]", objName);
-            synchronized (LOCK) {
-               mBeanServer.unregisterMBean(objName);
-            }
-        }        
-    }
-    
-    /**
-     * @return a {@link Collection} with the {@link ZKMBeanInfo} instances not
-     *         unregistered. Mainly for testing purposes.
-     */
-    public Set<ZKMBeanInfo> getRegisteredBeans() {
-        return new HashSet<ZKMBeanInfo>(mapBean2Path.keySet());
-    }
-
-    /**
-     * Unregister MBean.
-     * @param bean
-     */
-    public void unregister(ZKMBeanInfo bean) {
-        if(bean==null)
-            return;
-        String path = mapBean2Path.remove(bean);
-        try {
-            unregister(path,bean);
-        } catch (JMException e) {
-            LOG.warn("Error during unregister of [{}]", bean.getName(), e);
-        } catch (Throwable t) {
-            LOG.error("Unexpected exception during unregister of [{}]. It should be reviewed and fixed.", bean.getName(), t);
-        }
-    }
-
-    /**
-     * Generate a filesystem-like path.
-     * @param prefix path prefix
-     * @param name path elements
-     * @return absolute path
-     */
-    public String makeFullPath(String prefix, String... name) {
-        StringBuilder sb=new StringBuilder(prefix == null ? "/" : (prefix.equals("/")?prefix:prefix+"/"));
-        boolean first=true;
-        for (String s : name) {
-            if(s==null) continue;
-            if(!first){
-                sb.append("/");
-            }else
-                first=false;
-            sb.append(s);
-        }
-        return sb.toString();
-    }
-    
-    protected String makeFullPath(String prefix, ZKMBeanInfo bean) {
-        return makeFullPath(prefix, bean == null ? null : bean.getName());
-    }
-
-    /**
-     * This takes a path, such as /a/b/c, and converts it to 
-     * name0=a,name1=b,name2=c
-     */
-    private int tokenize(StringBuilder sb, String path, int index){
-        String[] tokens = path.split("/");
-        for (String s: tokens) {
-            if (s.length()==0)
-                continue;
-            sb.append("name").append(index++)
-                    .append("=").append(s).append(",");
-        }
-        return index;
-    }
-    /**
-     * Builds an MBean path and creates an ObjectName instance using the path. 
-     * @param path MBean path
-     * @param bean the MBean instance
-     * @return ObjectName to be registered with the platform MBean server
-     */
-    protected ObjectName makeObjectName(String path, ZKMBeanInfo bean)
-        throws MalformedObjectNameException
-    {
-        if(path==null)
-            return null;
-        StringBuilder beanName = new StringBuilder(CommonNames.DOMAIN + ":");
-        int counter=0;
-        counter=tokenize(beanName,path,counter);
-        tokenize(beanName,bean.getName(),counter);
-        beanName.deleteCharAt(beanName.length()-1);
-        try {
-            return new ObjectName(beanName.toString());
-        } catch (MalformedObjectNameException e) {
-            LOG.warn("Invalid name \"" + beanName.toString() + "\" for class "
-                    + bean.getClass().toString());
-            throw e;
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/main/org/apache/zookeeper/jmx/ManagedUtil.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/jmx/ManagedUtil.java b/src/java/main/org/apache/zookeeper/jmx/ManagedUtil.java
deleted file mode 100644
index 43451b0..0000000
--- a/src/java/main/org/apache/zookeeper/jmx/ManagedUtil.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper.jmx;
-
-import java.util.Enumeration;
-
-import javax.management.JMException;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Shared utilities
- */
-public class ManagedUtil {
-    private static final Logger LOG = LoggerFactory.getLogger(ManagedUtil.class);
-
-    private static final boolean isLog4jJmxEnabled() {
-        boolean enabled = false;
-
-        try {
-            Class.forName("org.apache.log4j.spi.LoggerRepository");
-
-            if (Boolean.getBoolean("zookeeper.jmx.log4j.disable") == true) {
-                LOG.info("Log4j found but jmx support is disabled.");
-            } else {
-                enabled = true;
-                LOG.info("Log4j found with jmx enabled.");
-            }
-
-        } catch (ClassNotFoundException e) {
-            LOG.info("Log4j not found.");
-        }
-
-        return enabled;
-    }
-
-
-    /**
-     * Register the log4j JMX mbeans. Set environment variable
-     * "zookeeper.jmx.log4j.disable" to true to disable registration.
-     * @see http://logging.apache.org/log4j/1.2/apidocs/index.html?org/apache/log4j/jmx/package-summary.html
-     * @throws JMException if registration fails
-     */
-    @SuppressWarnings("rawtypes")
-    public static void registerLog4jMBeans() throws JMException {
-        if (isLog4jJmxEnabled()) {
-            LOG.debug("registerLog4jMBeans()");
-            MBeanServer mbs = MBeanRegistry.getInstance().getPlatformMBeanServer();
-
-            try {
-                // Create and Register the top level Log4J MBean
-                // org.apache.log4j.jmx.HierarchyDynamicMBean hdm = new org.apache.log4j.jmx.HierarchyDynamicMBean();
-                Object hdm = Class.forName("org.apache.log4j.jmx.HierarchyDynamicMBean").getDeclaredConstructor().newInstance();
-
-                ObjectName mbo = new ObjectName("log4j:hiearchy=default");
-                mbs.registerMBean(hdm, mbo);
-
-                // Add the root logger to the Hierarchy MBean
-                // org.apache.log4j.Logger rootLogger =
-                // org.apache.log4j.Logger.getRootLogger();
-                Object rootLogger = Class.forName("org.apache.log4j.Logger")
-                        .getMethod("getRootLogger", (Class<?>[]) null)
-                        .invoke(null, (Object[]) null);
-
-                // hdm.addLoggerMBean(rootLogger.getName());
-                Object rootLoggerName = rootLogger.getClass()
-                        .getMethod("getName", (Class<?>[]) null)
-                        .invoke(rootLogger, (Object[]) null);
-                hdm.getClass().getMethod("addLoggerMBean", String.class)
-                        .invoke(hdm, rootLoggerName);
-
-                // Get each logger from the Log4J Repository and add it to the
-                // Hierarchy MBean created above.
-                // org.apache.log4j.spi.LoggerRepository r =
-                // org.apache.log4j.LogManager.getLoggerRepository();
-                Object r = Class.forName("org.apache.log4j.LogManager")
-                        .getMethod("getLoggerRepository", (Class<?>[]) null)
-                        .invoke(null, (Object[]) null);
-
-                // Enumeration enumer = r.getCurrentLoggers();
-                Enumeration enumer = (Enumeration) r.getClass()
-                        .getMethod("getCurrentLoggers", (Class<?>[]) null)
-                        .invoke(r, (Object[]) null);
-
-                while (enumer.hasMoreElements()) {
-                    Object logger = enumer.nextElement();
-                    // hdm.addLoggerMBean(logger.getName());
-                    Object loggerName = logger.getClass()
-                            .getMethod("getName", (Class<?>[]) null)
-                            .invoke(logger, (Object[]) null);
-                    hdm.getClass().getMethod("addLoggerMBean", String.class)
-                            .invoke(hdm, loggerName);
-                }
-            } catch (Exception e) {
-                LOG.error("Problems while registering log4j jmx beans!", e);
-                throw new JMException(e.toString());
-            }
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/main/org/apache/zookeeper/jmx/ZKMBeanInfo.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/jmx/ZKMBeanInfo.java b/src/java/main/org/apache/zookeeper/jmx/ZKMBeanInfo.java
deleted file mode 100644
index 1e87d92..0000000
--- a/src/java/main/org/apache/zookeeper/jmx/ZKMBeanInfo.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper.jmx;
-
-/**
- * Zookeeper MBean info interface. MBeanRegistry uses the interface to generate
- * JMX object name.
- */
-public interface ZKMBeanInfo {
-    /**
-     * @return a string identifying the MBean 
-     */
-    public String getName();
-    /**
-     * If isHidden returns true, the MBean won't be registered with MBean server,
-     * and thus won't be available for management tools. Used for grouping MBeans.
-     * @return true if the MBean is hidden.
-     */
-    public boolean isHidden();
-}

http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/main/org/apache/zookeeper/server/ByteBufferInputStream.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/ByteBufferInputStream.java b/src/java/main/org/apache/zookeeper/server/ByteBufferInputStream.java
deleted file mode 100644
index 48d4a8d..0000000
--- a/src/java/main/org/apache/zookeeper/server/ByteBufferInputStream.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper.server;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.ByteBuffer;
-
-import org.apache.jute.BinaryInputArchive;
-import org.apache.jute.Record;
-
-public class ByteBufferInputStream extends InputStream {
-    ByteBuffer bb;
-
-    public ByteBufferInputStream(ByteBuffer bb) {
-        this.bb = bb;
-    }
-
-    @Override
-    public int read() throws IOException {
-        if (bb.remaining() == 0) {
-            return -1;
-        }
-        return bb.get() & 0xff;
-    }
-
-    @Override
-    public int available() throws IOException {
-        return bb.remaining();
-    }
-
-    @Override
-    public int read(byte[] b, int off, int len) throws IOException {
-        if (bb.remaining() == 0) {
-            return -1;
-        }
-        if (len > bb.remaining()) {
-            len = bb.remaining();
-        }
-        bb.get(b, off, len);
-        return len;
-    }
-
-    @Override
-    public int read(byte[] b) throws IOException {
-        return read(b, 0, b.length);
-    }
-
-    @Override
-    public long skip(long n) throws IOException {
-        if (n < 0L) {
-            return 0;
-        }
-        n = Math.min(n, bb.remaining());
-        bb.position(bb.position() + (int) n);
-        return n;
-    }
-
-    static public void byteBuffer2Record(ByteBuffer bb, Record record)
-            throws IOException {
-        BinaryInputArchive ia;
-        ia = BinaryInputArchive.getArchive(new ByteBufferInputStream(bb));
-        record.deserialize(ia, "request");
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/main/org/apache/zookeeper/server/ByteBufferOutputStream.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/ByteBufferOutputStream.java b/src/java/main/org/apache/zookeeper/server/ByteBufferOutputStream.java
deleted file mode 100644
index a1bdabd..0000000
--- a/src/java/main/org/apache/zookeeper/server/ByteBufferOutputStream.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper.server;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.nio.ByteBuffer;
-
-import org.apache.jute.BinaryOutputArchive;
-import org.apache.jute.Record;
-
-public class ByteBufferOutputStream extends OutputStream {
-    ByteBuffer bb;
-    public ByteBufferOutputStream(ByteBuffer bb) {
-        this.bb = bb;
-    }
-    @Override
-    public void write(int b) throws IOException {
-        bb.put((byte)b);
-    }
-    @Override
-    public void write(byte[] b) throws IOException {
-        bb.put(b);
-    }
-    @Override
-    public void write(byte[] b, int off, int len) throws IOException {
-        bb.put(b, off, len);
-    }
-    static public void record2ByteBuffer(Record record, ByteBuffer bb)
-    throws IOException {
-        BinaryOutputArchive oa;
-        oa = BinaryOutputArchive.getArchive(new ByteBufferOutputStream(bb));
-        record.serialize(oa, "request");
-    }
-}

http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/main/org/apache/zookeeper/server/ConnectionBean.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/ConnectionBean.java b/src/java/main/org/apache/zookeeper/server/ConnectionBean.java
deleted file mode 100644
index 58917e0..0000000
--- a/src/java/main/org/apache/zookeeper/server/ConnectionBean.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper.server;
-
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.util.Arrays;
-
-import javax.management.ObjectName;
-
-import org.apache.zookeeper.common.Time;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.zookeeper.jmx.MBeanRegistry;
-import org.apache.zookeeper.jmx.ZKMBeanInfo;
-
-/**
- * Implementation of connection MBean interface.
- */
-public class ConnectionBean implements ConnectionMXBean, ZKMBeanInfo {
-    private static final Logger LOG = LoggerFactory.getLogger(ConnectionBean.class);
-
-    private final ServerCnxn connection;
-    private final Stats stats;
-
-    private final ZooKeeperServer zk;
-    
-    private final String remoteIP;
-    private final long sessionId;
-
-    public ConnectionBean(ServerCnxn connection,ZooKeeperServer zk){
-        this.connection = connection;
-        this.stats = connection;
-        this.zk = zk;
-        
-        InetSocketAddress sockAddr = connection.getRemoteSocketAddress();
-        if (sockAddr == null) {
-            remoteIP = "Unknown";
-        } else {
-            InetAddress addr = sockAddr.getAddress();
-            if (addr instanceof Inet6Address) {
-                remoteIP = ObjectName.quote(addr.getHostAddress());
-            } else {
-                remoteIP = addr.getHostAddress();
-            }
-        }
-        sessionId = connection.getSessionId();
-    }
-    
-    public String getSessionId() {
-        return "0x" + Long.toHexString(sessionId);
-    }
-
-    public String getSourceIP() {
-        InetSocketAddress sockAddr = connection.getRemoteSocketAddress();
-        if (sockAddr == null) {
-            return null;
-        }
-        return sockAddr.getAddress().getHostAddress()
-            + ":" + sockAddr.getPort();
-    }
-
-    public String getName() {
-        return MBeanRegistry.getInstance().makeFullPath("Connections", remoteIP,
-                getSessionId());
-    }
-    
-    public boolean isHidden() {
-        return false;
-    }
-    
-    public String[] getEphemeralNodes() {
-        if(zk.getZKDatabase()  !=null){
-            String[] res = zk.getZKDatabase().getEphemerals(sessionId)
-                .toArray(new String[0]);
-            Arrays.sort(res);
-            return res;
-        }
-        return null;
-    }
-    
-    public String getStartedTime() {
-        return stats.getEstablished().toString();
-    }
-    
-    public void terminateSession() {
-        try {
-            zk.closeSession(sessionId);
-        } catch (Exception e) {
-            LOG.warn("Unable to closeSession() for session: 0x" 
-                    + getSessionId(), e);
-        }
-    }
-    
-    public void terminateConnection() {
-        connection.sendCloseSession();
-    }
-
-    public void resetCounters() {
-        stats.resetStats();
-    }
-
-    @Override
-    public String toString() {
-        return "ConnectionBean{ClientIP=" + ObjectName.quote(getSourceIP())
-            + ",SessionId=0x" + getSessionId() + "}";
-    }
-    
-    public long getOutstandingRequests() {
-        return stats.getOutstandingRequests();
-    }
-    
-    public long getPacketsReceived() {
-        return stats.getPacketsReceived();
-    }
-    
-    public long getPacketsSent() {
-        return stats.getPacketsSent();
-    }
-    
-    public int getSessionTimeout() {
-        return connection.getSessionTimeout();
-    }
-
-    public long getMinLatency() {
-        return stats.getMinLatency();
-    }
-
-    public long getAvgLatency() {
-        return stats.getAvgLatency();
-    }
-
-    public long getMaxLatency() {
-        return stats.getMaxLatency();
-    }
-    
-    public String getLastOperation() {
-        return stats.getLastOperation();
-    }
-
-    public String getLastCxid() {
-        return "0x" + Long.toHexString(stats.getLastCxid());
-    }
-
-    public String getLastZxid() {
-        return "0x" + Long.toHexString(stats.getLastZxid());
-    }
-
-    public String getLastResponseTime() {
-        return Time.elapsedTimeToDate(stats.getLastResponseTime()).toString();
-    }
-
-    public long getLastLatency() {
-        return stats.getLastLatency();
-    }
-}

http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/main/org/apache/zookeeper/server/ConnectionMXBean.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/ConnectionMXBean.java b/src/java/main/org/apache/zookeeper/server/ConnectionMXBean.java
deleted file mode 100644
index 8bdec9a..0000000
--- a/src/java/main/org/apache/zookeeper/server/ConnectionMXBean.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper.server;
-
-/**
- * This MBean represents a client connection.
- */
-public interface ConnectionMXBean {
-    /**
-     * @return source (client) IP address
-     */
-    public String getSourceIP();
-    /**
-     * @return client's session id
-     */
-    public String getSessionId();
-    /**
-     * @return time the connection was started
-     */
-    public String getStartedTime();
-    /**
-     * @return number of ephemeral nodes owned by this connection
-     */
-    public String[] getEphemeralNodes();
-    /**
-     * @return packets received from this client
-     */
-    public long getPacketsReceived();
-    /**
-     * @return number of packets sent to this client
-     */
-    public long getPacketsSent();
-    /**
-     * @return number of requets being processed
-     */
-    public long getOutstandingRequests();
-    /**
-     * @return session timeout in ms
-     */
-    public int getSessionTimeout();
-    
-    /**
-     * Terminate this client session. The client will reconnect with a different
-     * session id.
-     */
-    public void terminateSession();
-    /**
-     * Terminate thei client connection. The client will immediately attempt to 
-     * reconnect with the same session id.
-     */
-    public void terminateConnection();
-
-
-    /** Min latency in ms
-     * @since 3.3.0 */
-    long getMinLatency();
-    /** Average latency in ms
-     * @since 3.3.0 */
-    long getAvgLatency();
-    /** Max latency in ms
-     * @since 3.3.0 */
-    long getMaxLatency();
-    /** Last operation performed by this connection
-     * @since 3.3.0 */
-    String getLastOperation();
-    /** Last cxid of this connection
-     * @since 3.3.0 */
-    String getLastCxid();
-    /** Last zxid of this connection
-     * @since 3.3.0 */
-    String getLastZxid();
-    /** Last time server sent a response to client on this connection
-     * @since 3.3.0 */
-    String getLastResponseTime();
-    /** Latency of last response to client on this connection in ms
-     * @since 3.3.0 */
-    long getLastLatency();
-
-    /** Reset counters
-     * @since 3.3.0 */
-    void resetCounters();
-}

http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/main/org/apache/zookeeper/server/ContainerManager.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/ContainerManager.java b/src/java/main/org/apache/zookeeper/server/ContainerManager.java
deleted file mode 100644
index 2b41ac6..0000000
--- a/src/java/main/org/apache/zookeeper/server/ContainerManager.java
+++ /dev/null
@@ -1,178 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper.server;
-
-import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.common.Time;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.nio.ByteBuffer;
-import java.util.*;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
-
-/**
- * Manages cleanup of container ZNodes. This class is meant to only
- * be run from the leader. There's no harm in running from followers/observers
- * but that will be extra work that's not needed. Once started, it periodically
- * checks container nodes that have a cversion > 0 and have no children. A
- * delete is attempted on the node. The result of the delete is unimportant.
- * If the proposal fails or the container node is not empty there's no harm.
- */
-public class ContainerManager {
-    private static final Logger LOG = LoggerFactory.getLogger(ContainerManager.class);
-    private final ZKDatabase zkDb;
-    private final RequestProcessor requestProcessor;
-    private final int checkIntervalMs;
-    private final int maxPerMinute;
-    private final Timer timer;
-    private final AtomicReference<TimerTask> task = new AtomicReference<TimerTask>(null);
-
-    /**
-     * @param zkDb the ZK database
-     * @param requestProcessor request processer - used to inject delete
-     *                         container requests
-     * @param checkIntervalMs how often to check containers in milliseconds
-     * @param maxPerMinute the max containers to delete per second - avoids
-     *                     herding of container deletions
-     */
-    public ContainerManager(ZKDatabase zkDb, RequestProcessor requestProcessor,
-                            int checkIntervalMs, int maxPerMinute) {
-        this.zkDb = zkDb;
-        this.requestProcessor = requestProcessor;
-        this.checkIntervalMs = checkIntervalMs;
-        this.maxPerMinute = maxPerMinute;
-        timer = new Timer("ContainerManagerTask", true);
-
-        LOG.info(String.format("Using checkIntervalMs=%d maxPerMinute=%d",
-                checkIntervalMs, maxPerMinute));
-    }
-
-    /**
-     * start/restart the timer the runs the check. Can safely be called
-     * multiple times.
-     */
-    public void start() {
-        if (task.get() == null) {
-            TimerTask timerTask = new TimerTask() {
-                @Override
-                public void run() {
-                    try {
-                        checkContainers();
-                    } catch (InterruptedException e) {
-                        Thread.currentThread().interrupt();
-                        LOG.info("interrupted");
-                        cancel();
-                    } catch ( Throwable e ) {
-                        LOG.error("Error checking containers", e);
-                    }
-                }
-            };
-            if (task.compareAndSet(null, timerTask)) {
-                timer.scheduleAtFixedRate(timerTask, checkIntervalMs,
-                        checkIntervalMs);
-            }
-        }
-    }
-
-    /**
-     * stop the timer if necessary. Can safely be called multiple times.
-     */
-    public void stop() {
-        TimerTask timerTask = task.getAndSet(null);
-        if (timerTask != null) {
-            timerTask.cancel();
-        }
-        timer.cancel();
-    }
-
-    /**
-     * Manually check the containers. Not normally used directly
-     */
-    public void checkContainers()
-            throws InterruptedException {
-        long minIntervalMs = getMinIntervalMs();
-        for (String containerPath : getCandidates()) {
-            long startMs = Time.currentElapsedTime();
-
-            ByteBuffer path = ByteBuffer.wrap(containerPath.getBytes());
-            Request request = new Request(null, 0, 0,
-                    ZooDefs.OpCode.deleteContainer, path, null);
-            try {
-                LOG.info("Attempting to delete candidate container: {}",
-                        containerPath);
-                requestProcessor.processRequest(request);
-            } catch (Exception e) {
-                LOG.error("Could not delete container: {}",
-                        containerPath, e);
-            }
-
-            long elapsedMs = Time.currentElapsedTime() - startMs;
-            long waitMs = minIntervalMs - elapsedMs;
-            if (waitMs > 0) {
-                Thread.sleep(waitMs);
-            }
-        }
-    }
-
-    // VisibleForTesting
-    protected long getMinIntervalMs() {
-        return TimeUnit.MINUTES.toMillis(1) / maxPerMinute;
-    }
-
-    // VisibleForTesting
-    protected Collection<String> getCandidates() {
-        Set<String> candidates = new HashSet<String>();
-        for (String containerPath : zkDb.getDataTree().getContainers()) {
-            DataNode node = zkDb.getDataTree().getNode(containerPath);
-            /*
-                cversion > 0: keep newly created containers from being deleted
-                before any children have been added. If you were to create the
-                container just before a container cleaning period the container
-                would be immediately be deleted.
-             */
-            if ((node != null) && (node.stat.getCversion() > 0) &&
-                    (node.getChildren().size() == 0)) {
-                candidates.add(containerPath);
-            }
-        }
-        for (String ttlPath : zkDb.getDataTree().getTtls()) {
-            DataNode node = zkDb.getDataTree().getNode(ttlPath);
-            if (node != null) {
-                Set<String> children = node.getChildren();
-                if ((children == null) || (children.size() == 0)) {
-                    if ( EphemeralType.get(node.stat.getEphemeralOwner()) == EphemeralType.TTL ) {
-                        long elapsed = getElapsed(node);
-                        long ttl = EphemeralType.TTL.getValue(node.stat.getEphemeralOwner());
-                        if ((ttl != 0) && (getElapsed(node) > ttl)) {
-                            candidates.add(ttlPath);
-                        }
-                    }
-                }
-            }
-        }
-        return candidates;
-    }
-
-    // VisibleForTesting
-    protected long getElapsed(DataNode node) {
-        return Time.currentWallTime() - node.stat.getMtime();
-    }
-}

http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/main/org/apache/zookeeper/server/DataNode.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/DataNode.java b/src/java/main/org/apache/zookeeper/server/DataNode.java
deleted file mode 100644
index 0859aab..0000000
--- a/src/java/main/org/apache/zookeeper/server/DataNode.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper.server;
-
-import java.io.IOException;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.Collections;
-
-import org.apache.jute.InputArchive;
-import org.apache.jute.OutputArchive;
-import org.apache.jute.Record;
-import org.apache.zookeeper.data.Stat;
-import org.apache.zookeeper.data.StatPersisted;
-
-/**
- * This class contains the data for a node in the data tree.
- * <p>
- * A data node contains a reference to its parent, a byte array as its data, an
- * array of ACLs, a stat object, and a set of its children's paths.
- * 
- */
-public class DataNode implements Record {
-    /** the data for this datanode */
-    byte data[];
-
-    /**
-     * the acl map long for this datanode. the datatree has the map
-     */
-    Long acl;
-
-    /**
-     * the stat for this node that is persisted to disk.
-     */
-    public StatPersisted stat;
-
-    /**
-     * the list of children for this node. note that the list of children string
-     * does not contain the parent path -- just the last part of the path. This
-     * should be synchronized on except deserializing (for speed up issues).
-     */
-    private Set<String> children = null;
-
-    private static final Set<String> EMPTY_SET = Collections.emptySet();
-
-    /**
-     * default constructor for the datanode
-     */
-    DataNode() {
-        // default constructor
-    }
-
-    /**
-     * create a DataNode with parent, data, acls and stat
-     * 
-     * @param parent
-     *            the parent of this DataNode
-     * @param data
-     *            the data to be set
-     * @param acl
-     *            the acls for this node
-     * @param stat
-     *            the stat for this node.
-     */
-    public DataNode(byte data[], Long acl, StatPersisted stat) {
-        this.data = data;
-        this.acl = acl;
-        this.stat = stat;
-    }
-
-    /**
-     * Method that inserts a child into the children set
-     * 
-     * @param child
-     *            to be inserted
-     * @return true if this set did not already contain the specified element
-     */
-    public synchronized boolean addChild(String child) {
-        if (children == null) {
-            // let's be conservative on the typical number of children
-            children = new HashSet<String>(8);
-        }
-        return children.add(child);
-    }
-
-    /**
-     * Method that removes a child from the children set
-     * 
-     * @param child
-     * @return true if this set contained the specified element
-     */
-    public synchronized boolean removeChild(String child) {
-        if (children == null) {
-            return false;
-        }
-        return children.remove(child);
-    }
-
-    /**
-     * convenience method for setting the children for this datanode
-     * 
-     * @param children
-     */
-    public synchronized void setChildren(HashSet<String> children) {
-        this.children = children;
-    }
-
-    /**
-     * convenience methods to get the children
-     * 
-     * @return the children of this datanode. If the datanode has no children, empty
-     *         set is returned
-     */
-    public synchronized Set<String> getChildren() {
-        if (children == null) {
-            return EMPTY_SET;
-        }
-
-        return Collections.unmodifiableSet(children);
-    }
-
-    public synchronized long getApproximateDataSize() {
-        if(null==data) return 0;
-        return data.length;
-    }
-
-    synchronized public void copyStat(Stat to) {
-        to.setAversion(stat.getAversion());
-        to.setCtime(stat.getCtime());
-        to.setCzxid(stat.getCzxid());
-        to.setMtime(stat.getMtime());
-        to.setMzxid(stat.getMzxid());
-        to.setPzxid(stat.getPzxid());
-        to.setVersion(stat.getVersion());
-        to.setEphemeralOwner(getClientEphemeralOwner(stat));
-        to.setDataLength(data == null ? 0 : data.length);
-        int numChildren = 0;
-        if (this.children != null) {
-            numChildren = children.size();
-        }
-        // when we do the Cversion we need to translate from the count of the creates
-        // to the count of the changes (v3 semantics)
-        // for every create there is a delete except for the children still present
-        to.setCversion(stat.getCversion()*2 - numChildren);
-        to.setNumChildren(numChildren);
-    }
-
-    private static long getClientEphemeralOwner(StatPersisted stat) {
-        EphemeralType ephemeralType = EphemeralType.get(stat.getEphemeralOwner());
-        if (ephemeralType != EphemeralType.NORMAL) {
-            return 0;
-        }
-        return stat.getEphemeralOwner();
-    }
-
-    synchronized public void deserialize(InputArchive archive, String tag)
-            throws IOException {
-        archive.startRecord("node");
-        data = archive.readBuffer("data");
-        acl = archive.readLong("acl");
-        stat = new StatPersisted();
-        stat.deserialize(archive, "statpersisted");
-        archive.endRecord("node");
-    }
-
-    synchronized public void serialize(OutputArchive archive, String tag)
-            throws IOException {
-        archive.startRecord(this, "node");
-        archive.writeBuffer(data, "data");
-        archive.writeLong(acl, "acl");
-        stat.serialize(archive, "statpersisted");
-        archive.endRecord(this, "node");
-    }
-}


Mime
View raw message