com.velocitypowered.api.proxy.server.RegisteredServer Java Examples

The following examples show how to use com.velocitypowered.api.proxy.server.RegisteredServer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OnlineForwardPluginMessagingForwardingSource.java    From NuVotifier with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void forward(Vote v) {
    Optional<Player> p = plugin.getServer().getPlayer(v.getUsername());
    Optional<ServerConnection> sc = p.flatMap(Player::getCurrentServer);
    if (sc.isPresent() &&
            serverFilter.isAllowed(sc.get().getServerInfo().getName())
    ) {
        if (forwardSpecific(new VelocityBackendServer(plugin.getServer(), sc.get().getServer()), v)) {
            if (plugin.isDebug()) {
                plugin.getPluginLogger().info("Successfully forwarded vote " + v + " to server " + sc.get().getServerInfo().getName());
            }
            return;
        }
    }

    Optional<RegisteredServer> fs = plugin.getServer().getServer(fallbackServer);
    // nowhere to fall back to, yet still not online. lets save this vote yet!
    if (!fs.isPresent())
        attemptToAddToPlayerCache(v, v.getUsername());
    else if (!forwardSpecific(new VelocityBackendServer(plugin.getServer(), fs.get()), v))
        attemptToAddToCache(v, fallbackServer);
}
 
Example #2
Source File: GlistCommand.java    From Velocity with MIT License 6 votes vote down vote up
private void sendServerPlayers(CommandSource target, RegisteredServer server, boolean fromAll) {
  List<Player> onServer = ImmutableList.copyOf(server.getPlayersConnected());
  if (onServer.isEmpty() && fromAll) {
    return;
  }

  TextComponent.Builder builder = TextComponent.builder()
      .append(TextComponent.of("[" + server.getServerInfo().getName() + "] ",
          TextColor.DARK_AQUA))
      .append("(" + onServer.size() + ")", TextColor.GRAY)
      .append(": ")
      .resetStyle();

  for (int i = 0; i < onServer.size(); i++) {
    Player player = onServer.get(i);
    builder.append(player.getUsername());

    if (i + 1 < onServer.size()) {
      builder.append(", ");
    }
  }

  target.sendMessage(builder.build());
}
 
Example #3
Source File: ProtocolDetectorService.java    From ViaVersion with MIT License 6 votes vote down vote up
public static void probeServer(final RegisteredServer serverInfo) {
    final String key = serverInfo.getServerInfo().getName();
    serverInfo.ping().thenAccept((serverPing) -> {
        if (serverPing != null && serverPing.getVersion() != null) {
            detectedProtocolIds.put(key, serverPing.getVersion().getProtocol());
            if (((VelocityViaConfig) Via.getConfig()).isVelocityPingSave()) {
                Map<String, Integer> servers = ((VelocityViaConfig) Via.getConfig()).getVelocityServerProtocols();
                Integer protocol = servers.get(key);
                if (protocol != null && protocol == serverPing.getVersion().getProtocol()) {
                    return;
                }
                // Ensure we're the only ones writing to the config
                synchronized (Via.getPlatform().getConfigurationProvider()) {
                    servers.put(key, serverPing.getVersion().getProtocol());
                }
                // Save
                Via.getPlatform().getConfigurationProvider().saveConfig();
            }
        }
    });
}
 
Example #4
Source File: ConnectedPlayer.java    From Velocity with MIT License 6 votes vote down vote up
/**
 * Finds another server to attempt to log into, if we were unexpectedly disconnected from the
 * server.
 *
 * @param current the "current" server that the player is on, useful as an override
 *
 * @return the next server to try
 */
