see if port is using by supervisor
if used return true, if not, add this port to registry and return false

@param supervisorHost
@param slotCount
@return
550185
public List<String> getSetPortUsedBySupervisor(String supervisorHost, int slotCount) throws Exception {

        String appPath = RegistryUtils.serviceclassPath(
                JOYConstants.APP_TYPE, JOYConstants.EMPTY);

        String path = RegistryUtils.serviceclassPath(
                JOYConstants.APP_TYPE, instanceName);

        String containerPath = RegistryUtils.componentPath(
                JOYConstants.APP_TYPE, instanceName, containerId.getApplicationAttemptId().getApplicationId().toString(), containerId.toString());

        List<String> reList = new ArrayList<String>();
        try {

            List<ServiceRecord> hostContainers = new ArrayList<ServiceRecord>();
            Set<String> hostUsedPorts = new HashSet<String>();


            List<String> instanceNames = registryOperations.list(appPath);
            for (String instance : instanceNames) {

                String servicePath = RegistryUtils.serviceclassPath(
                        JOYConstants.APP_TYPE, instance);

                List<String> apps = registryOperations.list(servicePath);

                for (String subapp : apps) {

                    String subAppPath = RegistryUtils.servicePath(
                            JOYConstants.APP_TYPE, instance, subapp);
                    String componentsPath = subAppPath + JOYConstants.COMPONENTS;
                    if (!registryOperations.exists(componentsPath))
                        continue;
                    Map<String, ServiceRecord> containers = RegistryUtils.listServiceRecords(registryOperations, componentsPath);

                    for (String container : containers.keySet()) {
                        ServiceRecord sr = containers.get(container);
                        LOG.info(sr.toString());

                        if (!sr.get(JOYConstants.HOST).equals(supervisorHost))
                            continue;
                        hostContainers.add(sr);
                        String[] portList = new String[]{};
                        if (sr.get(JOYConstants.PORT_LIST) != null)
                            portList = sr.get(JOYConstants.PORT_LIST).split(JOYConstants.COMMA);
                        for (String usedport : portList) {
                            hostUsedPorts.add(usedport);
                        }
                    }
                }
            }

            //scan port range from 9000 to 15000
            for (int i = getMinPort(); i < getMaxPort(); i++) {
                if (JstormYarnUtils.isPortAvailable(supervisorHost, i)) {
                    if (!hostUsedPorts.contains(String.valueOf(i)))
                        reList.add(String.valueOf(i));
                }
                if (reList.size() >= slotCount) {
                    break;
                }
            }


            if (registryOperations.exists(containerPath)) {
                ServiceRecord sr = registryOperations.resolve(containerPath);
                String portListUpdate = JstormYarnUtils.join(reList, JOYConstants.COMMA, false);
                if (sr.get(JOYConstants.PORT_LIST) != null) {
                    String[] portList = sr.get(JOYConstants.PORT_LIST).split(JOYConstants.COMMA);
                    portListUpdate = JstormYarnUtils.join(portList, JOYConstants.COMMA, true) + JstormYarnUtils.join(reList, JOYConstants.COMMA, false);
                }
                sr.set(JOYConstants.PORT_LIST, portListUpdate);
                registryOperations.bind(containerPath, sr, BindFlags.OVERWRITE);
            } else {
                registryOperations.mknode(containerPath, true);
                ServiceRecord sr = new ServiceRecord();
                sr.set(JOYConstants.HOST, supervisorHost);
                String portListUpdate = JstormYarnUtils.join(reList, JOYConstants.COMMA, false);
                sr.set(JOYConstants.PORT_LIST, portListUpdate);
                sr.set(YarnRegistryAttributes.YARN_ID, containerId.toString());
                sr.description = JOYConstants.CONTAINER;
                sr.set(YarnRegistryAttributes.YARN_PERSISTENCE,
                        PersistencePolicies.CONTAINER);
                registryOperations.bind(containerPath, sr, BindFlags.OVERWRITE);
            }
            return reList;
        } catch (Exception ex) {
            LOG.error(ex);
            throw ex;
        }
    }
