<commit_before>// ReplicaSetStatus.java

/**
 *      Copyright (C) 2008 10gen 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.mongodb;

import com.mongodb.util.JSON;
import org.bson.util.annotations.Immutable;
import org.bson.util.annotations.ThreadSafe;

import java.net.UnknownHostException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;

// TODO:
//  pull config to get
//  priority
//  slave delay

/**
 * Keeps replica set status.  Maintains a background thread to ping all members of the set to keep the status current.
 */
@ThreadSafe
public class ReplicaSetStatus {

	static final Logger _rootLogger = Logger.getLogger( "com.mongodb.ReplicaSetStatus" );

    ReplicaSetStatus( Mongo mongo, List<ServerAddress> initial ){
        _mongoOptions = _mongoOptionsDefaults.copy();
        _mongoOptions.socketFactory = mongo._options.socketFactory;
        _mongo = mongo;
        _updater = new Updater(initial);
    }

    void start() {
        _updater.start();
    }

    public String getName() {
        return _setName.get();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{replSetName: ").append(_setName.get());
        sb.append(", nextResolveTime: ").append(new Date(_updater.getNextResolveTime()).toString());
        sb.append(", all : ").append(_replicaSetHolder);

        return sb.toString();
    }

    void _checkClosed(){
        if ( _closed )
            throw new IllegalStateException( "ReplicaSetStatus closed" );
    }

    /**
     * @return master or null if don't have one
     */
    public ServerAddress getMaster(){
        Node n = getMasterNode();
        if ( n == null )
            return null;
        return n.getServerAddress();
    }

    Node getMasterNode(){
        _checkClosed();
        return _replicaSetHolder.get().getMaster();
    }

	/**
	 * @param srv
	 *            the server to compare
	 * @return indication if the ServerAddress is the current Master/Primary
	 */
	public boolean isMaster(ServerAddress srv) {
		if (srv == null)
			return false;

		return srv.equals(getMaster());
	}

    /**
     * @param tags tags map
     * @return a good secondary by tag value or null if can't find one
     */
    ServerAddress getASecondary( DBObject tags ) {
        // store the reference in local, so that it doesn't change out from under us while looping
        List<Tag> tagList = new ArrayList<Tag>();
        for ( String key : tags.keySet() ) {
            tagList.add(new Tag(key, tags.get(key).toString()));
        }
        Node node =  _replicaSetHolder.get().getASecondary(tagList);
        if (node != null) {
            return node.getServerAddress();
        }
        return null;
    }

    /**
     * @return a good secondary or null if can't find one
     */
    ServerAddress getASecondary() {
        Node node = _replicaSetHolder.get().getASecondary();
        if (node == null) {
            return null;
        }
        return node._addr;
    }

    boolean hasServerUp() {
        for (Node node : _replicaSetHolder.get().getAll()) {
            if (node.isOk()) {
                return true;
            }
        }
        return false;
    }
    
    // Simple abstraction over a volatile ReplicaSet reference that starts as null.  The get method blocks until members
    // is not null. The set method notifies all, thus waking up all getters.
    @ThreadSafe
    static class ReplicaSetHolder {
       private volatile ReplicaSet members;

       // blocks until replica set is set.
       synchronized ReplicaSet get() {
           while (members == null) {
               try {
                   wait();
               }
               catch (InterruptedException e) {
                   throw new MongoException("Interrupted while waiting for next update to replica set status", e);
               }
           }
           return members;
       }

       // set the replica set to a non-null value and notifies all threads waiting.
       synchronized void set(ReplicaSet members) {
           if (members == null) {
               throw new IllegalArgumentException("members can not be null");
           }
           this.members = members;
           notifyAll();
       }

       // blocks until the replica set is set again
       synchronized void waitForNextUpdate() {
           try {
               wait();
           } 
           catch (InterruptedException e) {
              throw new MongoException("Interrupted while waiting for next update to replica set status", e);
           }
       }

        public synchronized void close() {
            this.members = null;
            notifyAll();
        }
    }

    // Immutable snapshot state of a replica set. Since the nodes don't change state, this class pre-computes the list
    // of good secondaries so that choosing a random good secondary is dead simple
    @Immutable
    static class ReplicaSet {
        final List<Node> all;
        final Random random;
        final List<Node> goodSecondaries;
        final Map<Tag, List<Node>> goodSecondariesByTagMap;
        final Node master;

        public ReplicaSet(List<Node> nodeList, Random random, int acceptableLatencyMS) {
            this.random = random;
            this.all = Collections.unmodifiableList(new ArrayList<Node>(nodeList));
            this.goodSecondaries =
                    Collections.unmodifiableList(calculateGoodSecondaries(all, calculateBestPingTime(all), acceptableLatencyMS));
            Set<Tag> uniqueTags = new HashSet<Tag>();
            for (Node curNode : all) {
                for (Tag curTag : curNode._tags) {
                    uniqueTags.add(curTag);<commit_msg>JAVA-458: Fixed regression in ReplicaSetStatus.toString()<commit_after>// ReplicaSetStatus.java

/**
 *      Copyright (C) 2008 10gen 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.mongodb;

import com.mongodb.util.JSON;
import org.bson.util.annotations.Immutable;
import org.bson.util.annotations.ThreadSafe;

import java.net.UnknownHostException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;

// TODO:
//  pull config to get
//  priority
//  slave delay

/**
 * Keeps replica set status.  Maintains a background thread to ping all members of the set to keep the status current.
 */
@ThreadSafe
public class ReplicaSetStatus {

	static final Logger _rootLogger = Logger.getLogger( "com.mongodb.ReplicaSetStatus" );

    ReplicaSetStatus( Mongo mongo, List<ServerAddress> initial ){
        _mongoOptions = _mongoOptionsDefaults.copy();
        _mongoOptions.socketFactory = mongo._options.socketFactory;
        _mongo = mongo;
        _updater = new Updater(initial);
    }

    void start() {
        _updater.start();
    }

    public String getName() {
        return _setName.get();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{replSetName: ").append(_setName.get());
        sb.append(", nextResolveTime: ").append(new Date(_updater.getNextResolveTime()).toString());
        sb.append(", members: ").append(_replicaSetHolder);

        return sb.toString();
    }

    void _checkClosed(){
        if ( _closed )
            throw new IllegalStateException( "ReplicaSetStatus closed" );
    }

    /**
     * @return master or null if don't have one
     */
    public ServerAddress getMaster(){
        Node n = getMasterNode();
        if ( n == null )
            return null;
        return n.getServerAddress();
    }

    Node getMasterNode(){
        _checkClosed();
        return _replicaSetHolder.get().getMaster();
    }

	/**
	 * @param srv
	 *            the server to compare
	 * @return indication if the ServerAddress is the current Master/Primary
	 */
	public boolean isMaster(ServerAddress srv) {
		if (srv == null)
			return false;

		return srv.equals(getMaster());
	}

    /**
     * @param tags tags map
     * @return a good secondary by tag value or null if can't find one
     */
    ServerAddress getASecondary( DBObject tags ) {
        // store the reference in local, so that it doesn't change out from under us while looping
        List<Tag> tagList = new ArrayList<Tag>();
        for ( String key : tags.keySet() ) {
            tagList.add(new Tag(key, tags.get(key).toString()));
        }
        Node node =  _replicaSetHolder.get().getASecondary(tagList);
        if (node != null) {
            return node.getServerAddress();
        }
        return null;
    }

    /**
     * @return a good secondary or null if can't find one
     */
    ServerAddress getASecondary() {
        Node node = _replicaSetHolder.get().getASecondary();
        if (node == null) {
            return null;
        }
        return node._addr;
    }

    boolean hasServerUp() {
        for (Node node : _replicaSetHolder.get().getAll()) {
            if (node.isOk()) {
                return true;
            }
        }
        return false;
    }
    
    // Simple abstraction over a volatile ReplicaSet reference that starts as null.  The get method blocks until members
    // is not null. The set method notifies all, thus waking up all getters.
    @ThreadSafe
    static class ReplicaSetHolder {
       private volatile ReplicaSet members;

       // blocks until replica set is set.
       synchronized ReplicaSet get() {
           while (members == null) {
               try {
                   wait();
               }
               catch (InterruptedException e) {
                   throw new MongoException("Interrupted while waiting for next update to replica set status", e);
               }
           }
           return members;
       }

       // set the replica set to a non-null value and notifies all threads waiting.
       synchronized void set(ReplicaSet members) {
           if (members == null) {
               throw new IllegalArgumentException("members can not be null");
           }
           this.members = members;
           notifyAll();
       }

       // blocks until the replica set is set again
       synchronized void waitForNextUpdate() {
           try {
               wait();
           } 
           catch (InterruptedException e) {
              throw new MongoException("Interrupted while waiting for next update to replica set status", e);
           }
       }

        public synchronized void close() {
            this.members = null;
            notifyAll();
        }
        
        public String toString() {
            ReplicaSet cur = this.members;
            if (cur != null) {
                return cur.toString();
            }
            return "none";
        }
    }

    // Immutable snapshot state of a replica set. Since the nodes don't change state, this class pre-computes the list
    // of good secondaries so that choosing a random good secondary is dead simple
    @Immutable
    static class ReplicaSet {
        final List<Node> all;
        final Random random;
        final List<Node> goodSecondaries;
        final Map<Tag, List<Node>> goodSecondariesByTagMap;
        final Node master;

        public ReplicaSet(List<Node> nodeList, Random random, int acceptableLatencyMS) {
            this.random = random;
            this.all = Collections.unmodifiableList(new ArrayList<Node>(nodeList));
            this.goodSecondaries =
                    Collections.unmodifiableList(calculateGoodSecondaries(all, calculateBestPingTime(all), acceptableLatencyMS));
            Set<Tag> uniqueTags = new HashSet<Tag>();
            for (Node curNode : all) {
                for (Tag curTag : curNode._tags) {
                    uniqueTags.add(curTag);
{'fraction_non_alphanumeric': 0.09170439720666104, 'fraction_numerical': 0.0017650218709231833, 'mean_word_length': 2.1708029197080294, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6190833', 'n_tokens_mistral': 3511, 'n_tokens_neox': 3461, 'n_words': 1122}