private Optional<RegisteredServer> getNextServerToTry(@Nullable RegisteredServer current) {
  if (serversToTry == null) {
    String virtualHostStr = getVirtualHost().map(InetSocketAddress::getHostString).orElse("");
    serversToTry = server.getConfiguration().getForcedHosts().getOrDefault(virtualHostStr,
        Collections.emptyList());
  }

  if (serversToTry.isEmpty()) {
    serversToTry = server.getConfiguration().getAttemptConnectionOrder();
  }

  for (int i = tryIndex; i < serversToTry.size(); i++) {
    String toTryName = serversToTry.get(i);
    if ((connectedServer != null && hasSameName(connectedServer.getServer(), toTryName))
        || (connectionInFlight != null && hasSameName(connectionInFlight.getServer(), toTryName))
        || (current != null && hasSameName(current, toTryName))) {
      continue;
    }

    tryIndex = i;
    return server.getServer(toTryName);
  }
  return Optional.empty();
}
 
Example #5
Source File: GlistCommand.java    From Velocity with MIT License 6 votes vote down vote up
@Override
public List<String> suggest(CommandSource source, String @NonNull [] currentArgs) {
  ImmutableList.Builder<String> options = ImmutableList.builder();
  for (RegisteredServer server : server.getAllServers()) {
    options.add(server.getServerInfo().getName());
  }
  options.add("all");

  switch (currentArgs.length) {
    case 0:
      return options.build();
    case 1:
      return options.build().stream()
          .filter(o -> o.regionMatches(true, 0, currentArgs[0], 0, currentArgs[0].length()))
          .collect(ImmutableList.toImmutableList());
    default:
      return ImmutableList.of();
  }
}
 
Example #6
Source File: ServerMap.java    From Velocity with MIT License 6 votes vote down vote up
/**
 * Registers a server with the proxy.
 *
 * @param serverInfo the server to register
 * @return the registered server
 */
public RegisteredServer register(ServerInfo serverInfo) {
  Preconditions.checkNotNull(serverInfo, "serverInfo");
  String lowerName = serverInfo.getName().toLowerCase(Locale.US);
  VelocityRegisteredServer rs = new VelocityRegisteredServer(server, serverInfo);

  RegisteredServer existing = servers.putIfAbsent(lowerName, rs);
  if (existing != null && !existing.getServerInfo().equals(serverInfo)) {
    throw new IllegalArgumentException(
        "Server with name " + serverInfo.getName() + " already registered");
  } else if (existing == null) {
    return rs;
  } else {
    return existing;
  }
}
 
Example #7
Source File: VelocityServer.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public Collection<RegisteredServer> matchServer(String partialName) {
  Objects.requireNonNull(partialName);

  return getAllServers().stream().filter(s -> s.getServerInfo().getName()
          .regionMatches(true, 0, partialName, 0, partialName.length()))
          .collect(Collectors.toList());
}
 
Example #8
Source File: KickedFromServerEvent.java    From Velocity with MIT License 5 votes vote down vote up
/**
 * Creates a {@code KickedFromServerEvent} instance.
 * @param player the player affected
 * @param server the server the player disconnected from
 * @param originalReason the reason for being kicked, optional
 * @param duringServerConnect whether or not the player was kicked during the connection process
 * @param result the initial result
 */
public KickedFromServerEvent(Player player,
    RegisteredServer server,
    @Nullable Component originalReason, boolean duringServerConnect,
    ServerKickResult result) {
  this.player = Preconditions.checkNotNull(player, "player");
  this.server = Preconditions.checkNotNull(server, "server");
  this.originalReason = originalReason;
  this.duringServerConnect = duringServerConnect;
  this.result = Preconditions.checkNotNull(result, "result");
}
 
Example #9
Source File: KickedFromServerEvent.java    From Velocity with MIT License 5 votes vote down vote up
/**
 * Creates a {@code KickedFromServerEvent} instance.
 * @param player the player affected
 * @param server the server the player disconnected from
 * @param originalReason the reason for being kicked, optional
 * @param duringServerConnect whether or not the player was kicked during the connection process
 * @param fancyReason a fancy reason for being disconnected, used for the initial result
 */
public KickedFromServerEvent(Player player, RegisteredServer server,
    @Nullable Component originalReason, boolean duringServerConnect, Component fancyReason) {
  this.player = Preconditions.checkNotNull(player, "player");
  this.server = Preconditions.checkNotNull(server, "server");
  this.originalReason = originalReason;
  this.duringServerConnect = duringServerConnect;
  this.result = new Notify(fancyReason);
}
 