1057133
public static boolean makePPDDecision(int thisHostId, Set<Integer> previousHosts, Set<Integer> currentHosts, boolean pdEnabled) {

        String logLine = String.format("Partition Detection at host %d code sees current hosts [%s] and previous hosts [%s]",
                thisHostId,
                StringUtils.join(currentHosts, ','),
                StringUtils.join(previousHosts, ','));
        tmLog.info(logLine);

        // A strict, viable minority is always a partition.
        if ((currentHosts.size() * 2) < previousHosts.size()) {
            if (pdEnabled) {
                tmLog.fatal("It's possible a network partition has split the cluster into multiple viable clusters. "
                        + "Current cluster contains fewer than half of the previous servers. "
                        + "Shutting down to avoid multiple copies of the database running independently.");
                return true; // partition detection triggered
            }
            else {
                tmLog.warn("It's possible a network partition has split the cluster into multiple viable clusters. "
                        + "Current cluster contains fewer than half of the previous servers. "
                        + "Continuing because network partition detection is disabled, but there "
                        + "is significant danger that multiple copies of the database are running "
                        + "independently.");
                return false; // partition detection not triggered
            }
        }

        // Exact 50-50 splits. The set with the lowest survivor host doesn't trigger PPD
        // If the blessed host is in the failure set, this set is not blessed.
        if (currentHosts.size() * 2 == previousHosts.size()) {
            if (pdEnabled) {
                // find the lowest hostId between the still-alive hosts and the
                // failed hosts. Which set contains the lowest hostId?
                // This should be all the pre-partition hosts IDs.  Any new host IDs
                // (say, if this was triggered by rejoin), will be greater than any surviving
                // host ID, so don't worry about including it in this search.
                if (currentHosts.contains(Collections.min(previousHosts))) {
                    tmLog.info("It's possible a network partition has split the cluster into multiple viable clusters. "
                            + "Current cluster contains half of the previous servers, "
                            + "including the \"tie-breaker\" node. Continuing.");
                    return false; // partition detection not triggered
                }
                else {
                    tmLog.fatal("It's possible a network partition has split the cluster into multiple viable clusters. "
                            + "Current cluster contains exactly half of the previous servers, but does "
                            + "not include the \"tie-breaker\" node. "
                            + "Shutting down to avoid multiple copies of the database running independently.");
                    return true; // partition detection triggered
                }
            }
            else {
                // 50/50 split. We don't care about tie-breakers for this error message
                tmLog.warn("It's possible a network partition has split the cluster into multiple viable clusters. "
                        + "Current cluster contains exactly half of the previous servers. "
                        + "Continuing because network partition detection is disabled, "
                        + "but there is significant danger that multiple copies of the "
                        + "database are running independently.");
                return false; // partition detection not triggered
            }
        }

        // info message will be printed on every failure that isn't handled above (most cases)
        tmLog.info("It's possible a network partition has split the cluster into multiple viable clusters. "
                + "Current cluster contains a majority of the prevous servers and is safe. Continuing.");
        return false; // partition detection not triggered
    }
1140433
public static boolean portAvailable(int port) {
        if (port < MIN_PORT || port > MAX_PORT) {
            throw new InvalidArgument("port is out of range");
        }

        ServerSocket ss = null;
        DatagramSocket ds = null;
        try {
            ss = new ServerSocket(port);
            ss.setReuseAddress(true);
            ds = new DatagramSocket(port);
            ds.setReuseAddress(true);
            return true;
        } catch (IOException e) {
            // Do nothing
        } finally {
            if (ds != null) {
                ds.close();
            }

            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    /* should not be thrown */
                }
            }
        }

        return false;
    }
