Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   *      Copyright (C) 2012 DataStax Inc.
   *
   *   Licensed under the Apache License, Version 2.0 (the "License");
   *   you may not use this file except in compliance with the License.
   *   You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  *   Unless required by applicable law or agreed to in writing, software
  *   distributed under the License is distributed on an "AS IS" BASIS,
  *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  *   See the License for the specific language governing permissions and
  *   limitations under the License.
  */
 package com.datastax.driver.core;
 
 import java.util.*;
 
Keeps metadata on the connected cluster, including known nodes and schema definitions.
 
 public class Metadata {
 
     private static final Logger logger = LoggerFactory.getLogger(Metadata.class);
 
     private final Cluster.Manager cluster;
     volatile String clusterName;
     volatile String partitioner;
     private final ConcurrentMap<InetAddressHosthosts = new ConcurrentHashMap<InetAddressHost>();
 
     @SuppressWarnings({"unchecked""rawtypes"})
     private volatile TokenMap<? extends TokentokenMap;
 
     Metadata(Cluster.Manager cluster) {
         this. = cluster;
     }
 
     // Synchronized to make it easy to detect dropped keyspaces
     synchronized void rebuildSchema(String keyspaceString tableResultSet ksResultSet cfsResultSet cols) {
 
         Map<StringList<Row>> cfDefs = new HashMap<StringList<Row>>();
         Map<StringMap<StringList<Row>>> colsDefs = new HashMap<StringMap<StringList<Row>>>();
 
         // Gather cf defs
         for (Row row : cfs) {
             String ksName = row.getString(.);
             List<Rowl = cfDefs.get(ksName);
             if (l == null) {
                 l = new ArrayList<Row>();
                 cfDefs.put(ksNamel);
             }
             l.add(row);
         }
 
         // Gather columns per Cf
         for (Row row : cols) {
             String ksName = row.getString(.);
             String cfName = row.getString(.);
             Map<StringList<Row>> colsByCf = colsDefs.get(ksName);
             if (colsByCf == null) {
                 colsByCf = new HashMap<StringList<Row>>();
                 colsDefs.put(ksNamecolsByCf);
             }
             List<Rowl = colsByCf.get(cfName);
             if (l == null) {
                 l = new ArrayList<Row>();
                 colsByCf.put(cfNamel);
             }
             l.add(row);
         }
 
         if (table == null) {
             assert ks != null;
             Set<StringaddedKs = new HashSet<String>();
             for (Row ksRow : ks) {
                 String ksName = ksRow.getString(.);
                 KeyspaceMetadata ksm = KeyspaceMetadata.build(ksRow);
 
                 if (cfDefs.containsKey(ksName)) {
                     buildTableMetadata(ksmcfDefs.get(ksName), colsDefs.get(ksName));
                 }
                 addedKs.add(ksName);
                 .put(ksNameksm);
             }
 
             // If keyspace is null, it means we're rebuilding from scratch, so
             // remove anything that was not just added as it means it's a dropped keyspace
             if (keyspace == null) {
                 Iterator<Stringiter = .keySet().iterator();
                 while (iter.hasNext()) {
                    if (!addedKs.contains(iter.next()))
                        iter.remove();
                }
            }
        } else {
            assert keyspace != null;
            KeyspaceMetadata ksm = .get(keyspace);
            // If we update a keyspace we don't know about, something went
            // wrong. Log an error an schedule a full schema rebuilt.
            if (ksm == null) {
                .error(String.format("Asked to rebuild table %s.%s but I don't know keyspace %s"keyspacetablekeyspace));
                .submitSchemaRefresh(nullnull);
                return;
            }
            if (cfDefs.containsKey(keyspace))
                buildTableMetadata(ksmcfDefs.get(keyspace), colsDefs.get(keyspace));
        }
    }
    private static void buildTableMetadata(KeyspaceMetadata ksmList<RowcfRowsMap<StringList<Row>> colsDefs) {
        boolean hasColumns = (colsDefs != null) && !colsDefs.isEmpty();
        for (Row cfRow : cfRows) {
            String cfName = cfRow.getString(.);
            TableMetadata tm = TableMetadata.build(ksmcfRowhasColumns);
            if (!hasColumns || colsDefs.get(cfName) == null)
                continue;
            for (Row colRow : colsDefs.get(cfName)) {
                ColumnMetadata.build(tmcolRow);
            }
        }
    }
    @SuppressWarnings("unchecked")
    synchronized void rebuildTokenMap(String partitionerMap<HostCollection<String>> allTokens) {
        if (!allTokens.isEmpty())
            this. = TokenMap.build(partitionerallTokens);
    }
    Host add(InetAddress address) {
        Host newHost = new Host(address.);
        Host previous = .putIfAbsent(addressnewHost);
        return previous == null ? newHost : null;
    }
    boolean remove(Host host) {
        return .remove(host.getAddress()) != null;
    }
    Host getHost(InetAddress address) {
        return .get(address);
    }
    // For internal use only
    Collection<HostallHosts() {
        return .values();
    }

    
Returns the set of hosts that are replica for a given partition key.

Note that this method is a best effort method. Consumers should not rely too heavily on the result of this method not being stale (or even empty).

Parameters:
partitionKey the partition key for which to find the set of replica.
Returns:
the (immutable) set of replicas for partitionKey as know by the driver. No strong guarantee is provided on the stalelessness of this information. It is also not guarantee that the returned set won't be empty (which is then some form of staleness).
    @SuppressWarnings({"unchecked""rawtypes"})
    public Set<HostgetReplicas(ByteBuffer partitionKey) {
        TokenMap current = ;
        if (current == null) {
            return Collections.emptySet();
        } else {
            return current.getReplicas(current.factory.hash(partitionKey));
        }
    }

    
The Cassandra name for the cluster connect to.

Returns:
the Cassandra name for the cluster connect to.
    public String getClusterName() {
        return ;
    }

    
The partitioner in use as reported by the Cassandra nodes.

Returns:
the partitioner in use as reported by the Cassandra nodes.
    public String getPartitioner() {
        return ;
    }

    
Returns the known hosts of this cluster.

Returns:
A set will all the know host of this cluster.
    public Set<HostgetAllHosts() {
        return new HashSet<Host>(allHosts());
    }

    
Returns the metadata of a keyspace given its name.

Parameters:
keyspace the name of the keyspace for which metadata should be returned.
Returns:
the metadata of the requested keyspace or null if keyspace is not a known keyspace.
    public KeyspaceMetadata getKeyspace(String keyspace) {
        return .get(keyspace);
    }

    
Returns a list of all the defined keyspaces.

Returns:
a list of all the defined keyspaces.
    public List<KeyspaceMetadatagetKeyspaces() {
        return new ArrayList<KeyspaceMetadata>(.values());
    }

    
Returns a String containing CQL queries representing the schema of this cluster. In other words, this method returns the queries that would allow to recreate the schema of this cluster. Note that the returned String is formatted to be human readable (for some definition of human readable at least).

Returns:
the CQL queries representing this cluster schema as a {code String}.
    public String exportSchemaAsString() {
        StringBuilder sb = new StringBuilder();
        for (KeyspaceMetadata ksm : .values())
            sb.append(ksm.exportAsString()).append("\n");
        return sb.toString();
    }
    static class TokenMap<T extends Token<T>> {
        private final Token.Factory<T> factory;
        private final Map<T, Set<Host>> tokenToHosts;
        private final List<T> ring;
        private TokenMap(Token.Factory<T> factoryMap<T, Set<Host>> tokenToHostsList<T> ring) {
            this. = factory;
            this. = tokenToHosts;
            this. = ring;
        }
        public static <T extends Token<T>> TokenMap<T> build(String partitionerMap<HostCollection<String>> allTokens) {
            @SuppressWarnings("unchecked")
            Token.Factory<T> factory = (Token.Factory<T>)Token.getFactory(partitioner);
            if (factory == null)
                return null;
            Map<T, Set<Host>> tokenToHosts = new HashMap<T, Set<Host>>();
            Set<T> allSorted = new TreeSet<T>();
            for (Map.Entry<HostCollection<String>> entry : allTokens.entrySet()) {
                Host host = entry.getKey();
                for (String tokenStr : entry.getValue()) {
                    try {
                        T t = factory.fromString(tokenStr);
                        allSorted.add(t);
                        Set<Hosthosts = tokenToHosts.get(t);
                        if (hosts == null) {
                            hosts = new HashSet<Host>();
                            tokenToHosts.put(thosts);
                        }
                        hosts.add(host);
                    } catch (IllegalArgumentException e) {
                        // If we failed parsing that token, skip it
                    }
                }
            }
            // Make all the inet set immutable so we can share them publicly safely
            for (Map.Entry<T, Set<Host>> entrytokenToHosts.entrySet()) {
                entry.setValue(Collections.unmodifiableSet(entry.getValue()));
            }
            return new TokenMap<T>(factorytokenToHostsnew ArrayList<T>(allSorted));
        }
        private Set<HostgetReplicas(T token) {
            // Find the primary replica
            int i = Collections.binarySearch(token);
            if (i < 0) {
                i = (i + 1) * (-1);
                if (i >= .size())
                    i = 0;
            }
            return .get(.get(i));
        }
    }
New to GrepCode? Check out our FAQ X