Example #10
Source File: VelocityPlugin.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Integer getOnlinePlayers(String location) {
    Optional<RegisteredServer> server = proxy.getServer(location);
    if (!server.isPresent()) {
        return null;
    }

    return server.get().getPlayersConnected().size();
}
 
Example #11
Source File: BackendServerCalculator.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public ContextSet estimatePotentialContexts() {
    Collection<RegisteredServer> servers = this.plugin.getBootstrap().getProxy().getAllServers();
    ImmutableContextSet.Builder builder = new ImmutableContextSetImpl.BuilderImpl();
    for (RegisteredServer server : servers) {
        builder.add(DefaultContextKeys.WORLD_KEY, server.getServerInfo().getName().toLowerCase());
    }
    return builder.build();
}
 
Example #12
Source File: ServerMapTest.java    From Velocity with MIT License 5 votes vote down vote up
@Test
void allowsSameServerLaxRegistrationCheck() {
  ServerMap map = new ServerMap(null);
  ServerInfo info = new ServerInfo("TestServer", TEST_ADDRESS);
  RegisteredServer connection = map.register(info);
  assertEquals(connection, map.register(info));
}
 
Example #13
Source File: ServerMapTest.java    From Velocity with MIT License 5 votes vote down vote up
@Test
void respectsCaseInsensitivity() {
  ServerMap map = new ServerMap(null);
  ServerInfo info = new ServerInfo("TestServer", TEST_ADDRESS);
  RegisteredServer connection = map.register(info);

  assertEquals(Optional.of(connection), map.getServer("TestServer"));
  assertEquals(Optional.of(connection), map.getServer("testserver"));
  assertEquals(Optional.of(connection), map.getServer("TESTSERVER"));
}
 
Example #14
Source File: ConnectedPlayer.java    From Velocity with MIT License 5 votes vote down vote up
/**
 * Handles unexpected disconnects.
 * @param server the server we disconnected from
 * @param throwable the exception
 * @param safe whether or not we can safely reconnect to a new server
 */
public void handleConnectionException(RegisteredServer server, Throwable throwable,
    boolean safe) {
  if (!isActive()) {
    // If the connection is no longer active, it makes no sense to try and recover it.
    return;
  }

  if (throwable == null) {
    throw new NullPointerException("throwable");
  }

  Throwable wrapped = throwable;
  if (throwable instanceof CompletionException) {
    Throwable cause = throwable.getCause();
    if (cause != null) {
      wrapped = cause;
    }
  }
  String userMessage;
  if (connectedServer != null && connectedServer.getServerInfo().equals(server.getServerInfo())) {
    userMessage = "Your connection to " + server.getServerInfo().getName() + " encountered an "
        + "error.";
  } else {
    logger.error("{}: unable to connect to server {}", this, server.getServerInfo().getName(),
        wrapped);
    userMessage = "Unable to connect to " + server.getServerInfo().getName() + ". Try again "
        + "later.";
  }
  handleConnectionException(server, null, TextComponent.of(userMessage, TextColor.RED), safe);
}
 
Example #15
Source File: ConnectedPlayer.java    From Velocity with MIT License 5 votes vote down vote up
/**
 * Handles unexpected disconnects.
 * @param server the server we disconnected from
 * @param disconnect the disconnect packet
 * @param safe whether or not we can safely reconnect to a new server
 */
public void handleConnectionException(RegisteredServer server, Disconnect disconnect,
    boolean safe) {
  if (!isActive()) {
    // If the connection is no longer active, it makes no sense to try and recover it.
    return;
  }

  Component disconnectReason = GsonComponentSerializer.INSTANCE.deserialize(
      disconnect.getReason());
  String plainTextReason = PASS_THRU_TRANSLATE.serialize(disconnectReason);
  if (connectedServer != null && connectedServer.getServerInfo().equals(server.getServerInfo())) {
    logger.error("{}: kicked from server {}: {}", this, server.getServerInfo().getName(),
        plainTextReason);
    handleConnectionException(server, disconnectReason, TextComponent.builder()
        .content("Kicked from " + server.getServerInfo().getName() + ": ")
        .color(TextColor.RED)
        .append(disconnectReason)
        .build(), safe);
  } else {
    logger.error("{}: disconnected while connecting to {}: {}", this,
        server.getServerInfo().getName(), plainTextReason);
    handleConnectionException(server, disconnectReason, TextComponent.builder()
        .content("Can't connect to server " + server.getServerInfo().getName() + ": ")
        .color(TextColor.RED)
        .append(disconnectReason)
        .build(), safe);
  }
}
 