417199
@Override
	public CompletableFuture<Acknowledge> requestSlot(
		final SlotID slotId,
		final JobID jobId,
		final AllocationID allocationId,
		final String targetAddress,
		final ResourceManagerId resourceManagerId,
		final Time timeout) {
		// TODO: Filter invalid requests from the resource manager by using the instance/registration Id

		log.info("Receive slot request {} for job {} from resource manager with leader id {}.",
			allocationId, jobId, resourceManagerId);

		try {
			if (!isConnectedToResourceManager(resourceManagerId)) {
				final String message = String.format("TaskManager is not connected to the resource manager %s.", resourceManagerId);
				log.debug(message);
				throw new TaskManagerException(message);
			}

			if (taskSlotTable.isSlotFree(slotId.getSlotNumber())) {
				if (taskSlotTable.allocateSlot(slotId.getSlotNumber(), jobId, allocationId, taskManagerConfiguration.getTimeout())) {
					log.info("Allocated slot for {}.", allocationId);
				} else {
					log.info("Could not allocate slot for {}.", allocationId);
					throw new SlotAllocationException("Could not allocate slot.");
				}
			} else if (!taskSlotTable.isAllocated(slotId.getSlotNumber(), jobId, allocationId)) {
				final String message = "The slot " + slotId + " has already been allocated for a different job.";

				log.info(message);

				final AllocationID allocationID = taskSlotTable.getCurrentAllocation(slotId.getSlotNumber());
				throw new SlotOccupiedException(message, allocationID, taskSlotTable.getOwningJob(allocationID));
			}

			if (jobManagerTable.contains(jobId)) {
				offerSlotsToJobManager(jobId);
			} else {
				try {
					jobLeaderService.addJob(jobId, targetAddress);
				} catch (Exception e) {
					// free the allocated slot
					try {
						taskSlotTable.freeSlot(allocationId);
					} catch (SlotNotFoundException slotNotFoundException) {
						// slot no longer existent, this should actually never happen, because we've
						// just allocated the slot. So let's fail hard in this case!
						onFatalError(slotNotFoundException);
					}

					// release local state under the allocation id.
					localStateStoresManager.releaseLocalStateForAllocationId(allocationId);

					// sanity check
					if (!taskSlotTable.isSlotFree(slotId.getSlotNumber())) {
						onFatalError(new Exception("Could not free slot " + slotId));
					}

					throw new SlotAllocationException("Could not add job to job leader service.", e);
				}
			}
		} catch (TaskManagerException taskManagerException) {
			return FutureUtils.completedExceptionally(taskManagerException);
		}

		return CompletableFuture.completedFuture(Acknowledge.get());
	}
877818
private boolean isProcessTriggerOnly(final ComponentWithContext triggerWithContext,
			final AjaxOperation operation) {

		// Target container implies only process the trigger or is Internal Ajax
		if (operation.getTargetContainerId() != null || operation.isInternalAjaxRequest()) {
			return true;
		}

		WComponent trigger = triggerWithContext.getComponent();

		// Check if trigger is a polling AJAX control
		if (trigger instanceof WAjaxControl) {
			// Get user context
			UIContext uic = triggerWithContext.getContext();
			UIContextHolder.pushContext(uic);
			try {
				WAjaxControl ajax = (WAjaxControl) trigger;
				// Is a polling region so only process trigger
				if (ajax.getDelay() > 0) {
					return true;
				}
			} finally {
				UIContextHolder.popContext();
			}
		}

		return false;
	}
1112372
private boolean validateServer(String host, int port){
        if(host==null || host.isEmpty()){
            return false;
        }
        if(port <=0 || port > 65535){
            return false;
        }
        return true;
    }
1096860
public String getWorkerGcParameter(LocalAssignment assignment,
                                       Map totalConf,
                                       String topologyId,
                                       Integer port) {

        StringBuilder commandSB = new StringBuilder();
        GcStrategy gcStrategy = GcStrategyManager.getGcStrategy(totalConf);
        return gcStrategy.toString();
    }
854704
protected boolean isAvailable(final NetworkPort port) {

        int portNumber = port.getPortNumber();

        try {
            try (ServerSocket tcp = new ServerSocket(portNumber);
                 DatagramSocket udp = new DatagramSocket(portNumber)) {
                return tcp.isBound() && udp.isBound();
            }
        } catch (IOException e) { //NOSONAR
            LOG.debug("Port {} not available", port.getSocketAddress(), e);
            return false;
        }
    }
534522
private boolean isWorkAvailable() throws SIConnectionDroppedException {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "isWorkAvailable");
      final boolean isWork;
      if (terminate) {
         isWork = false;
      } else {
         isWork = (partiallySentTransmission != null) || !priorityQueue.isEmpty();
      }
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "isWorkAvailable", Boolean.valueOf(isWork));
      return isWork;
   }
