Java Code Examples for org.bukkit.Bukkit#isPrimaryThread()

The following examples show how to use org.bukkit.Bukkit#isPrimaryThread() . 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: MySQLUserDataSource.java    From MCAuthenticator with GNU General Public License v3.0 6 votes vote down vote up
@Override
public UserData getUser(UUID id) throws IOException, SQLException {
    if (Bukkit.isPrimaryThread() && !MCAuthenticator.isReload)
        throw new RuntimeException("Primary thread I/O");
    try (Connection c = pool.getConnection()) {
        PreparedStatement p = c.prepareStatement("SELECT authtype, ip, secret, locked FROM 2FA WHERE uuid = ?;");
        p.setString(1, id.toString().replaceAll("-", ""));
        p.setQueryTimeout(queryTimeout);
        ResultSet rs = p.executeQuery();
        if (rs.next()) {
            return new UpdatableFlagData(updateHook, id,
                    InetAddress.getByName(rs.getString("ip")),
                    rs.getString("secret"),
                    rs.getInt("authtype"),
                    rs.getBoolean("locked"));
        } else {
            return null;
        }
    }
}
 
Example 2
Source File: NametagHandler.java    From NametagEdit with GNU General Public License v3.0 6 votes vote down vote up
public void applyTags() {
    if (!Bukkit.isPrimaryThread()) {
        new BukkitRunnable() {
            @Override
            public void run() {
                applyTags();
            }
        }.runTask(plugin);
        return;
    }

    for (Player online : Utils.getOnline()) {
        if (online != null) {
            applyTagToPlayer(online, false);
        }
    }

    plugin.debug("Applied tags to all online players.");
}
 
Example 3
Source File: BukkitEventDispatcher.java    From BungeePerms with GNU General Public License v3.0 6 votes vote down vote up
@SneakyThrows
private static void runSync(Plugin p, Runnable r, boolean waitfinished)
{
    if (Bukkit.isPrimaryThread())
    {
        r.run();
    }
    else
    {
        int id = Bukkit.getScheduler().runTask(p, r).getTaskId();
        if (waitfinished)
        {
            while (Bukkit.getScheduler().isCurrentlyRunning(id) || Bukkit.getScheduler().isQueued(id))
            {
                Thread.sleep(1);
            }
        }
    }
}
 
Example 4
Source File: PacketListener.java    From ScoreboardStats with MIT License 6 votes vote down vote up
@Override
public void onPacketSending(PacketEvent packetEvent) {
    Player player = packetEvent.getPlayer();
    if (packetEvent.isCancelled() || player instanceof Factory) {
        return;
    }

    PacketContainer packet = packetEvent.getPacket();
    if (packet.hasMetadata("ScoreboardStats")) {
        //it's our own packet
        return;
    }

    UUID playerUUID = player.getUniqueId();

    //handle async packets by other plugins
    if (Bukkit.isPrimaryThread()) {
        ensureMainThread(playerUUID, packet);
    } else {
        PacketContainer clone = packet.deepClone();
        Bukkit.getScheduler().runTask(plugin, () -> ensureMainThread(playerUUID, clone));
    }
}
 
Example 5
Source File: ASkyBlock.java    From askyblock with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the World object for the island world named in config.yml.
 * If the world does not exist then it is created.
 *
 * @return islandWorld - Bukkit World object for the ASkyBlock world
 */
public static World getIslandWorld() {
    if (islandWorld == null) {
        //Bukkit.getLogger().info("DEBUG worldName = " + Settings.worldName);
        //
        if (Settings.useOwnGenerator) {
            islandWorld = Bukkit.getServer().getWorld(Settings.worldName);
            //Bukkit.getLogger().info("DEBUG world is " + islandWorld);
        } else {
            islandWorld = WorldCreator.name(Settings.worldName).type(WorldType.FLAT).environment(World.Environment.NORMAL).generator(new ChunkGeneratorWorld())
                    .createWorld();
        }
        // Make the nether if it does not exist
        if (Settings.createNether) {
            getNetherWorld();
        }
        // Multiverse configuration
        if (!Settings.useOwnGenerator && Bukkit.getServer().getPluginManager().isPluginEnabled("Multiverse-Core")) {
            // Run sync
            if (!Bukkit.isPrimaryThread()) {
                Bukkit.getScheduler().runTask(plugin, ASkyBlock::registerMultiverse);
            } else {
                registerMultiverse();
            }
        }

    }
    // Set world settings
    if (islandWorld != null) {
        islandWorld.setWaterAnimalSpawnLimit(Settings.waterAnimalSpawnLimit);
        islandWorld.setMonsterSpawnLimit(Settings.monsterSpawnLimit);
        islandWorld.setAnimalSpawnLimit(Settings.animalSpawnLimit);
    }

    return islandWorld;
}
 