Example #16
Source File: Main.java    From TAB with Apache License 2.0 5 votes vote down vote up
@Override
public void suggestPlaceholders() {
	//bungee only
	suggestPlaceholderSwitch("%premiumvanish_bungeeplayercount%", "%canseeonline%");
	suggestPlaceholderSwitch("%bungee_total%", "%online%");
	for (RegisteredServer server : server.getAllServers()) {
		suggestPlaceholderSwitch("%bungee_" + server.getServerInfo().getName() + "%", "%online_" + server.getServerInfo().getName() + "%");
	}

	//both
	suggestPlaceholderSwitch("%player_ping%", "%ping%");
	suggestPlaceholderSwitch("%viaversion_player_protocol_version%", "%player-version%");
	suggestPlaceholderSwitch("%player_name%", "%nick%");
}
 
Example #17
Source File: ServerMap.java    From Velocity with MIT License 5 votes vote down vote up
/**
 * Unregisters the specified server from the proxy.
 *
 * @param serverInfo the server to unregister
 */
public void unregister(ServerInfo serverInfo) {
  Preconditions.checkNotNull(serverInfo, "serverInfo");
  String lowerName = serverInfo.getName().toLowerCase(Locale.US);
  RegisteredServer rs = servers.get(lowerName);
  if (rs == null) {
    throw new IllegalArgumentException(
        "Server with name " + serverInfo.getName() + " is not registered!");
  }
  Preconditions.checkArgument(rs.getServerInfo().equals(serverInfo),
      "Trying to remove server %s with differing information", serverInfo.getName());
  Preconditions.checkState(servers.remove(lowerName, rs),
      "Server with name %s replaced whilst unregistering", serverInfo.getName());
}
 
Example #18
Source File: ConnectedPlayer.java    From Velocity with MIT License 5 votes vote down vote up
private Optional<ConnectionRequestBuilder.Status> checkServer(RegisteredServer server) {
  Preconditions
      .checkState(server instanceof VelocityRegisteredServer, "Not a valid Velocity server.");
  if (connectionInFlight != null || (connectedServer != null
      && !connectedServer.hasCompletedJoin())) {
    return Optional.of(ConnectionRequestBuilder.Status.CONNECTION_IN_PROGRESS);
  }
  if (connectedServer != null && connectedServer.getServer().equals(server)) {
    return Optional.of(ConnectionRequestBuilder.Status.ALREADY_CONNECTED);
  }
  return Optional.empty();
}
 
Example #19
Source File: ConnectedPlayer.java    From Velocity with MIT License 5 votes vote down vote up
private CompletableFuture<Impl> internalConnect() {
  Optional<ConnectionRequestBuilder.Status> initialCheck = checkServer(toConnect);
  if (initialCheck.isPresent()) {
    return CompletableFuture
        .completedFuture(ConnectionRequestResults.plainResult(initialCheck.get(), toConnect));
  }

  // Otherwise, initiate the connection.
  ServerPreConnectEvent event = new ServerPreConnectEvent(ConnectedPlayer.this, toConnect);
  return server.getEventManager().fire(event)
      .thenCompose(newEvent -> {
        Optional<RegisteredServer> connectTo = newEvent.getResult().getServer();
        if (!connectTo.isPresent()) {
          return CompletableFuture.completedFuture(
              ConnectionRequestResults
                  .plainResult(ConnectionRequestBuilder.Status.CONNECTION_CANCELLED, toConnect)
          );
        }

        RegisteredServer rs = connectTo.get();
        Optional<ConnectionRequestBuilder.Status> lastCheck = checkServer(rs);
        if (lastCheck.isPresent()) {
          return CompletableFuture
              .completedFuture(ConnectionRequestResults.plainResult(lastCheck.get(), rs));
        }

        VelocityRegisteredServer vrs = (VelocityRegisteredServer) rs;
        VelocityServerConnection con = new VelocityServerConnection(vrs, ConnectedPlayer.this,
            server);
        connectionInFlight = con;
        return con.connect();
      });
}
 
