Bootstraps the map to attempt to get in sync with existing instances of the same map on other nodes in the cluster.
This is necessary to ensure that a read immediately after the map is created doesn't return a null value.
518217
private void bootstrap() {
    List<MemberId> activePeers = bootstrapPeersSupplier.get();
    if (activePeers.isEmpty()) {
      return;
    }
    try {
      requestBootstrapFromPeers(activePeers)
          .get(DistributedPrimitive.DEFAULT_OPERATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    } catch (ExecutionException | InterruptedException | TimeoutException e) {
      LOGGER.debug("Failed to bootstrap ec map {}: {}", mapName, ExceptionUtils.getStackTrace(e));
    }
  }
904390
@Override
    public void initUsed(boolean used, VanillaChronicleMap map) {
        assert used;
        firstContextLockedInThisThread = rootContextInThisThread.lockContextLocally(map);
        initMap(map);
        this.used = true;
    }
472450
public static <K,V> Map<K,V> asSynchronized(Map<K,V> self) {
        return Collections.synchronizedMap(self);
    }
397893
public function bootstrapMage2()
    {
        if (is_null($this->bootstrap)) {
            $bootstrap = Bootstrap::create(BP, $_SERVER);
            $bootstrap->getObjectManager();
            $this->bootstrap = true;
        }
    }
1102867
private void initializeMapper() {
    if (valueClass == null) {
      valueMapper = CatchAllMapper.getInstance();
    } else {
      try {
        valueMapper = MapperFactory.getInstance().getMapper(valueClass);
      } catch (NoSuitableMapperException exp) {
        valueMapper = CatchAllMapper.getInstance();
      }

    }
  }
1277210
private void initialClustering() {
		//System.out.println("INITIAL CLUSTERING CALLED");
		//printDStreamState();
		// 1. Update the density of all grids in grid_list

		updateGridListDensity();
		//printGridList();
				
		// 2. Assign each dense grid to a distinct cluster
		// and
		// 3. Label all other grids as NO_CLASS	
		Iterator<Map.Entry<DensityGrid, CharacteristicVector>> glIter = this.grid_list.entrySet().iterator();
		HashMap<DensityGrid, CharacteristicVector> newGL = new HashMap<DensityGrid, CharacteristicVector>();
		
		while(glIter.hasNext())
		{
			Map.Entry<DensityGrid, CharacteristicVector> grid = glIter.next();
			DensityGrid dg = grid.getKey();
			CharacteristicVector cvOfG = grid.getValue();

			//System.out.print(dg.toString());
			if(cvOfG.getAttribute() == DENSE)
			{
				int gridClass = this.cluster_list.size();
				cvOfG.setLabel(gridClass);
				GridCluster gc = new GridCluster ((CFCluster)dg, new ArrayList<CFCluster>(), gridClass);
				gc.addGrid(dg);
				this.cluster_list.add(gc);
				//System.out.print(" was dense (class "+gridClass+")");
			}
			else
				cvOfG.setLabel(NO_CLASS);

			//System.out.println();
			newGL.put(dg, cvOfG);
		}

		this.grid_list = newGL;
		//printGridClusters();
		
		// 4. Make changes to grid labels by doing:
		//    a. For each cluster c
		//    b. For each outside grid g of c
		//    c. For each neighbouring grid h of g
		//    d. If h belongs to c', label c and c' with 
		//       the label of the largest cluster
		//    e. Else if h is transitional, assign it to c
		//    f. While changes can be made

		boolean changesMade;

		do{	
			changesMade = adjustLabels();
		}while(changesMade);	// while changes are being made
		
		//printGridList();
		//printGridClusters();
	}
266886
protected boolean _load ()
    {
        java.sql.ResultSet rs = null;
        try
        {
            // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1
            // The documentation says synchronization is done within the driver, but they
            // must have overlooked something. Without the lock we'd get mysterious error
            // messages.            
            synchronized(getDbMeta())
            {
                getDbMetaTreeModel().setStatusBarMessage("Reading columns for table " + getSchema().getCatalog().getCatalogName() + "." + getSchema().getSchemaName() + "." + getTableName());
                rs = getDbMeta().getColumns(getSchema().getCatalog().getCatalogName(), 
                                                          getSchema().getSchemaName(),
                                                          getTableName(), "%");
                final java.util.ArrayList alNew = new java.util.ArrayList();
                while (rs.next())
                {
                    alNew.add(new DBMetaColumnNode(getDbMeta(), getDbMetaTreeModel(), DBMetaTableNode.this, rs.getString("COLUMN_NAME")));
                }
                alChildren = alNew;            
                javax.swing.SwingUtilities.invokeLater(new Runnable()
                {
                    public void run()
                    {
                        getDbMetaTreeModel().nodeStructureChanged(DBMetaTableNode.this);
                    }
                });
                rs.close();
            }
        }
        catch (java.sql.SQLException sqlEx)
        {
            this.getDbMetaTreeModel().reportSqlError("Error retrieving columns", sqlEx);
            try
            {
                if (rs != null) rs.close ();
            }
            catch (java.sql.SQLException sqlEx2)
            {
                this.getDbMetaTreeModel().reportSqlError("Error retrieving columns", sqlEx2);
            }
            return false;
        }
        return true;
    }
134415
public static <K,V> SortedMap<K,V> asSynchronized(SortedMap<K,V> self) {
        return Collections.synchronizedSortedMap(self);
    }
1207990
private void join(Iterator<MemberState> iterator) {
    if (iterator.hasNext()) {
      cancelJoinTimer();
      joinTimeout = context.getThreadContext().schedule(context.getElectionTimeout().multipliedBy(2), () -> {
        join(iterator);
      });

      MemberState member = iterator.next();
      LOGGER.debug("{} - Attempting to join via {}", member().address(), member.getMember().serverAddress());

      context.getConnections().getConnection(member.getMember().serverAddress()).thenCompose(connection -> {
        JoinRequest request = JoinRequest.builder()
          .withMember(new ServerMember(member().type(), member().serverAddress(), member().clientAddress(), member().updated()))
          .build();
        return connection.<JoinRequest, JoinResponse>sendAndReceive(request);
      }).whenComplete((response, error) -> {
        // Cancel the join timer.
        cancelJoinTimer();

        if (error == null) {
          if (response.status() == Response.Status.OK) {
            LOGGER.info("{} - Successfully joined via {}", member().address(), member.getMember().serverAddress());

            Configuration configuration = new Configuration(response.index(), response.term(), response.timestamp(), response.members());

            // Configure the cluster with the join response.
            // Commit the configuration as we know it was committed via the successful join response.
            configure(configuration).commit();

            // If the local member is not present in the configuration, fail the future.
            if (!members.contains(this.member)) {
              joinFuture.completeExceptionally(new IllegalStateException("not a member of the cluster"));
            } else if (joinFuture != null) {
              joinFuture.complete(null);
            }
          } else if (response.error() == null || response.error() == CopycatError.Type.CONFIGURATION_ERROR) {
            // If the response error is null, that indicates that no error occurred but the leader was
            // in a state that was incapable of handling the join request. Attempt to join the leader
            // again after an election timeout.
            LOGGER.debug("{} - Failed to join {}", member().address(), member.getMember().address());
            resetJoinTimer();
          } else {
            // If the response error was non-null, attempt to join via the next server in the members list.
            LOGGER.debug("{} - Failed to join {}", member().address(), member.getMember().address());
            join(iterator);
          }
        } else {
          LOGGER.debug("{} - Failed to join {}", member().address(), member.getMember().address());
          join(iterator);
        }
      });
    }
    // If join attempts remain, schedule another attempt after two election timeouts. This allows enough time
    // for servers to potentially timeout and elect a leader.
    else {
      LOGGER.debug("{} - Failed to join cluster, retrying...", member.address());
      resetJoinTimer();
    }
  }
807404
@SuppressWarnings("unchecked")
    private void doRefreshTopologies() {
        for (String topology : JStormMetrics.SYS_TOPOLOGIES) {
            if (!context.getTopologyMetricContexts().containsKey(topology)) {
                LOG.info("adding {} to metric context.", topology);
                Map conf = new HashMap();
                if (topology.equals(JStormMetrics.CLUSTER_METRIC_KEY)) {
                    //there's no need to consider sample rate when cluster metrics merge
                    conf.put(ConfigExtension.TOPOLOGY_METRIC_SAMPLE_RATE, 1.0);
                }
                Set<ResourceWorkerSlot> workerSlot = Sets.newHashSet(new ResourceWorkerSlot());
                TopologyMetricContext metricContext = new TopologyMetricContext(topology, workerSlot, conf);
                context.getTopologyMetricContexts().putIfAbsent(topology, metricContext);
                syncMetaFromCache(topology, context.getTopologyMetricContexts().get(topology));
            }

            // in the first 10 min, sync every 1 min
            if (context.getNimbusData().uptime() < INIT_SYNC_REMOTE_META_TIME_SEC) {
                syncMetaFromRemote(topology, context.getTopologyMetricContexts().get(topology),
                        Lists.newArrayList(MetaType.TOPOLOGY, MetaType.WORKER, MetaType.NIMBUS));
            } else { // after that, sync every 5 min
                checkTimeAndSyncMetaFromRemote(topology, context.getTopologyMetricContexts().get(topology),
                        Lists.newArrayList(MetaType.values()));

            }
        }

        Map<String, Assignment> assignMap;
        try {
            assignMap = Cluster.get_all_assignment(context.getStormClusterState(), null);
            for (Entry<String, Assignment> entry : assignMap.entrySet()) {
                String topology = entry.getKey();
                Assignment assignment = entry.getValue();

                TopologyMetricContext metricContext = context.getTopologyMetricContexts().get(topology);
                if (metricContext == null) {
                    metricContext = new TopologyMetricContext(assignment.getWorkers());
                    metricContext.setTaskNum(NimbusUtils.getTopologyTaskNum(assignment));
                    syncMetaFromCache(topology, metricContext);

                    LOG.info("adding {} to metric context.", topology);
                    context.getTopologyMetricContexts().put(topology, metricContext);
                } else {
                    boolean modify = false;
                    if (metricContext.getTaskNum() != NimbusUtils.getTopologyTaskNum(assignment)) {
                        modify = true;
                        metricContext.setTaskNum(NimbusUtils.getTopologyTaskNum(assignment));
                    }

                    if (!assignment.getWorkers().equals(metricContext.getWorkerSet())) {
                        modify = true;
                        metricContext.setWorkerSet(assignment.getWorkers());
                    }

                    // for normal topologies, only sync topology/component level metrics
                    checkTimeAndSyncMetaFromRemote(topology, metricContext,
                            Lists.newArrayList(MetaType.TOPOLOGY, MetaType.COMPONENT));

                    // we may need to sync meta when task num/workers change
                    metricContext.setSyncMeta(!modify);
                }
            }
        } catch (Exception e1) {
            LOG.warn("Failed to get assignments");
            return;
        }

        List<String> removing = new ArrayList<>();
        for (String topology : context.getTopologyMetricContexts().keySet()) {
            if (!JStormMetrics.SYS_TOPOLOGY_SET.contains(topology) && !assignMap.containsKey(topology)) {
                removing.add(topology);
            }
        }

        for (String topology : removing) {
            LOG.info("removing topology:{}", topology);
            RemoveTopologyEvent.pushEvent(topology);
            syncRemoteTimes.remove(topology);
        }
    }
469736
def _create_sync_map(self, sync_root):
        
        sync_map = SyncMap(tree=sync_root, rconf=self.rconf, logger=self.logger)
        if self.rconf.safety_checks:
            self.log(u"Running sanity check on computed sync map...")
            if not sync_map.leaves_are_consistent:
                self._step_failure(ValueError(u"The computed sync map contains inconsistent fragments"))
            self.log(u"Running sanity check on computed sync map... passed")
        else:
            self.log(u"Not running sanity check on computed sync map")
        self.task.sync_map = sync_map
204462
def setup(self):
        
        # Get the existing mapping & cache it. We'll compare it
        # during the ``update`` & if it doesn't match, we'll put the new
        # mapping.
        for language in self.languages:
            self.index_name = self._index_name_for_language(language)
            try:
                self.existing_mapping[language] = self.conn.indices.get_mapping(
                    index=self.index_name)
            except NotFoundError:
                pass
            except Exception:
                if not self.silently_fail:
                    raise

            unified_index = haystack.connections[self.connection_alias].get_unified_index()

            self.content_field_name, field_mapping = self.build_schema(
                unified_index.all_searchfields(), language)

            current_mapping = {
                'modelresult': {
                    'properties': field_mapping,
                    '_boost': {
                        'name': 'boost',
                        'null_value': 1.0
                    }
                }
            }

            if current_mapping != self.existing_mapping[language]:
                try:
                    # Make sure the index is there first.
                    self.conn.indices.create(
                        index=self.index_name,
                        body=self.DEFAULT_SETTINGS,
                        ignore=400)
                    self.conn.indices.put_mapping(
                        index=self.index_name,
                        doc_type='modelresult',
                        body=current_mapping
                    )
                    self.existing_mapping[language] = current_mapping
                except Exception:
                    if not self.silently_fail:
                        raise

        self.setup_complete = True
720354
@SuppressWarnings("unchecked")
    protected void initialise() {
        if (getBean() == null) {
            return;
        }

        this.beanClass = (Class<T>) bean.getClass();
        if (!(getBean() instanceof Map)) {
            Class currentClass = beanClass;

            List<Class> classes = Lists.newLinkedList();

            while (currentClass != null) {
                classes.add(0, currentClass);
                currentClass = currentClass.getSuperclass();
            }

            for (Class clazz : classes) {
                for (Method m : clazz.getMethods()) {
                    String name = m.getName();
                    Class rtype = m.getReturnType();
                    if (void.class != rtype && !name.equals("getClass")) {
                        boolean getType = name.startsWith(HandleType.GET.name().toLowerCase());
                        boolean isType = false;
                        if (!getType) {
                            isType = name.startsWith(HandleType.IS.name().toLowerCase())
                                    && (Boolean.class.isAssignableFrom(rtype) || rtype == boolean.class);
                        }
                        if (getType || isType) {
                            String fn = transformPropertyName(StringUtils.uncapitalize(name.substring(isType ? 2 : 3)));
                            if (StringUtils.isNotBlank(fn)) {
                                types.put(fn, rtype);
                                readHandleType.put(fn, isType ? HandleType.IS : HandleType.GET);
                            }
                        }
                    }
                }
            }
        } else {
            if (getBean() instanceof BeanMap) {
                types = ((BeanMap) getBean()).types;
                readInvokers = ((BeanMap) getBean()).readInvokers;
                writeInvokers = ((BeanMap) getBean()).writeInvokers;
                beanClass = (Class<T>) bean.getClass();
                bean = (T) ((BeanMap) bean).getBean();
            } else {
                Set<Map.Entry> entries = ((Map) getBean()).entrySet();
                for (Map.Entry entry : entries) {
                    String name = transformPropertyName((String) entry.getKey());
                    if (StringUtils.isNotBlank(name) && entry.getValue() != null) {
                        types.put(name, entry.getValue().getClass());
                    }
                }
            }
        }
    }
126459
void initInputsByIdMap() {
    inputsById.clear();
    for (CompilerInput input : externs) {
      InputId id = input.getInputId();
      CompilerInput previous = putCompilerInput(id, input);
      if (previous != null) {
        report(JSError.make(DUPLICATE_EXTERN_INPUT, input.getName()));
      }
    }
    for (CompilerInput input : moduleGraph.getAllInputs()) {
      InputId id = input.getInputId();
      CompilerInput previous = putCompilerInput(id, input);
      if (previous != null) {
        report(JSError.make(DUPLICATE_INPUT, input.getName()));
      }
    }
  }
801024
@Api
	public void refresh() {
		if (state == State.INITIALIZED) { // to prevent refresh before the map is drawn
			state = State.REFRESHING;
			clear();
			ClientConfigurationService.clear(); // refresh because configuration changed, clear cache
			refreshFromConfiguration();
		}
	}
449246
void beginSynchronizing() throws IOException {
    // Synchronization is performed in other threads.
    Zxid lastZxid = persistence.getLatestZxid();
    ClusterConfiguration clusterConfig = persistence.getLastSeenConfig();
    long proposedEpoch = persistence.getProposedEpoch();
    for (PeerHandler ph : this.quorumMap.values()) {
      ph.setSyncTask(new SyncPeerTask(ph.getServerId(), ph.getLastZxid(),
                                      lastZxid, clusterConfig),
                     proposedEpoch);
      ph.startSynchronizingTask();
    }
  }
1248104
@SuppressWarnings({"unchecked", "rawtypes"})
    private void populateMap(Map map, Node node) {
        Map.Entry entry = getMapEntry(node);
        if (entry != null) {
            map.put(entry.getKey(), entry.getValue());
        }
    }