Example 6
Source File: Metrics.java    From NickNamer with MIT License 5 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JSONObject data) throws Exception {
	if (data == null) {
		throw new IllegalArgumentException("Data cannot be null!");
	}
	if (Bukkit.isPrimaryThread()) {
		throw new IllegalAccessException("This method must not be called from the main thread!");
	}
	HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

	// Compress the data to save bandwidth
	byte[] compressedData = compress(data.toString());

	// Add headers
	connection.setRequestMethod("POST");
	connection.addRequestProperty("Accept", "application/json");
	connection.addRequestProperty("Connection", "close");
	connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
	connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
	connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
	connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

	// Send data
	connection.setDoOutput(true);
	DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
	outputStream.write(compressedData);
	outputStream.flush();
	outputStream.close();

	connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
 
Example 7
Source File: IslandLogic.java    From uSkyBlock with GNU General Public License v3.0 5 votes vote down vote up
public boolean clearFlatland(final CommandSender sender, final Location loc, final int delay) {
    if (loc == null) {
        return false;
    }
    if (delay > 0 && !flatlandFix) {
        return false; // Skip
    }
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            final World w = loc.getWorld();
            final int px = loc.getBlockX();
            final int pz = loc.getBlockZ();
            final int py = 0;
            final int range = Math.max(Settings.island_protectionRange, Settings.island_distance) + 1;
            final int radius = range/2;
            // 5 sampling points...
            if (w.getBlockAt(px, py, pz).getType() == BEDROCK
                    || w.getBlockAt(px+radius, py, pz+radius).getType() == BEDROCK
                    || w.getBlockAt(px+radius, py, pz-radius).getType() == BEDROCK
                    || w.getBlockAt(px-radius, py, pz+radius).getType() == BEDROCK
                    || w.getBlockAt(px-radius, py, pz-radius).getType() == BEDROCK)
            {
                sender.sendMessage(String.format("\u00a7c-----------------------------------\n\u00a7cFlatland detected under your island!\n\u00a7e Clearing it in %s, stay clear.\n\u00a7c-----------------------------------\n", TimeUtil.ticksAsString(delay)));
                new WorldEditClearFlatlandTask(plugin, sender, new CuboidRegion(BlockVector3.at(px-radius, 0, pz-radius),
                        BlockVector3.at(px+radius, 4, pz+radius)),
                        "\u00a7eFlatland was cleared under your island (%s). Take care.").runTaskLater(plugin, delay);
            }
        }
    };
    if (Bukkit.isPrimaryThread()) {
        runnable.run();
    } else {
        plugin.sync(runnable);
    }
    return false;
}
 
Example 8
Source File: MainListener.java    From HolographicDisplays with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler (priority = EventPriority.MONITOR)
public void onChunkLoad(ChunkLoadEvent event) {
	Chunk chunk = event.getChunk();
	
	// Other plugins could call this event wrongly, check if the chunk is actually loaded.
	if (chunk.isLoaded()) {
		
		// In case another plugin loads the chunk asynchronously always make sure to load the holograms on the main thread.
		if (Bukkit.isPrimaryThread()) {
			processChunkLoad(chunk);
		} else {
			Bukkit.getScheduler().runTask(HolographicDisplays.getInstance(), () -> processChunkLoad(chunk));
		}
	}
}
 
Example 9
Source File: BlockingActionManager.java    From LagMonitor with MIT License 5 votes vote down vote up
public void checkBlockingAction(String event) {
    if (!Bukkit.isPrimaryThread()) {
        return;
    }

    logCurrentStack(BLOCKING_ACTION_MESSAGE, event);
}
 