346799
public static boolean isServiceExported(Configuration configuration, int port, String serviceName) {
        if (serviceName == null)
            return false;
        try {
            final Registry registry = RegistryFinder.getInstance().getRegistry(configuration, port);
            String[] list = registry.list();

            if (list != null) {
                for (int i = 0; i < list.length; i++) {
                    if (serviceName.equals(list[i]))
                        return true;
                }
            }
        } catch (RemoteException ex) {
            return false;
        } catch (Exception e) {
            return false;
        }
        return false;
    }
596195
private static boolean isAvailable(int thePort) {
		ourLog.info("Testing a bind on thePort {}", thePort);
		try (ServerSocket ss = new ServerSocket()) {
			ss.setReuseAddress(true);
			ss.bind(new InetSocketAddress("0.0.0.0", thePort));
			try (DatagramSocket ds = new DatagramSocket()) {
				ds.setReuseAddress(true);
				ds.connect(new InetSocketAddress("127.0.0.1", thePort));
				ourLog.info("Successfully bound thePort {}", thePort);
			} catch (IOException e) {
				ourLog.info("Failed to bind thePort {}: {}", thePort, e.toString());
				return false;
			}
		} catch (IOException e) {
			ourLog.info("Failed to bind thePort {}: {}", thePort, e.toString());
			return false;
		}

		try (ServerSocket ss = new ServerSocket()) {
			ss.setReuseAddress(true);
			ss.bind(new InetSocketAddress("localhost", thePort));
		} catch (IOException e) {
			ourLog.info("Failed to bind thePort {}: {}", thePort, e.toString());
			return false;
		}

		return true;
	}
956863
public int getConnectionsActive(SocketDestination destination) {
        if(destination == null) {
            return pool.getTotalResourceCount();
        } else {
            return pool.getTotalResourceCount(destination);
        }
    }
1340166
public static Cluster connectCluster(String host, int port) {
	Builder clusterBuilder = Cluster.builder();
	// Socket Options
	SocketOptions socketOptions = new SocketOptions();
	socketOptions.setConnectTimeoutMillis(60000);
	socketOptions.setKeepAlive(true);
	socketOptions.setReadTimeoutMillis(30000);
	return clusterBuilder.addContactPoint(host)
		.withSocketOptions(socketOptions).withPort(port).build();
    }
183441
private static boolean isSameNodeAndServer(ObjectName mName) {
        String processName = mName.getKeyProperty("process");
        String nodeName = mName.getKeyProperty("node");

        if (tc.isDebugEnabled())
            Tr.debug(tc, "isSameNodeAndServer: " + mName.toString());

        if (processName != null && !processName.equals(PmiRegistry.serverName)) {
            // print only when debug is enabled since customers get worried seeing this message
            if (tc.isDebugEnabled())
                Tr.warning(tc, "PMI0002W", mName.toString() + ", expected process name is " + PmiRegistry.serverName);
            return false;
        }
        if (nodeName != null && !nodeName.equals(PmiRegistry.nodeName)) {
            // print only when debug is enabled since customers get worried seeing this message
            if (tc.isDebugEnabled())
                Tr.warning(tc, "PMI0002W", mName.toString() + ", expected node name is " + PmiRegistry.nodeName);
            return false;
        }

        return true;
    }
181727
private boolean isAddToLoadBalancerSuspended(AutoScalingGroup asg) {
        List<SuspendedProcess> suspendedProcesses = asg.getSuspendedProcesses();
        for (SuspendedProcess process : suspendedProcesses) {
            if (PROP_ADD_TO_LOAD_BALANCER.equals(process.getProcessName())) {
                return true;
            }
        }
        return false;
    }
776769
public static boolean isPortAvailable(int port) {
        StringBuilder builder = new StringBuilder();
        builder.append("Testing port ").append(port).append("\n");
        try (Socket s = new Socket("localhost", port)) {
            // If the code makes it this far without an exception it means
            // something is using the port and has responded.
            builder.append("Port ").append(port).append(" is not available").append("\n");
            return false;
        } catch (IOException e) {
            builder.append("Port ").append(port).append(" is available").append("\n");
            return true;
        } finally {
            log.fine(builder.toString());
        }
    }
668015
public boolean hasSlotIsNumber(final String slotName) {
        return hasSlot(slotName) && NumberUtils.isNumber(intentRequest.getIntent().getSlot(slotName).getValue());
    }