Example #20
Source File: GlistCommand.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void execute(CommandSource source, String @NonNull [] args) {
  if (args.length == 0) {
    sendTotalProxyCount(source);
    source.sendMessage(
        TextComponent.builder("To view all players on servers, use ", TextColor.YELLOW)
            .append("/glist all", TextColor.DARK_AQUA)
            .append(".", TextColor.YELLOW)
            .build());
  } else if (args.length == 1) {
    String arg = args[0];
    if (arg.equalsIgnoreCase("all")) {
      for (RegisteredServer server : server.getAllServers()) {
        sendServerPlayers(source, server, true);
      }
      sendTotalProxyCount(source);
    } else {
      Optional<RegisteredServer> registeredServer = server.getServer(arg);
      if (!registeredServer.isPresent()) {
        source.sendMessage(
            TextComponent.of("Server " + arg + " doesn't exist.", TextColor.RED));
        return;
      }
      sendServerPlayers(source, registeredServer.get(), false);
    }
  } else {
    source.sendMessage(TextComponent.of("Too many arguments.", TextColor.RED));
  }
}
 
Example #21
Source File: ConnectionRequestResults.java    From Velocity with MIT License 5 votes vote down vote up
Impl(Status status, @Nullable Component component,
    RegisteredServer attemptedConnection, boolean safe) {
  this.status = status;
  this.component = component;
  this.attemptedConnection = attemptedConnection;
  this.safe = safe;
}
 
Example #22
Source File: VelocityPlugin.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Iterator<String> getRandomPlayers(String location) {
    Optional<RegisteredServer> server = proxy.getServer(location);
    if (!server.isPresent()) {
        return null;
    }

    ArrayList<String> result = new ArrayList<>();
    for (Player player : server.get().getPlayersConnected()) {
        result.add(player.getUsername());
    }

    return Randoms.shuffle(result).iterator();
}
 
Example #23
Source File: ConnectionRequestResults.java    From Velocity with MIT License 4 votes vote down vote up
@Override
public RegisteredServer getAttemptedConnection() {
  return attemptedConnection;
}
 
Example #24
Source File: VelocityServer.java    From Velocity with MIT License 4 votes vote down vote up
@Override
public Optional<RegisteredServer> getServer(String name) {
  return servers.getServer(name);
}
 
Example #25
Source File: VelocityServer.java    From Velocity with MIT License 4 votes vote down vote up
@Override
public Collection<RegisteredServer> getAllServers() {
  return servers.getAllServers();
}
 
Example #26
Source File: ConnectionRequestResults.java    From Velocity with MIT License 4 votes vote down vote up
public static Impl successful(RegisteredServer server) {
  return plainResult(Status.SUCCESS, server);
}
 
Example #27
Source File: ProtocolDetectorService.java    From ViaVersion with MIT License 4 votes vote down vote up
@Override
public void run() {
    for (final RegisteredServer serv : VelocityPlugin.PROXY.getAllServers()) {
        probeServer(serv);
    }
}
 
Example #28
Source File: ConnectedPlayer.java    From Velocity with MIT License 4 votes vote down vote up
@Override
public RegisteredServer getServer() {
  return toConnect;
}
 
Example #29
Source File: VelocityServer.java    From Velocity with MIT License 4 votes vote down vote up
@Override
public RegisteredServer registerServer(ServerInfo server) {
  return servers.register(server);
}
 
Example #30
Source File: ConnectedPlayer.java    From Velocity with MIT License 4 votes vote down vote up
ConnectionRequestBuilderImpl(RegisteredServer toConnect) {
  this.toConnect = Preconditions.checkNotNull(toConnect, "info");
}