Example 10
Source File: MetricsLite.java    From skUtilities with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JSONObject data) throws Exception {
  if (data == null) {
    throw new IllegalArgumentException("Data cannot be null!");
  }
  if (Bukkit.isPrimaryThread()) {
    throw new IllegalAccessException("This method must not be called from the main thread!");
  }
  HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

  // Compress the data to save bandwidth
  byte[] compressedData = compress(data.toString());

  // Add headers
  connection.setRequestMethod("POST");
  connection.addRequestProperty("Accept", "application/json");
  connection.addRequestProperty("Connection", "close");
  connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
  connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
  connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
  connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

  // Send data
  connection.setDoOutput(true);
  DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
  outputStream.write(compressedData);
  outputStream.flush();
  outputStream.close();

  connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
 
Example 11
Source File: TLocaleLoader.java    From TabooLib with MIT License 5 votes vote down vote up
public static void sendTo(Plugin plugin, String path, CommandSender sender, String... args) {
    TabooLibAPI.debug(plugin, "TLocaleLoader.sendTo: " + plugin + ", path: " + path + ", sender: " + sender + ", args: " + Arrays.asList(args));
    if (Bukkit.isPrimaryThread()) {
        Optional.ofNullable(map.get(plugin.getName())).ifPresent(localeInstance -> localeInstance.sendTo(path, sender, args));
    } else {
        synchronized (TLocaleLoader.class) {
            Optional.ofNullable(map.get(plugin.getName())).ifPresent(localeInstance -> localeInstance.sendTo(path, sender, args));
        }
    }
}
 
Example 12
Source File: ClientControlEvent.java    From AACAdditionPro with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructor for 1.14 and onwards.
 */
protected ClientControlEvent(final Player p, final ModuleType moduleType, final String message)
{
    super(!Bukkit.isPrimaryThread());
    this.player = p;
    this.moduleType = moduleType;
    this.message = message;
}
 
Example 13
Source File: Metrics.java    From MapManager with MIT License 5 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JSONObject data) throws Exception {
	if (data == null) {
		throw new IllegalArgumentException("Data cannot be null!");
	}
	if (Bukkit.isPrimaryThread()) {
		throw new IllegalAccessException("This method must not be called from the main thread!");
	}
	HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

	// Compress the data to save bandwidth
	byte[] compressedData = compress(data.toString());

	// Add headers
	connection.setRequestMethod("POST");
	connection.addRequestProperty("Accept", "application/json");
	connection.addRequestProperty("Connection", "close");
	connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
	connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
	connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
	connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

	// Send data
	connection.setDoOutput(true);
	DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
	outputStream.write(compressedData);
	outputStream.flush();
	outputStream.close();

	connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
 
Example 14
Source File: Metrics.java    From ClaimChunk with MIT License 4 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param plugin Any plugin. It's just used to get a logger instance.
 * @param data   The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(Plugin plugin, JsonObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    if (logSentData) {
        plugin.getLogger().info("Sending data to bStats: " + data.toString());
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    InputStream inputStream = connection.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        builder.append(line);
    }
    bufferedReader.close();
    if (logResponseStatusText) {
        plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
    }
}
 
Example 15
Source File: BStatsMetricsLite.java    From Sentinel with MIT License 4 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param plugin Any plugin. It's just used to get a logger instance.
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(Plugin plugin, JSONObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    if (logSentData) {
        plugin.getLogger().info("Sending data to bStats: " + data.toString());
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    InputStream inputStream = connection.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        builder.append(line);
    }
    bufferedReader.close();
    if (logResponseStatusText) {
        plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
    }
}
 
Example 16
Source File: BStats.java    From DiscordSRV with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param plugin Any plugin. It's just used to get a logger instance.
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(Plugin plugin, JsonObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    if (logSentData) {
        plugin.getLogger().info("Sending data to bStats: " + data.toString());
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    InputStream inputStream = connection.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        builder.append(line);
    }
    bufferedReader.close();
    if (logResponseStatusText) {
        plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
    }
}
 
Example 17
Source File: CStats.java    From TabooLib with MIT License 4 votes vote down vote up
/**
 * Sends the data to the cStats server.
 *
 * @param plugin Any plugin. It's just used to get a logger instance.
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(Plugin plugin, JsonObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    if (logSentData) {
        plugin.getLogger().info("Sending data to cStats: " + data);
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + C_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
        outputStream.write(compressedData);
    }

    StringBuilder builder = new StringBuilder();
    try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            builder.append(line);
        }
    }

    if (logResponseStatusText) {
        plugin.getLogger().info("Sent data to cStats and received response: " + builder);
    }
}
 
Example 18
Source File: Metrics.java    From Harbor with MIT License 4 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param plugin Any plugin. It's just used to get a logger instance.
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(Plugin plugin, JsonObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    if (logSentData) {
        plugin.getLogger().info("Sending data to bStats: " + data.toString());
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    InputStream inputStream = connection.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        builder.append(line);
    }
    bufferedReader.close();
    if (logResponseStatusText) {
        plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
    }
}
 
Example 19
Source File: Metrics.java    From skript-yaml with MIT License 4 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param plugin Any plugin. It's just used to get a logger instance.
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(Plugin plugin, JSONObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    if (logSentData) {
        plugin.getLogger().info("Sending data to bStats: " + data.toString());
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    InputStream inputStream = connection.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        builder.append(line);
    }
    bufferedReader.close();
    if (logResponseStatusText) {
        plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
    }
}
 
Example 20
Source File: Metrics.java    From NametagEdit with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param plugin Any plugin. It's just used to get a logger instance.
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(Plugin plugin, JSONObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    if (logSentData) {
        plugin.getLogger().info("Sending data to bStats: " + data.toString());
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    InputStream inputStream = connection.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        builder.append(line);
    }
    bufferedReader.close();
    if (logResponseStatusText) {
        plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
    }
}